Compare commits

...

2263 Commits

Author SHA1 Message Date
Kannan J c7202c0db5
Bump readme (#12305) 2025-08-24 18:21:52 +05:30
Eric Anderson 028afbe352
xds: Implement equals in WRRLBConfig
Just an is a8de9f0, lack of equals causes cluster_resolver to consider every update a different configuration and restart itself.

Handling NaN should really be prevented with validation, but it looks like that
would lead to yak shaving at the moment.

b/435208946
2025-08-22 08:07:51 -07:00
John Cormie afdbecb235
binder: Move BinderTransport's inner classes to the top level (#12303)
BinderTransport.java was getting too long and deeply nested.

This is a pure refactor with no behavior changes.
2025-08-21 16:08:58 -07:00
MV Shiva 2039266ebc
xds: xdsClient caches transient error for new watchers (#12262) 2025-08-19 21:41:52 +05:30
Jiri Kaplan 43bef65cf9 netty: Support BCJSSE provider in GrpcSslContexts 2025-08-19 07:17:57 -07:00
Eric Anderson 437e03dc98
xds: Avoid PriorityLb re-enabling timer on duplicate CONNECTING (#12289)
Since c4256add4 we no longer fabricate a TRANSIENT_FAILURE update from
children. However, previously that would have set
seenReadyOrIdleSinceTransientFailure = false and prevented future timer
creation. If a LB policy gives extraneous updates with state CONNECTING,
then it was possible to re-create failOverTimer which would then wait
the 10 seconds for the child to finish CONNECTING. We only want to give
the child one opportunity after transitioning out of READY/IDLE.

https://github.com/grpc/proposal/pull/509
2025-08-19 12:53:47 +05:30
Eric Anderson 6462ef9a11 netty: Count sent RST_STREAMs against limit
Http2RstCounterEncoder has to be constructed before
NettyServerHandler/Http2ConnectionHandler so it must be static. Thus the
code/counters were moved into RstStreamCounter which then can be
constructed earlier and shared.

This depends on Netty 4.1.124 for a bug fix to actually call the
encoder:
be53dc3c9a
2025-08-18 07:23:34 -07:00
Eric Anderson 95d16d85c8 Upgrade to Netty 4.1.124.Final
This implicitly disables NettyAdaptiveCumulator (#11284), which can have a
performance impact. We delayed upgrading Netty to give time to rework
the optimization, but we've gone too long already without upgrading
which causes problems for vulnerability tracking.
2025-08-13 14:23:14 -07:00
Sangamesh f50726d32e
android: Clean up android lint and other warnings (#12143)
Worked on clearing the lint warnings (OldTargetApi, ObsoleteSdkInt,
InlinedApi, NewApi)

Fixes #12142
2025-08-11 15:18:01 -07:00
Eric Anderson 06707f7c38 xds: Use a different log name for XdsClientImpl and ControlPlaneClient
Seems like a good time to stop hating ourselves, as that seems to be the
only reason to use the same string.
2025-08-08 14:23:43 -07:00
John Cormie efcdebb904
Introduce a NameResolver for Android's `intent:` URIs (#12248)
Let grpc-binder clients find on-device services by [implicit Intent](https://developer.android.com/guide/components/intents-filters#Types) target URI, lifting the need to hard code a server's package name.
2025-08-07 08:38:44 -07:00
Eric Anderson f30964ab82
Bump versions of dependencies (#12252)
Notably, protobuf to 3.25.8, opentelemetry to 1.52.0. Protobuf in Bazel
has 25.5 in the BCR and it seems better to align the WORKSPACE
with that version. But we can't actually use 25.5 in BCR because it is
incompatible with Bazel 7.
2025-08-06 11:01:45 -07:00
MV Shiva 7040417eee
stub: use the closedTrailers in StatusException (#12259) 2025-08-06 12:24:33 +05:30
camel a40c8cf5a4
binder: Let apps call SecurityPolicy.checkAuthorization() by PeerUid (#12257)
This allows a server with access to PeerUid to check additional application-layer security policy *after* the call itself is authorized by the transport layer. Cross cutting application-layer checks could be done from a ServerInterceptor (RPC method level policy, say). Checks based on the substance of a request message could be done by the individual RPC method implementations themselves.
2025-08-05 16:47:45 -07:00
Kannan J 8b46ad58c3
Start 1.76.0 development cycle (#12258) 2025-08-05 22:00:39 +05:30
apolcyn d947c80f99
interop-testing: make soak test use logger rather than writing to stderr directly 2025-07-30 09:31:02 -07:00
Eric Anderson 6ffcbd927e Bump Gradle to 8.14.3 and upgrade plugins
The syntax changes adding `=` were to address:
https://docs.gradle.org/8.14.3/userguide/upgrading_version_8.html#groovy_space_assignment_syntax
2025-07-30 08:43:06 -07:00
MV Shiva 36fe276a50
xds: add "resource_timer_is_transient_failure" server feature (#12249) 2025-07-30 17:54:45 +05:30
Benjamin Peterson ba0a7329da
stub: simplify BlockingClientCall infinite blocking (#12217)
Move deadline computation into overloads with finite timeouts. Blocking calls without timeouts now do not have to read the clock.
2025-07-29 09:33:09 -07:00
Eric Anderson 28f14255ce Update README etc to reference 1.74.0 2025-07-29 07:51:17 -07:00
Kannan J 7e982e48a1
Xds: Aggregate cluster fixes (A75) (#12186)
Instead of representing an aggregate cluster as a single cluster whose
priorities come from different underlying clusters, represent an aggregate cluster as an instance of a priority LB policy where each child is a cds LB policy for the underlying
cluster.
2025-07-29 18:06:39 +05:30
MV Shiva c3ef1ab034
xds: Envoy proto sync to (#12224) 2025-07-28 20:56:27 +05:30
Eric Anderson 8f09b96899
bazel: Use jarjar to avoid xds deps (#12243)
Avoiding so many deps will allow us to upgrade the protos without being
forced to upgrade to protobuf-java 4.x. It also removes the remaining
non-bzlmod dependencies.

It'd be really easy to get this wrong, so we do two things 1) mirror the
gradle configuration as much as possible, as that sees a lot of testing,
and 2) run the fake control plane with the _results_ of jarjar. There's
lots of classes that we could mess up, but that at least kicks the tires.

XdsTestUtils.buildRouteConfiguration() was moved to ControlPlaneRule to
stop the unnecessary circular dependency between the classes and to
avoid the many dependencies of XdsTestUtils.

I'm totally hacking java_grpc_library to improve the dependency
situation. Long-term, I think we will stop building Java libraries with
Bazel and require users to rely entirely on Maven Central. That seems to
be the direction Bazel is going and it will greatly simplify the
problems we've seen with protobuf having a single repository for many
languages. So while the hack isn't too bad, I hope we won't have to live
with it long-term.
2025-07-28 12:30:39 +05:30
Kannan J 42e1829b37
xds: Do RLS fallback policy eagar start (#12211)
The resource subscription to the fallback target was done only at the time of falling back, which can cause rpcs to fail. This change makes the fallback target to be subscribed and cached earlier, similar to C++ and go gRPC implementations.
2025-07-24 16:58:32 +05:30
Eric Anderson c4256add4d xds: Align PriorityLB child selection with A56
The PriorityLB predates A56. tryNextPriority() now matches
ChoosePriority() from the gRFC.

The biggest change is waiting on CONNECTING children instead of failing
after the failOverTimer fires. The failOverTimer should be used to start
lower priorities more eagerly, but shouldn't cause the overall
connectivity state to become TRANSIENT_FAILURE on its own. The prior
behavior of creating the "Connection timeout for priority" failing
picker was particularly strange, because it didn't update child's
connectivity state. This previous behavior was creating errors because
of the failOverTimer with no way to diagnose what was going wrong.

b/428517222
2025-07-23 06:38:33 -07:00
Eric Anderson 6ff8ecac09 core: Don't pre-compute DEADLINE_EXCEEDED message for delayed calls
The main reason I made a change here was to fix the tense from the
deadline "will be exceeded in" to "was exceeded after". But we really
don't want to be doing the string formatting unless the deadline is
actually exceeded. There were a few more changes to make some variables
effectively final.
2025-07-22 06:56:02 -07:00
Patrick Strawderman 80217275db
api: Size Sets and Maps correctly in handling of Metadata values to be exchanged during a call (#12229)
Fix HashSet / HashMap initializations to have sufficient capacity allocated based on the number of keys to be inserted, without which it would always lead to a rehash / resize operation.
2025-07-22 09:14:08 +05:30
Eric Anderson 2e96fbf1e8 netty: Associate netty stream eagerly to avoid client hang
In #12185, RPCs were randomly hanging. In #12207 this was tracked down
to the headers promise completing successfully, but the netty stream
was null. This was because the headers write hadn't completed but
stream.close() had been called by goingAway().
2025-07-17 21:55:53 +00:00
George Gensure a37d3eb349 Guarantee missing stream promise delivery
In observed cases, whether RST_STREAM or another failure from netty or
the server, listeners can fail to be notified when a connection yields a
null stream for the selected streamId. This causes hangs in clients,
despite deadlines, with no obvious resolution.

Tests which relied upon this promise succeeding must now change.
2025-07-17 21:55:16 +00:00
Eric Anderson 1fc4ab0bb2 LBs should avoid calling LBs after lb.shutdown()
LoadBalancers shouldn't be called after shutdown(), but RingHashLb could
have enqueued work to the SynchronizationContext that executed after
shutdown(). This commit fixes problems discovered when auditing all LBs
usage of the syncContext for that type of problem.

Similarly, PickFirstLb could have requested a new connection after
shutdown(). We want to avoid that sort of thing too.

RingHashLb's test changed from CONNECTING to TRANSIENT_FAILURE to get
the latest picker. Because two subchannels have failed it will be in
TRANSIENT_FAILURE. Previously the test was using an older picker with
out-of-date subchannelView, and the verifyConnection() was too imprecise
to notice it was creating the wrong subchannel.

As discovered in b/430347751, where ClusterImplLb was seeing a new
subchannel being called after the child LB was shutdown (the shutdown
itself had been caused by RingHashConfig not implementing equals() and
was fixed by a8de9f07ab, which caused ClusterResolverLb to replace its
state):

```
java.lang.NullPointerException
	at io.grpc.xds.ClusterImplLoadBalancer$ClusterImplLbHelper.createClusterLocalityFromAttributes(ClusterImplLoadBalancer.java:322)
	at io.grpc.xds.ClusterImplLoadBalancer$ClusterImplLbHelper.createSubchannel(ClusterImplLoadBalancer.java:236)
	at io.grpc.util.ForwardingLoadBalancerHelper.createSubchannel(ForwardingLoadBalancerHelper.java:47)
	at io.grpc.util.ForwardingLoadBalancerHelper.createSubchannel(ForwardingLoadBalancerHelper.java:47)
	at io.grpc.internal.PickFirstLeafLoadBalancer.createNewSubchannel(PickFirstLeafLoadBalancer.java:527)
	at io.grpc.internal.PickFirstLeafLoadBalancer.requestConnection(PickFirstLeafLoadBalancer.java:459)
	at io.grpc.internal.PickFirstLeafLoadBalancer.acceptResolvedAddresses(PickFirstLeafLoadBalancer.java:174)
	at io.grpc.xds.LazyLoadBalancer$LazyDelegate.activate(LazyLoadBalancer.java:64)
	at io.grpc.xds.LazyLoadBalancer$LazyDelegate.requestConnection(LazyLoadBalancer.java:97)
	at io.grpc.util.ForwardingLoadBalancer.requestConnection(ForwardingLoadBalancer.java:61)
	at io.grpc.xds.RingHashLoadBalancer$RingHashPicker.lambda$pickSubchannel$0(RingHashLoadBalancer.java:440)
	at io.grpc.SynchronizationContext.drain(SynchronizationContext.java:96)
	at io.grpc.SynchronizationContext.execute(SynchronizationContext.java:128)
	at io.grpc.xds.client.XdsClientImpl$ResourceSubscriber.onData(XdsClientImpl.java:817)
```
2025-07-17 12:56:33 +00:00
MV Shiva 6935d3a115
Revert "xds: add "resource_timer_is_transient_failure" server feature (#12063)" (#12228) 2025-07-17 11:35:34 +05:30
MV Shiva d7d70c6905
xds: cncf/xds proto sync to 2025-05-02 (#12225) 2025-07-17 10:26:12 +05:30
Kannan J d352540a02
api: Add more Javadoc for NameResolver.Listener2 interface (#12220) 2025-07-16 14:39:43 +05:30
MV Shiva 5a8326f1c7
xds: add "resource_timer_is_transient_failure" server feature (#12063) 2025-07-15 15:33:02 +05:30
Eric Anderson a8de9f07ab xds: Implement equals in RingHashConfig
Lack of equals causes cluster_resolver to consider every update a
different configuration and restart itself.

b/430347751
2025-07-14 14:06:15 +00:00
Eric Anderson 9d191b31b5 xds: Check isHttp11ProxyAvailable in equals()
This fixes an equals/hashCode bug introduced in 12197065fe.

Discovered when investigating b/430347751
2025-07-14 14:05:35 +00:00
Richard Belleville 01bd63d88f
Remove inactive maintainers (#12187) 2025-07-11 15:07:00 -07:00
John Cormie 94532a6b56
binder: Introduce server pre-authorization (#12127)
grpc-binder clients authorize servers by checking the UID of the sender of the SETUP_TRANSPORT Binder transaction against some SecurityPolicy. But merely binding to an unauthorized server to learn its UID can enable "keep-alive" and "background activity launch" abuse, even if security policy ultimately decides the connection is unauthorized. Pre-authorization mitigates this kind of abuse by looking up and authorizing a candidate server Application's UID before binding to it. Pre-auth is especially important when the server's address is not fixed in advance but discovered by PackageManager lookup.
2025-07-10 14:14:36 -07:00
Eric Anderson 6dfa03c51c
core: grpc-timeout should always be positive (#12201)
PROTOCOL-HTTP2.md specifies "TimeoutValue → {positive integer as ASCII
string of at most 8 digits}". Zero is not positive, so it should be
avoided. So make sure timeouts are at least 1 nanosecond instead of 0
nanoseconds.

grpc-go recently began disallowing zero timeouts in
https://github.com/grpc/grpc-go/pull/8290 which caused a regression as
grpc-java can generate such timeouts. Apparently no gRPC implementation
had previously been checking for zero timeouts.

Instead of changing the max(0) to max(1) everywhere, just move the max
handling into TimeoutMarshaller, since every caller of TIMEOUT_KEY was
doing the same max() handling.

Before fd8fd517d (in 2016!), grpc-java actually behaved correctly, as it
failed RPCs with timeouts "<= 0". The commit changed the handling to the
max(0) handling we see now.

b/427338711
2025-07-03 11:44:04 +05:30
Abhishek Agrawal 919370172d
census: APIs for stats and tracing (#12050) 2025-07-01 20:44:28 +05:30
Eric Anderson ca99a8c478 Fix RLS regressions from XdsDepMan conversion
297ab05ef converted CDS to XdsDependencyManager. This caused three
regressions:

 * CdsLB2 as a RLS child would always fail with "Unable to find
   non-dynamic root cluster" because is_dynamic=true was missing in
   its service config
 * XdsNameResolver only propagated resolution updates when the clusters
   changed, so a CdsUpdate change would be ignored. This caused a hang
   for RLS even with is_dynamic=true. For non-RLS the lack config update
   broke the circuit breaking psm interop test. This would have been
   more severe if ClusterResolverLb had been converted to
   XdsDependenceManager, as it would have ignored EDS updates
 * RLS did not propagate resolution updates, so CdsLB2 even with
   is_dynamic=true the CdsUpdate for the new cluster would never arrive,
   causing a hang

b/428120265
b/427912384
2025-06-30 14:23:32 +00:00
John Cormie 2ee4f9b488
AndroidComponentAddress constructor can be private. (#12188) 2025-06-27 10:58:48 +05:30
John Cormie 74aee11389
Clarify requirements for creating a cross-user Channel. (#12181)
The @SystemApi runtime visibility requirement isn't really new. It has always been implicit in the required INTERACT_ACROSS_USERS permission, which (in production) can only be held by system apps.

The SDK_INT >= 30 requirement was also always present, via @RequiresApi() on  BinderChannelBuilder#bindAsUser. This change just updates its replacement APIs (AndroidComponentAddress and TARGET_ANDROID_USER) to require it too.
2025-06-26 17:43:13 -07:00
vimanikag 64322c3243
11243: RLS cleanups (#12085) 2025-06-25 10:55:00 +05:30
Eric Anderson af7efeb9f5 core: Rely on ping-pong for flow control testing
The previous code did a ping-pong to make sure the transport had enough
time to process, but then proceeded to sleep 5 seconds. That sleep would
have been needed without the ping-pong, but with the ping-pong we are
confident all events have been drained from the transport. Deleting the
unnecessary sleeps saves 10 seconds, for each of the 9 instances of this
test.
2025-06-25 04:52:46 +00:00
Eric Anderson ebc6d3e932 Start 1.75.0 development cycle 2025-06-25 04:52:17 +00:00
Eric Anderson d374b26b68 xds: Disable LOGICAL_DNS in XdsDepMan until used
ClusterResolverLb is still doing DNS itself, so disable it in XdsDepMan
until that migration has finished. EDS is fine in XdsDepman, because
XdsClient will share the result with ClusterResolverLb.
2025-06-24 14:56:16 +00:00
MV Shiva f99b2aaef8
release: Migrate artifacts publishing from legacy OSSRH to Central Portal (#12156) 2025-06-24 10:12:35 +05:30
John Cormie 30d40a6179
binder: Cancel checkAuthorization() request if still pending upon termination (#12167) 2025-06-23 12:51:40 -07:00
John Cormie 9a6bdc70af
download maven using archive/permalink url (#12169) 2025-06-23 12:00:25 -07:00
Kun Zhang e6e7bcadaf
binder: stops emulating for 21/22 Lollipop in tests
See cl/769936336 internally
2025-06-18 14:47:24 -07:00
John Cormie 922dc8a999
Mark a few test helper methods as @CanIgnoreReturnValue (#12162) 2025-06-18 10:59:21 +05:30
Eric Anderson d2d8ed8efa xds: Add logical dns cluster support to XdsDepManager
ClusterResolverLb gets the NameResolverRegistry from
LoadBalancer.Helper, so a new API was added in NameResover.Args to
propagate the same object to the name resolver tree.

RetryingNameResolver was exposed to xds. This is expected to be
temporary, as the retrying is being removed from ManagedChannelImpl and
moved into the resolvers. At that point, DnsNameResolverProvider would
wrap DnsNameResolver with a similar API to RetryingNameResolver and xds
would no longer be responsible.
2025-06-17 22:14:20 +00:00
Eric Anderson f07eb47cac
util: Deliver addresses in a random order in MultiChildLb
This should often not matter much, but in b/412468630 it was cleary
visible that child creation order can skew load for the first batch of
RPCs. This doesn't solve all the cases, as further-away backends will
still be less likely chosen initially and it is ignorant of the LB
policy. But this doesn't impact correctness, is easy, and is one fewer
cases to worry about.
2025-06-17 07:14:32 -07:00
Eric Anderson 2604ce8a55 xds: XdsNR should be subscribing to clusters with XdsDepManager
This is missing behavior defined in gRFC A74:

> As per gRFC A31, the ConfigSelector gives each RPC a ref to the
> cluster that was selected for it to ensure that the cluster is not
> removed from the xds_cluster_manager LB policy config before the RPC
> is done with its LB picks. These cluster refs will also hold a
> subscription for the cluster from the XdsDependencyManager, so that
> the XdsDependencyManager will not stop watching the cluster resource
> until the cluster is removed from the xds_cluster_manager LB policy
> config.

Without the logic, RPCs can race and see the error:

> INTERNAL: CdsLb for cluster0: Unable to find non-dynamic root cluster

Fixes #12152. This fixes the regression introduced in 297ab05e
2025-06-17 13:36:24 +00:00
vimanikag 1c43098990
util: OutlierDetection should use Ticker, not TimeProvider (#12110)
TimeProvider provides wall time. That can move forward and backward as time is adjusted. OutlierDetection is measuring durations, so it should use a monotonic clock.

Fixes #11622
2025-06-16 07:47:36 -07:00
Eric Anderson d5b4fb51c2 xds: Support tracking non-xds resources in XdsDepManager
This will be used for logical dns clusters as part of gRFC A74. Swapping
to EnumMap wasn't really necessary, but was easy given the new type
system.

I can't say I'm particularly happy with the name of the new
TrackedWatcher type, but XdsConfigWatcher prevented using "Watcher"
because it won't implement the new interface, and ResourceWatcher
already exists in XdsClient. So we have TrackedWatcher, WatcherTracer,
TypeWatchers, and TrackedWatcherType.
2025-06-16 14:32:27 +00:00
Eric Anderson 8974a306af
util: Mark OutlierDetectionLb classes final
None of these classes were intended to be extended. Even non-public
classes need final to prevent mocks from doing horrible things.
2025-06-13 10:52:00 -07:00
Eric Anderson d88ef97a87 core: Remove RetryingNR.RESOLUTION_RESULT_LISTENER_KEY
It was introduced in fcb5c54e4 because at the time we didn't change the
API to communicate the status. When onResult2() was introduced in
90d0fabb1 this hack stopped being necessary.
2025-06-13 15:20:10 +00:00
Eric Anderson 240f731e00 xds: Avoid changing cache when watching children in XdsDepManager
The watchers can be completely regular, so the base class can do the
cache management while the subclasses are only concerned with
subscribing to children.
2025-06-13 15:18:14 +00:00
MV Shiva 26bd0eee47
core: Use lazy message formatting in checkState (#12144) 2025-06-13 12:30:13 +05:30
David Sanderson 6f69363d90
bazel: Migrate java_grpc_library to use DefaultInfo (#12148)
We here address the following obstacles in grpc-java to using Bazel's
--incompatible_disable_target_default_provider_fields flag:

```
ERROR: /private/var/tmp/_bazel_dws/7fd3cd5077fbf76d9e2ae421c39ef7ed/external/googleapis+/google/devtools/build/v1/BUILD.bazel:81:18: in _java_grpc_library rule @@googleapis+//google/devtools/build/v1:build_java_grpc:
Traceback (most recent call last):
        File "/private/var/tmp/_bazel_dws/7fd3cd5077fbf76d9e2ae421c39ef7ed/external/grpc-java+/java_grpc_library.bzl", line 94, column 30, in _java_rpc_library_impl
                args.add(toolchain.plugin.files_to_run.executable, format = "--plugin=protoc-gen-rpc-plugin=%s")
Error: Accessing the default provider in this manner is deprecated and will be removed soon. It may be temporarily re-enabled by setting --incompatible_disable_target_default_provider_fields=false. See https://github.com/bazelbuild/bazel/issues/20183 for details.
ERROR: /private/var/tmp/_bazel_dws/7fd3cd5077fbf76d9e2ae421c39ef7ed/external/googleapis+/google/devtools/build/v1/BUILD.bazel:81:18: Analysis of target '@@googleapis+//google/devtools/build/v1:build_java_grpc' failed
ERROR: Analysis of target '//src:bazel' failed; build aborted: Analysis failed
```
2025-06-12 08:43:23 -07:00
Eric Anderson 6cc2ff1ced util: In OutlierDetectionLb, don't box longs if they can't be null
Changed the builder pattern to pass the builder to the constructor,
since I was changing almost all the arguments of the constructor anyway.
2025-06-12 04:02:40 +00:00
Eric Anderson 13fe008044
rls: Refactor estimatedSizeBytes updates (#12145)
Just use a regular method instead of reusing the EvictionListener API.
Fix a few comments as well. Both of these changes were based on review
comments to pre-existing code in #11203.

Contributes to #11243
2025-06-12 09:31:19 +05:30
John Cormie 30f6a4db77
google-java-format a line that was too long (#12147) 2025-06-11 12:19:19 -07:00
Eric Anderson 297ab05efe
xds: Convert CdsLb to XdsDepManager
I noticed we deviated from gRFC A37 in some ways. It turned out those
were added to the gRFC later in https://github.com/grpc/proposal/pull/344:
- NACKing empty aggregate clusters
- Failing aggregate cluster when children could not be loaded
- Recusion limit of 16. We had this behavior already, but it was
  ascribed to matching C++

There's disagreement on whether we should actually fail the aggregate
cluster for bad children, so I'm preserving the pre-existing behavior
for now.

The code is now doing a depth-first leaf traversal, not breadth-first.
This was odd to see, but the code was also pretty old, so the reasoning
seems lost to history. Since we haven't seen more than a single level of
aggregate clusters in practice, this wouldn't have been noticed by
users.

XdsDependencyManager.start() was created to guarantee that the callback
could not be called before returning from the constructor. Otherwise
XDS_CLUSTER_SUBSCRIPT_REGISTRY could potentially be null.
2025-06-11 11:56:13 -07:00
MV Shiva a16d655919
compiler: generate blocking v2 unary calls that throw StatusException (#12126) 2025-06-10 10:31:03 +05:30
Eric Anderson 6afacf589e xds: Don't cache rdsName in XdsDepManager
We can easily compute the rdsName and avoiding the state means we don't
need to override onResourceDoesNotExist() to keep the cache in-sync with
the config.
2025-06-09 14:13:59 +00:00
Eric Anderson 4ee662fbcf xds: cancelled=true on watch close in XdsDepManager
1fd29bc80 replaced cancelWatcher() with watcher.close(). But setting
cancelled was missing. Because the config update checks for shutdown,
the cancelled flag no longer avoids exceptions. But it seems best to
continue avoiding any processing after close to avoid surprises.
2025-06-09 14:13:41 +00:00
Eric Anderson 1fd29bc804 xds: Use tracing GC in XdsDepManager
Reference counting doesn't release cycles, so swap to a tracing garbage
collector. This greatly simplifies the code as well, as diffing is no
longer necessary. (If vanilla reference counting was used, diffing
wouldn't have been necessary either as you just increment all the new
objects and decrement the old ones. But that doesn't work when use a set
instead of an integer.)
2025-06-06 08:43:35 -07:00
eshitachandwani dc192f5c5e
Create SPIFFE tests config (#12133) 2025-06-06 19:24:27 +05:30
John Cormie c206428749
binder: Rationalize @ThreadSafe-ty of BinderTransport. (#12130)
- Use @BinderThread to document restrictions on methods and certain fields.
- Make TransactionHandler non-public since only Android should call it.
- Replace an unnecessary AtomicLong with a plain old long.
2025-06-05 19:07:59 -07:00
Eric Anderson 4cd7881086 xds: Fix XdsDepManager aggregate cluster child ordering and loop detection
The children of aggregate clusters have a priority order, so we can't
ever throw them in an ordinary set for later iteration.

This now detects recusion limits only after subscribing, but that
matches our existing behavior in CdsLoadBalancer2. We don't get much
value detecting the limit before subscribing and doing so makes watcher
types more different.

Loops are still a bit broken as they won't be unwatched when orphaned,
as they will form a reference loop. In CdsLoadBalancer2, duplicate
clusters had duplicate watchers so there was single-ownership and
reference cycles couldn't form. Fixing that is a bigger change.

Intermediate aggregate clusters are now included in XdsConfig, just for
simplicity. It doesn't hurt anything whether they are present or
missing. but it required updates to some tests.
2025-06-05 08:43:02 -07:00
John Cormie 4c73999102
Move all test helper classes out of AbstractTransportTest so they can be used elsewhere (#12125) 2025-06-05 15:39:51 +05:30
Eric Anderson 482dc5c1c3
xds: Don't allow hostnames in address field (#12123)
* xds: Don't allow hostnames in address field

gRFC A27 specifies they must be IPv4 or IPv6 addresses. Certainly doing
a DNS lookup hidden inside the config object is asking for trouble.

The tests were accidentally doing a lot of failing DNS requests greatly
slowing them down. On my desktop, which made the problem most obvious
with five search paths in /etc/resolv.conf, :grpc-xds:test decreased
from 66s to 29s. The majority of that is XdsDependencyManagerTest which
went from 33s to .1s, as it generated a UUID for the in-process
transport each test and then used it as a hostname, which defeated
Java's DNS (negative) cache. The slowness was noticed because
XdsDependencyManagerTest should have run quickly as a single thread
without I/O, but was particularly slow on my desktop.

The cleanup caused me to audit serverName and the weird places it went.
I think some of them were tricks for XdsClientFallbackTest to squirrel
away something distinguishing, although reusing the serverName is asking
for confusion as is including the tricks in "shared" utilities.
XdsClientFallbackTest does have some non-trivial changes, but this seems
to fix some pre-existing bugs in the tests.

* Add failing hostname unit test
2025-06-05 15:37:49 +05:30
Eric Anderson efe9ccc22c
xds: Non-SOTW resources need onError() callbacks, too (#12122)
SOTW is unique in that it can become absent after being found. But if we
NACK when initially loading the resource, we don't want to delay, depend
on the resource timeout, and then give a poor error.

This was noticed while adding the EDS restriction that address is not a
hostname and some tests started hanging instead of failing quickly.
2025-06-03 12:02:02 +05:30
Eric Anderson 48d08e643e
xds: Remove EDS maybePublishConfig() avoidance in XdsDepManager (#12121)
The optimization makes the code more complicated. Yes, we know that
maybePublishConfig() will do no work because of an outstanding watch,
but we don't do this for other new watchers created and doing so would
just make the code more bug-prone. This removes a difference in how
different watcher types are handled.
2025-06-03 11:52:38 +05:30
Eric Anderson 6bad600592
xds: Use getWatchers more often in XdsDepManager
This provides better type and missing-map handling. Note that
getWatchers() now implicitly creates the map if it doesn't exist,
instead of just returning an empty map. That makes it a bit easier to
use and more importantly avoids accidents where a bug tries to modify
the immutable map.
2025-06-02 06:42:31 -07:00
MV Shiva 379fbaa380
Update README etc to reference 1.73.0 (#12108) 2025-06-02 15:37:11 +05:30
Eric Anderson 8044a56ad2
xds: Remove timeouts from XdsDepManagerTest (#12114)
The tests are using FakeClock and inprocess transport with direct executor, so all operations should run in the test thread.
2025-06-02 12:25:27 +05:30
Eric Anderson 142e378cea
xds: Improve shutdown handling of XdsDepManager
The most important change here is to handle subscribeToCluster() calls
after shutdown(), and preventing the internal state from being heavily
confused as the assumption is there are no watchers after shutdown().

ClusterSubscription.closed isn't strictly necessary, but I don't want
the code to depend on double-deregistration being safe.
maybePublishConfig() isn't being called after shutdown(), but adding the
protection avoids a class of bugs that would cause channel panic.
2025-05-30 09:00:27 -07:00
Alex Panchenko 22cf7cf2ac
tests: Replace usages of deprecated junit ExpectedException with assertThrows (#12103) 2025-05-30 10:55:37 +05:30
Sangamesh 83538cdae3
cronet: Delete TODO for User-Agent on CronetEngine
gRPC doesn't create the CronetEngine, so even though streaming is
observing the CronetEngine's User-Agent, we don't have control of that.
In addition, CronetEngines are commonly shared between gRPC and normal
HTTP traffic, so we don't actually expect users to set gRPC in engine's
user agent. The existing behavior seems to be working as well as
feasible.

Fixes #11582
2025-05-27 10:52:47 -07:00
Eric Anderson d124007ff4
kokoro: Don't run grpc codegen in android-interop (#12098)
android-interop has been failing to build since 46485c8 because it
didn't have cmake installed and defined LDFLAGS/CXXFLAGS with pkg-config
before make_dependencies.sh had been run.

Android-interop didn't verify the codegen is up-to-date. Building the
codegen was just a relic from when android was its own separate gradle
build. Avoiding codegen means we don't have to compile absl/protobuf and
have a C++ toolchain.
2025-05-26 08:42:58 +05:30
Kannan J 46485c8b62
Upgrade Protobuf C++ to 22.5 (#11961) 2025-05-23 12:24:14 +05:30
Michael Lumish 9406d3b2a0 Rename PSM interop fallback test suite to light 2025-05-22 15:43:25 -07:00
MV Shiva 9d439d4a44
xds: Add GcpAuthenticationFilter to FilterRegistry (#12075) 2025-05-22 16:22:41 +05:30
Eric Anderson f8700a13ad
compiler: Default to @generated=omit (#12080)
After many years of issue 9179 being open, there's been nothing to show
that we need the javax.annotations.Generated annotation. Most tools use
file paths and a few check for annotations with "Generated" in the name.
ErrorProne has a few that check for javax.annotations.Generated, but
only UnnecessarilyFullyQualified looks like it'd be a problem and it is
disabled by default. We're not getting any more information, no users
have reported issues with `@generated=omit`, and the existing dependency
is annoying users, so just drop it.

Given we will still retain the GrpcGenerated annotation, it seems highly
likely things are already okay. Even if there are problems they would
probably be addressed by adding a io.grpc.stub.annotations.Generated
annotation or small tweaks. In the short-term, (non-Bazel) users can use
`@generated=javax`, but long-term we could consider removing the option
assuming we've resolved any outstanding issues.

We will want to update the examples and the README to remove the
org.apache.tomcat:annotations-api dependency after the next release.

Fixes #9179
2025-05-21 22:49:30 +05:30
Luwei Ge 2fb09578a8
xds: enableSpiffe also checks the new env var per gRFC-A87 2025-05-19 12:50:25 -07:00
Gregory Cooke 480640dc2f
alts: add experimental keepalive (#12076) 2025-05-19 08:30:10 -07:00
Abhishek Agrawal b88536a17d
kokoro: add cloud run tests config (#12065)
kokoro: add cloud run tests config
2025-05-15 10:59:52 +05:30
Eric Anderson b089761486
xds: Enable least request by default (#12054)
Enable least request by default.

It has seen good testing by users and behaved as expected.

Fixes #11996
2025-05-14 13:23:37 +05:30
MV Shiva 59adeb9d47
Start 1.74.0 development cycle (#12061) 2025-05-13 17:15:36 +05:30
vinodhabib 6baac45bd2
xds: Fix pretty-print of Cluster with WrrLocality and LB policies (#12037) 2025-05-12 12:44:14 +05:30
John Cormie 454f1c5c6a
binder: Create a Robolectric version of BinderTransportTest (#12057)
This version runs way faster than BinderTransportTest and doesn't require an actual Android device/emulator. It'll allow future tests to simulate things that are difficult/impossible on real Android, at the price of some realism.
2025-05-09 14:57:59 -07:00
John Cormie 64fe061ccd
Simplify RobolectricBinderSecurityTest (#12058)
- Use INSTRUMENTATION_TEST @LooperMode to avoid custom Executors and idleLoopers() toil.
- No android.app.Service is actually needed with Robolectric.
2025-05-09 14:52:12 -07:00
Eric Anderson 80cc988b3c
xds: Use acceptResolvedAddresses() for WeightedTarget children (#12053)
Convert the tests to use acceptResolvedAddresses() as well.
2025-05-08 11:34:16 +05:30
Eric Anderson 3f5fdf1266
core: Remove unnecessary SuppressWarnings("deprecation") (#12052) 2025-05-07 10:14:48 +05:30
Eric Anderson be0247f501 Bump com.google.protobuf gradle plugin to 0.9.5
The plugin now outputs to "generated/sources". The IDE configuration
explicitly adding the folders to the source sets hasn't been needed for
some years.
2025-05-06 06:20:33 -07:00
Kim Jin Young 12aaf88d86
Fix comment's typo (#12045) 2025-05-05 22:32:31 +05:30
Eric Anderson 25199e9df9
xds: XdsDepManager should ignore updates after shutdown
This prevents a NPE and subsequent channel panic when trying to build a
config (because there are no watchers, so waitingOnResource==false)
without any listener and route.
```
java.lang.NullPointerException: Cannot invoke "io.grpc.xds.XdsDependencyManager$RdsUpdateSupplier.getRdsUpdate()" because "routeSource" is null
    at io.grpc.xds.XdsDependencyManager.buildUpdate(XdsDependencyManager.java:295)
    at io.grpc.xds.XdsDependencyManager.maybePublishConfig(XdsDependencyManager.java:266)
    at io.grpc.xds.XdsDependencyManager$EdsWatcher.onChanged(XdsDependencyManager.java:899)
    at io.grpc.xds.XdsDependencyManager$EdsWatcher.onChanged(XdsDependencyManager.java:888)
    at io.grpc.xds.client.XdsClientImpl$ResourceSubscriber.notifyWatcher(XdsClientImpl.java:929)
    at io.grpc.xds.client.XdsClientImpl$ResourceSubscriber.lambda$onData$0(XdsClientImpl.java:837)
    at io.grpc.SynchronizationContext.drain(SynchronizationContext.java:96)
```

I think this fully-fixes the problem today, but not tomorrow.
subscribeToCluster() is racy as well, but not yet used.

This was noticed when idleTimeout was firing, with some other code
calling getState(true) to wake the channel back up. That may have made
this panic more visible than it would be otherwise, but that has not
been investigated.

b/412474567
2025-04-23 09:18:08 -07:00
Kannan J 7952afdd56
Add some documentation to StatusOr.equals regarding how underlying statuses are compared, to avoid any confusion, as suggested in issue #11949. (#12036)
Add some documentation to StatusOr.equals regarding how underlying statuses are compared, to avoid any confusion, as suggested in issue #11949.
2025-04-23 18:42:24 +05:30
Abhishek Agrawal 6cd007d0d0
xds: add the missing xds.authority metric (#12018)
This completes the [XDS client metrics](https://github.com/grpc/proposal/blob/master/A78-grpc-metrics-wrr-pf-xds.md#xdsclient) by adding the remaining grpc.xds.authority metric.
2025-04-22 14:34:51 +05:30
Eric Anderson 9619453799
Implement grpc.lb.backend_service optional label
This completes gRFC A89. 7162d2d66 and fc86084df had already implemented
the LB plumbing for the optional label on RPC metrics. This observes the
value in OpenTelemetry and adds it to WRR metrics as well.

https://github.com/grpc/proposal/blob/master/A89-backend-service-metric-label.md
2025-04-21 06:17:43 -07:00
Abhishek Agrawal 53de8a72ca
Update README etc to reference 1.72.0 (#12025) 2025-04-17 17:37:08 +05:30
MV Shiva 7a08fdb7f9
xds: float LRU cache across interceptors (#11992) 2025-04-17 07:26:40 +05:30
Kurt Alfred Kluever 84bd01454b context: Remove mention of "epoch" from Ticker.nanoTime() javadocs, plus other minor touchups
In Java, when people hear "epoch", they think "unix epoch".

cl/747082451
2025-04-15 13:00:35 -07:00
Eric Anderson 65d0bb8a4d
xds: Enable deprecation warnings
The security code referenced fields removed from gRFC A29 before it was
finalized.

Note that this fixes a bug in CommonTlsContextUtil where
CombinedValidationContext was not checked. I believe this was the only
location with such a bug as I audited all non-test usages of
has/getValidationContext() and confirmed they have have a corresponding
has/getCombinedValidationContext().
2025-04-11 08:25:21 -07:00
Eric Anderson f79ab2f16f api: Remove deprecated SubchannelPicker.requestConnection()
It has been deprecated since cec9ee368, six years ago. It was replaced
with LoadBalancer.requestConnection().
2025-04-09 12:51:33 -07:00
Eric Anderson a6aec2769e auth: Use pre-existing private key in test
Generating a KeyPair is very expensive when running with TSAN, because
TSAN keeps the JVM in interpreted mode. This speeds up the test running
on my desktop from .368s to .151s; faster, but nobody cares. With TSAN,
the speedup is from 150-500s to 4-6s. Within Google the test was timing
out because it was taking so long. While we can increase the timeout,
it seems better to speed up the test in this easy way.
2025-04-08 11:03:45 -07:00
Eric Anderson 2db4852e23 core: Loop over interceptors when computing effective interceptors
A post-merge review of 8516cfef9 suggested this change and the comment
had been lost in my inbox.
2025-04-07 21:33:55 -07:00
jiangyuan 54d37839a3
stub: trailersFromThrowable() metadata should be copied (#11979)
If the same exception is passed to multiple RPCs, then the results will
race.

Fixes #11973
2025-04-07 14:34:57 -07:00
Eric Anderson aae52de3b8 stub: Add RunWith(JUnit4) to support varied environments
Some JUnit environments require the RunWith annotation. Notably
Blaze/Bazel needs it.
2025-04-04 12:28:37 -07:00
Kannan J a13fca2bf2
xds: ClusterResolverLoadBalancer handle update for both resolved addresses and errors via ResolutionResult (#11997) 2025-04-04 22:08:29 +05:30
Alex Panchenko edc2bf7346
stub: Utility method StreamObservers.nextAndComplete() that does both onNext and onComplete (#11778) 2025-04-04 19:39:35 +05:30
Eric Anderson 5ca4d852ae
core: Avoid Set.removeAll() when passing a possibly-large List (#11994)
See #11958
2025-04-04 17:46:37 +05:30
Abhishek Agrawal d4c46a7f1f
refactor: prevents global stats config freeze in ConfiguratorRegistry.getConfigurators() (#11991) 2025-04-04 11:23:08 +05:30
MV Shiva c8d1e6e39c
xds: listener type validation (#11933) 2025-04-03 11:22:26 +05:30
MV Shiva 84c7713b2f
xds: propagate audience from cluster resource in gcp auth filter (#11972) 2025-04-02 16:29:55 +05:30
Eric Anderson 908f9f19cd
core: Delete the long-deprecated GRPC_PROXY_EXP (#11988)
"EXP" stood for experimental and all documentation that referenced it made it clear it was experimental. It's been some years since we started logging a message when it was used to say it will be deleted. There's no time like the present to delete it.
2025-04-02 16:24:32 +05:30
Eric Anderson 8ca7c4ef1f
core: Delete stale SuppressWarnings("deprecated") for ATTR_LOAD_BALANCING_CONFIG (#11982)
ATTR_LOAD_BALANCING_CONFIG was deleted in bf7a42dbd.
2025-04-02 16:22:00 +05:30
Kannan J c28a7e3e06
okhttp: Per-rpc call option authority verification (#11754) 2025-04-02 10:10:41 +05:30
Abhishek Agrawal 8f6a16f846
Start 1.73.0 development cycle (#11987) 2025-04-01 16:27:39 +05:30
Eric Anderson 2448c8b6b9
util: Replace BUFFER_PICKER with FixedResultPicker
I think at some point there were more usages in the tests. But now it
is pretty easy.

PriorityLb.ChildLbState.picker is initialized to
FixedResultPicker(NoResult). So now that GracefulSwitchLb is using the
same picker, equals() is able to de-dup an update.
2025-03-28 12:49:36 -07:00
Eric Anderson 2e260a4bbc util: Graceful switch to new LB when leaving CONNECTING
Previously it would wait for the new LB to enter READY. However, that
prevents there being an upper-bound on how long the old policy will
continue to be used. The point of graceful switch is to avoid RPCs
seeing increased latency when we swap config. We don't want it to
prevent the system from becoming eventually consistent.
2025-03-28 15:18:10 +00:00
Alex Panchenko 7507a9ec06
core: Use java.time.Time.getNano in InstantTimeProvider without reflection (#11977)
Fixes #11975
2025-03-26 13:49:21 +05:30
Abhishek Agrawal a332eddc13
fix: cleans up FileWatcherCertificateProvider in XdsSecurityClientServerTest 2025-03-26 11:43:05 +05:30
jiangyuan 350f90e1a3
services: Avoid cancellation exceptions when notifying watchers that already have their connections cancelled (#11934)
Some clients watching health status can cancel their watch and `HealthService` when trying to notify these watchers were getting CANCELLED exception because there was no cancellation  handler set on the `StreamObserver`. This change sets the cancellation handler that removes the watcher from the set of watcher clients to be notified of the health status.
2025-03-25 17:42:28 +05:30
Eric Anderson 3961a923ac
core: Log any exception during panic because of exception
panic() calls a good amount of code, so it could get another exception.
The SynchronizationContext is running on an arbitrary thread and we
don't want to propagate this secondary exception up its stack (to be
handled by its UncaughtExceptionHandler); it we wanted that we'd
propagate the original exception.

This second exception will only be seen in the logs; the first exception
was logged and will be used to fail RPCs.

Also related to http://yaqs/8493785598685872128 and b692b9d26
2025-03-24 14:32:53 -07:00
Ashley Zhang 1958e42370
xds: add support for custom per-target credentials on the transport (#11951) 2025-03-21 15:19:40 -07:00
yifeizhuang 94f8e93691
otel tracing: fix span names (#11974) 2025-03-21 15:19:25 -07:00
Alex Panchenko d60e6fc251
Replace usages of deprecated ExpectedException in grpc-api and grpc-core (#11962) 2025-03-21 13:00:24 +05:30
Eric Anderson d2d72cda83
xds: Expose filter names to filter instances (#11971)
This is to support gRFC A83 xDS GCP Authentication Filter:
> Otherwise, the filter will look in the CDS resource's metadata for a
> key corresponding to the filter's instance name.
2025-03-21 11:01:16 +05:30
Eric Anderson bb120a8cbb xds: Assert XdsNR's cluster ref counting is consistent
It is much harder to debug refcounting problems when we ignore
impossible situations. So make such impossible cases complain loudly so
the bug is obvious.
2025-03-19 13:47:02 -07:00
Eric Anderson bc3c764058 xds: Include XdsConfig as a CallOption
This allows Filters to access the xds configuration for their own
processing. From gRFC A83:

> This data is available via the XdsConfig attribute introduced in A74.
> If the xDS ConfigSelector is not already passing that attribute to the
> filters, it will need to be changed to do so.
2025-03-19 09:04:27 -07:00
Abhishek Agrawal a57c14a51e
refactor: Stops exception allocation on channel shutdown
This fixes #11955.

Stops exception allocation and its propagation on channel shutdown.
2025-03-19 09:27:34 +05:30
Eric Anderson e80c197455
xds: Use XdsDependencyManager for XdsNameResolver
Contributes to the gRFC A74 effort.
https://github.com/grpc/proposal/blob/master/A74-xds-config-tears.md

The alternative to using Mockito's ArgumentMatcher is to use Hamcrest.
However, Hamcrest did not impress me. ArgumentMatcher is trivial if you
don't care about the error message.

This fixes a pre-existing issue where ConfigSelector.releaseCluster
could revert the LB config back to using cluster manager after releasing
all RPCs using a cluster have committed.

Co-authored-by: Larry Safran <lsafran@google.com>
2025-03-18 14:05:01 -07:00
MV Shiva e388ef3975
documentation: upgrade to junit 4.13.2 (#11967) 2025-03-18 18:43:03 +05:30
Dennis Shao b69bd64ce7
Populate the pb::java feature extension to gprc proto plugin (#11885)
Populate the pb::java feature extension to the protoc plugins that require Protobuf Java feature resolution for the  edition.
2025-03-17 18:46:28 +05:30
Alex Panchenko fca1d3cf43
servlet: set description for CANCELLED status (#11927) 2025-03-12 14:09:49 +05:30
MV Shiva 2f52a00364
netty: Swap to UniformStreamByteDistributor (#11954) 2025-03-11 22:39:54 +05:30
Kannan J 2191557582
Update README etc to reference 1.71.0 (#11940) 2025-03-11 16:05:39 +05:30
Arjan Singh Bal 4933cddd00
Fix typo in dualstack example (#11916) 2025-03-11 16:05:05 +05:30
Kannan J 24b9f6ff0d
Update psm-dualstack.cfg (#11950)
120 minutes has not been sufficient, causing frequent VM timeout errors in the test runs: https://testgrid.corp.google.com/grpc-psm-java#v1.67.x&width=20&graph-metrics=test-duration-minutes&include-filter-by-regex=psm-dualstack$
2025-03-10 12:33:45 +05:30
Emmanuel Ferdman 61a110d962
examples: Update in-process sources in examples (#11952)
Update in-process sources location in examples since they have been migrated from core artifacts.
2025-03-10 05:20:20 +00:00
Eric Anderson f3f054a0a4 xds: Log cluster_manager config update before applying config
It is confusing/harder to read the logs when the
activations/deactivations because of the config happen before the log
entry describing the new config.
2025-03-07 14:37:37 -08:00
Eric Anderson d82613a74c
xds: Fix cluster selection races when updating config selector
Listener2.onResult() doesn't require running in the sync context, so
when called from the sync context it is guaranteed not to do its
processing immediately (instead, it schedules work into the sync
context).

The code was doing an update dance: 1) update service config to add new
cluster, 2) update config selector to use new cluster, 3) update service
config to remove old clusters. But the onResult() wasn't being processed
immediately, so the actual execution order was 2, 1, 3 which has a small
window where RPCs will fail. But onResult2() does run immediately. And
since ca4819ac6, updateBalancingState() updates the picker immediately.

cleanUpRoutes() was also racy because it updated the routingConfig
before swapping to the new config selector, so RPCs could fail saying
there was no route instead of the useful error message. Even with the
opposite order, some RPCs may be executing the while loop of
selectConfig(), trying to acquire a cluster. The code unreffed the
clusters before updating the routingConfig, so those RPCs could go into
a tight loop until the routingConfig was updated. Also, once the
routingConfig was updated to EMPTY those RPCs would similarly
see the wrong error message. To give the correct error message,
selectConfig() must fail such RPCs directly, and once it can do that
there's no need to stop using the config selector in error cases. This
has the benefit of fewer moving parts and more consistent threading
among cases.

The added test was able to detect the race 2% of the time. The slower
the code/machine, the more reliable the test failed. ca4819ac6 along
with this commit reduced it to 0 failures in 1000 runs.

Discovered when investigating b/394850611
2025-03-07 10:33:35 -08:00
Eric Anderson ca4819ac6d core: Apply ManagedChannelImpl's updateBalancingState() immediately
ffcc360ba adjusted updateBalancingState() to require being run within
the sync context. However, it still queued the work into the sync
context, which was unnecessary. This re-entering the sync context
unnecessarily delays the new state from being used.
2025-03-06 12:31:10 -08:00
Sergii Tkachenko a6a041e415
xds: Support filter state retention
This PR adds support filter state retention in Java. The mechanism
will be similar to the one described in [A83]
(https://github.com/grpc/proposal/blob/master/A83-xds-gcp-authn-filter.md#filter-call-credentials-cache)
for C-core, and will serve the same purpose. However, the
implementation details are very different due to the different nature
of xDS HTTP filter support in C-core and Java.

### Filter instance lifecycle
#### xDS gRPC clients
New filter instances are created per combination of:
1. `XdsNameResolver` instance,
2. Filter name+typeUrl as configured in 
   HttpConnectionManager (HCM) http_filters.

Existing client-side filter instances are shutdown:
- A single a filter instance is shutdown when an LDS update contains
  HCM that is missing filter configuration for name+typeUrl
  combination of this instance.
- All filter instances when watched LDS resource is missing from an
  LDS update.
- All filter instances name resolver shutdown.

#### xDS-enabled gRPC servers
New filter instances are created per combination of:
1. Server instance,
2. FilterChain name,
3. Filter name+typeUrl as configured in FilterChain's HCM.http_filters

Filter instances of Default Filter Chain is tracked separately per:
1. Server instance,
2. Filter name+typeUrl in default_filter_chain's HCM.http_filters.

Existing server-side filter instances are shutdown:
- A single a filter instance is shutdown when an LDS update contains
  FilterChain with HCM.http_filters that is missing configuration for
  filter name+typeUrl.
- All filter instances associated with the FilterChain when an LDS
  update no longer contains FilterChain's name.
- All filter instances when watched LDS resource is missing from an
  LDS update.
- All filter instances on server shutdown.

### Related
- Part 1: #11883
2025-03-06 10:32:08 -08:00
MV Shiva 602aece081
xds: avoid unnecessary dns lookup (#11932) 2025-03-06 16:04:53 +05:30
MV Shiva 12197065fe
xds: xDS-based HTTP CONNECT configuration (#11861) 2025-03-06 13:40:18 +05:30
MV Shiva c340f4a2f3
rls: allow maxAge to exceed 5m if staleAge is set (#11931) 2025-03-04 10:02:03 +05:30
Sergii Tkachenko 1a2285b527
xds: ensure server interceptors are created in a sync context (#11930)
`XdsServerWrapper#generatePerRouteInterceptors` was always intended
to be executed within a sync context. This PR ensures that by calling
`syncContext.throwIfNotInThisSynchronizationContext()`.

This change is needed for upcoming xDS filter state retention because
the new tests in XdsServerWrapperTest flake with this NPE:

> `Cannot invoke "io.grpc.xds.client.XdsClient$ResourceWatcher.onChanged(io.grpc.xds.client.XdsClient$ResourceUpdate)" because "this.ldsWatcher" is null`
2025-03-03 14:28:36 -08:00
Kannan J cdab410b81
netty: Per-rpc authority verification against peer cert subject names (#11724)
Per-rpc verification of authority specified via call options or set by the LB API against peer cert's subject names.
2025-02-24 20:28:11 +05:30
Eric Anderson 57124d6b29 Use acceptResolvedAddresses() in easy cases
We want to move away from handleResolvedAddresses(). These are "easy" in
that they need no logic. LBs extending ForwardingLoadBalancer had the
method duplicated from handleResolvedAddresses() and swapped away from
`super` because ForwardingLoadBalancer only forwards
handleResolvedAddresses() reliably today. Duplicating small methods was
less bug-prone than dealing with ForwardingLoadBalancer.
2025-02-20 21:25:55 -08:00
Eric Anderson 110c1ff0d6 xds: Use acceptResolvedAddresses() for PriorityLb children
PriorityLb should propagate config problems up to the name resolver so
it can refresh.
2025-02-20 16:35:54 -08:00
Eric Anderson f207be39a9 util: Remove GracefulSwitchLb.switchTo()
It was deprecated in 85e0a01ec, so has been deprecated for six
releases/over six months.
2025-02-20 16:06:37 -08:00
Daniel Liu 892144dcac
xds: explicitly set request hash key for the ring hash LB policy
Implements [gRFC A76: explicitly setting the request hash key for the
ring hash LB policy][A76]
* Explictly setting the request hash key is guarded by the
  `GRPC_EXPERIMENTAL_RING_HASH_SET_REQUEST_HASH_KEY` environment
  variable until API stabilized. 

Tested:
* Verified end-to-end by spinning up multiple gRPC servers and a gRPC
  client that injects a custom service (load balancing) config with
  `ring_hash_experimental` and a custom `request_hash_header` (with
  NO associated value in the metadata headers) which generates a random
  hash for each request to the ring hash LB. Verified picks/RPCs are
  split evenly/uniformly across all backends.
* Ran affected unit tests with thread sanitizer and 1000 iterations to
  prevent data races.

[A76]: https://github.com/grpc/proposal/blob/master/A76-ring-hash-improvements.md#explicitly-setting-the-request-hash-key
2025-02-19 20:25:33 -08:00
Riya Mehta 68d79b5130
s2a: Use protos published under com.google.s2a.proto.v2. (#11908) 2025-02-19 16:59:50 -08:00
Kannan J 60f6ea7b8e
Upgrade gradle and gradle plugin versions. (#11906)
Upgrading to Gradle 8.11.
Gradle 8.12 requires newer versions of Windows (gradle/gradle#31939) that we can look into later.
2025-02-19 17:25:54 +05:30
Sergii Tkachenko 2b87b01651
xds: Change how xDS filters are created by introducing Filter.Provider (#11883)
This is the first step towards supporting filter state retention in
Java. The mechanism will be similar to the one described in [A83]
(https://github.com/grpc/proposal/blob/master/A83-xds-gcp-authn-filter.md#filter-call-credentials-cache)
for C-core, and will serve the same purpose. However, the
implementation details are very different due to the different nature
of xDS HTTP filter support in C-core and Java.

In Java, xDS HTTP filters are backed by classes implementing
`io.grpc.xds.Filter`, from here just called "Filters". To support
Filter state retention (next PR), Java's xDS implementation must be
able to create unique Filter instances per:
- Per HCM
  `envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager`
- Per filter name as specified in
  `envoy.extensions.filters.network.http_connection_manager.v3.HttpFilter.name`

This PR **does not** implements Filter state retention, but lays the
groundwork for it by changing how filters are registered and
instantiated. To achieve this, all existing Filter classes had to be
updated to the new instantiation mechanism described below.

Prior to these this PR, Filters had no livecycle. FilterRegistry
provided singleton instances for a given typeUrl. This PR introduces
a new interface `Filter.Provider`, which instantiates Filter classes.
All functionality that doesn't need an instance of a Filter is moved
to the Filter.Provider. This includes parsing filter config proto
into FilterConfig and determining the filter kind
(client-side, server-side, or both).

This PR is limited to refactoring, and there's no changes to the
existing behavior. Note that all Filter Providers still return
singleton Filter instances. However, with this PR, it is now possible
to create Providers that return a new Filter instance each time
`newInstance` is called.
2025-02-18 10:47:01 -08:00
Eric Anderson 713607056e util: Use acceptResolvedAddresses() for MultiChildLb children
A failing Status from acceptResolvedAddresses means something is wrong
with the config, but parts of the config may still have been applied.
Thus there are now two possible flows: errors that should prevent
updateOverallBalancingState() and errors that should have no effect
other than the return code. To manage that, MultChildLb must always be
responsible for calling updateOverallBalancingState().
acceptResolvedAddressesInternal() was inlined to make that error
processing easier. No existing usages actually needed to have logic
between updating the children and regenerating the picker.

RingHashLb already was verifying that the address list was not empty, so
the short-circuiting when acceptResolvedAddressesInternal() returned an
error was impossible to trigger. WrrLb's updateWeightTask() calls the
last picker, so it can run before acceptResolvedAddressesInternal(); the
only part that matters is re-creating the weightUpdateTimer.
2025-02-18 07:33:49 -08:00
Kannan J a132123c93
Start 1.72.0 development cycle (#11907) 2025-02-18 19:46:02 +05:30
Naveen Prasanna V 16edf7ac4e
Examples: Updated HelloWorldServer to use Executor (#11850) 2025-02-18 14:40:18 +05:30
Eric Anderson 16d26726cf
s2a: Don't allow S2AStub to be set
S2AStub is an internal API and shouldn't be used outside of s2a. It is
still available for tests.

IntegrationTest was moved to io.grpc.s2a. It uses a io.grpc.s2a class,
so shouldn't be in internal.handler
2025-02-14 15:47:19 -08:00
Eric Anderson 9e54e8e5e9 servlet: Provide Gradle a filter version number
The version number is simply a unique string per version.
2025-02-14 15:45:44 -08:00
Larry Safran c1d703546a
okhttp:Use a locally specified value instead of Segment.SIZE in okhttp (#11899)
Switched to using 8192 which is the current value of Segment.SIZE and just have a test check that they are equal.  

The reason for doing this is that Segment.SIZE is Kotlin internal so shouldn't be used outside of its module.
2025-02-14 14:46:54 -08:00
Eric Anderson 57af63ad0a kokoro: Increase gradle mem in android-interop
To try to aid failure when building android-interop-testing
```
The Daemon will expire after the build after running out of JVM heap space.
The project memory settings are likely not configured or are configured to an insufficient value.
The daemon will restart for the next build, which may increase subsequent build times.
These settings can be adjusted by setting 'org.gradle.jvmargs' in 'gradle.properties'.
The currently configured max heap space is '512 MiB' and the configured max metaspace is '384 MiB'.
...
Exception in thread "Daemon client event forwarder" java.lang.OutOfMemoryError: Java heap space
...
> Task :grpc-android-interop-testing:mergeDexDebug FAILED
ERROR:D8: java.lang.OutOfMemoryError: Java heap space
com.android.builder.dexing.DexArchiveMergerException: Error while merging dex archives:
```
2025-02-14 13:20:05 -08:00
Riya Mehta a5347b2bc4
s2a: inject Optional<AccessTokenManager> in tests 2025-02-14 12:55:42 -08:00
Larry Safran 41dd0c6d73
xds:Cleanup to reduce test flakiness (#11895)
* don't process resourceDoesNotExist for watchers that have been cancelled.

* Change test to use an ArgumentMatcher instead of expecting that only the final result will be sent since depending on timing there may be configs sent for clusters being removed with their entries as errors.
2025-02-14 10:23:54 -08:00
Alex Panchenko 5a7f350537
optimize number of buffer allocations (#11879)
Currently this improves 2 flows

1. Known length message which length is greater than 1Mb. Previously the
first buffer was 1Mb, and then many buffers of 4096 bytes (from
CodedOutputStream), now subsequent buffers are also up to 1Mb

2. In case of compression, the first write is always 10 bytes buffer
(gzip header), but worth allocating more space
2025-02-14 05:59:21 -08:00
MV Shiva 7585b1607d
core: remember last pick status in no real stream (#11851) 2025-02-14 11:38:06 +05:30
Eric Anderson 122b683717 Upgrade netty-tcnative to 2.0.70 2025-02-13 12:41:56 -08:00
Larry Safran 764a4e3f08
xds: Cleanup by moving methods in XdsDependencyManager ahead of classes (#11890)
* Move private methods ahead of classes
2025-02-11 14:34:46 -08:00
Larry Safran ade2dd2038
xds: Change XdsClusterConfig to have children field instead of endpoint (#11888)
* Change XdsConfig to match spec with a `children` object holding either `a list of leaf cluster names` or `an EdsUpdate`.  Removed intermediate aggregate nodes from `XdsConfig.clusters`.
2025-02-11 12:38:52 -08:00
Kannan J fc8571a0e5
Version upgrades (#11874) 2025-02-12 01:08:46 +05:30
Naveen Prasanna V 302342cfce
core: logging the error message when onClose() itself fails (#11880) 2025-02-11 11:38:07 +05:30
Benjamin Peterson dc316f7fd9 Add missing frame release to Http2ClientStreamTransportState.
If a data frame is received before headers, processing of the frame is abandoned. The frame must be released in that case.
2025-02-10 21:40:05 -08:00
Sergii Tkachenko bd6af59221
xds: improve code readability of server FilterChain parsing
- Improve code flow and variable names
- Reduce nesting
- Add comments between logical blocks
- Add comments explaining some xDS/gRPC nuances
2025-02-10 17:14:07 -08:00
Larry Safran 67fc2e156a
Add new classes for eliminating xds config tears (#11740)
* Framework definition to support A74
2025-02-07 16:33:17 -08:00
MV Shiva 90b1c4fe94
protobuf: Stabilize marshallerWithRecursionLimit (#11884) 2025-02-07 14:16:13 +05:30
Abhishek Agrawal 44e92e2c2c
core: updates the backoff range as per the A6 redefinition (#11858)
* core: updates the backoff range being used from [0, 1] to [0.8, 1.2] as per the A6 redefinition

* adds a flag for experimental jitter

* xds: Allow FaultFilter's interceptor to be reused

This is the only usage of PickSubchannelArgs when creating a filter's
ClientInterceptor, and a follow-up commit will remove the argument and
actually reuse the interceptors. Other filter's interceptors can
already be reused.

There doesn't seem to be any significant loss of legibility by making
FaultFilter a more ordinary interceptor, but the change does cause the
ForwardingClientCall to be present when faultDelay is configured,
independent of whether the fault delay ends up being triggered.

Reusing interceptors will move more state management out of the RPC path
which will be more relevant with RLQS.

* netty: Removed 4096 min buffer size (#11856)

* netty: Removed 4096 min buffer size

* turns the flag in a var for better efficiency

---------

Co-authored-by: Eric Anderson <ejona@google.com>
2025-02-05 14:18:20 -08:00
Alex Panchenko 3142928fa3
use gradle java-platform in grpc-bom; Fixes #5530 (#11875)
* use gradle java-platform in grpc-bom; Fixes #5530

* fix withXml

* explicitly exclude grpc-compiler
2025-02-05 11:10:39 -08:00
Eric Anderson 199a7ea3e8
xds: Improve XdsNR's selectConfig() variable handling
The variables from the do-while are no longer initialized to let the
compiler verify that the loop sets each. Unnecessary comparisons to null
are also removed and is more obvious as the variables are never set to
null. Added a minor optimization of computing the RPCs path once instead
of once for each route. The variable declarations were also sorted to
match their initialization order.

This does fix an unlikely bug where if the old code could successfully
matched a route but fail to retain the cluster, then when trying a
second time if the route was _not_ matched it would re-use the prior route
and thus infinite-loop failing to retain that same cluster.

It also adds a missing cast to unsigned long for a uint32 weight. The old
code would detect if the _sum_ was negative, but a weight using 32 bits
would have been negative and never selected.
2025-02-05 10:37:22 -08:00
Eric Anderson ea3f644eef
Replace Kokoro ARM build with GitHub Actions
The Kokoro aarch64 build runs on x86 with an emulator, and has always
been flaky due to the slow execution speed. At present it is continually
failing due to deadline exceededs. GitHub Actions is running on aarch64
hardware, so is much faster (4 minutes vs 30 minutes, without including
the speedup from GitHub Action's caching).
2025-02-04 10:51:13 -08:00
Alex Panchenko 4a10a38166
servlet: remove 4096 min buffer size
Similar to 7153ff8
2025-02-04 10:49:30 -08:00
Eric Anderson b1bc0a9d24 alts: Add ClientCall support to AltsContextUtil
This adds a createFrom(Attributes) to mirror the check(Attributes) added
in ba8ab79. It also adds conveniences for ClientCall for both
createFrom() and check(). This allows getting peer information from
ClientCall and CallCredentials.RequestInfo, as was already available
from ServerCall.

The tests were reworked to test the Attribute-based methods and then
only basic tests for client/server.

Fixes #11042
2025-01-30 16:10:19 -08:00
Eric Anderson 04f1cc5845 xds: Make XdsNR.RoutingConfig.empty a constant
The field was made final in 4b52639aa but was soon reverted in 3ebb3e192
because of what I assume was a bad merge conflict resolution. The field
has contained an immutable object since its introduction in d25f5acf1,
so it is pretty likely to remain a constant in the future.
2025-01-30 15:10:12 -08:00
Eric Anderson c506190b0f
xds: Reuse filter interceptors across RPCs
This moves the interceptor creation from the ConfigSelector to the
resource update handling.

The code structure changes will make adding support for filter
lifecycles (for RLQS) a bit easier. The filter lifecycles will allow
filters to share state across interceptors, and constructing all the
interceptors on a single thread will mean filters wouldn't need to be
thread-safe (but their interceptors would be thread-safe).
2025-01-30 12:43:51 -08:00
Eric Anderson 90aefb26e7 core: Propagate authority override from LB exactly once
Setting the authority is only useful when creating a real stream, as
there will be a following pick otherwise. In addition, DelayedStream
will buffer each call to setAuthority() in a list and we don't want that
memory usage. Note that no LBs are using this feature yet, so users
would not have been exposed to the memory use.

We also needed to setAuthority() when the LB selected a subchannel on
the first pick attempt.
2025-01-30 08:08:17 -08:00
Abhishek Agrawal 7153ff8522
netty: Removed 4096 min buffer size (#11856)
* netty: Removed 4096 min buffer size
2025-01-30 12:52:37 +05:30
Eric Anderson b3db8c2489 xds: Allow FaultFilter's interceptor to be reused
This is the only usage of PickSubchannelArgs when creating a filter's
ClientInterceptor, and a follow-up commit will remove the argument and
actually reuse the interceptors. Other filter's interceptors can
already be reused.

There doesn't seem to be any significant loss of legibility by making
FaultFilter a more ordinary interceptor, but the change does cause the
ForwardingClientCall to be present when faultDelay is configured,
independent of whether the fault delay ends up being triggered.

Reusing interceptors will move more state management out of the RPC path
which will be more relevant with RLQS.
2025-01-29 14:21:53 -08:00
vinodhabib 9e8629914f
examples: Added README files for all missing Examples (#11676) 2025-01-28 13:02:00 +05:30
Larry Safran 87aa6deadf
core:Have acceptResolvedAddresses() do a seek when in CONNECTING state and cleanup removed subchannels when a seek was successful (#11849)
* Have acceptResolvedAddresses() do a seek when in CONNECTING state and cleanup removed subchannels when a seek was successful.
Move cleanup of removed subchannels into a method so it can be called from 2 places in acceptResolvedAddresses.
Since the seek could mean we never looked at the first address, if we go off the end of the index and haven't looked at the all of the addresses then instead of scheduleBackoff() we reset the index and request a connection.
2025-01-24 16:42:56 -08:00
Boddu Harshavardhan 67351c0c53
gcp-observability: Optimize GcpObservabilityTest.enableObservability execution time (#11783) 2025-01-24 16:50:41 +05:30
MV Shiva bf8eb24a30
Update README etc to reference 1.70.0 (#11854) 2025-01-24 15:21:14 +05:30
Kannan J 0f5503ebb1
xds: Include max concurrent request limit in the error status for concurre… (#11845)
Include max concurrent request limit in the error status for concurrent connections limit exceeded
2025-01-23 21:40:21 +05:30
Eric Anderson 495a8906b2 xds: Fix fallback test FakeClock TSAN failure
d65d3942e increased the test speed of
connect_then_mainServerDown_fallbackServerUp by using FakeClock.
However, it introduced a data race because FakeClock is not thread-safe.
This change injects a single thread for gRPC callbacks such that
syncContext is run on a thread under the test's control.

A simpler approach would be to expose syncContext from XdsClientImpl for
testing. However, this test is in a different package and I wanted to
avoid adding a public method.

```
  Read of size 8 at 0x00008dec9d50 by thread T25:
    #0 io.grpc.internal.FakeClock$ScheduledExecutorImpl.schedule(Lio/grpc/internal/FakeClock$ScheduledTask;JLjava/util/concurrent/TimeUnit;)V FakeClock.java:140
    #1 io.grpc.internal.FakeClock$ScheduledExecutorImpl.schedule(Ljava/lang/Runnable;JLjava/util/concurrent/TimeUnit;)Ljava/util/concurrent/ScheduledFuture; FakeClock.java:150
    #2 io.grpc.SynchronizationContext.schedule(Ljava/lang/Runnable;JLjava/util/concurrent/TimeUnit;Ljava/util/concurrent/ScheduledExecutorService;)Lio/grpc/SynchronizationContext$ScheduledHandle; SynchronizationContext.java:153
    #3 io.grpc.xds.client.ControlPlaneClient$AdsStream.handleRpcStreamClosed(Lio/grpc/Status;)V ControlPlaneClient.java:491
    #4 io.grpc.xds.client.ControlPlaneClient$AdsStream.lambda$onStatusReceived$0(Lio/grpc/Status;)V ControlPlaneClient.java:429
    #5 io.grpc.xds.client.ControlPlaneClient$AdsStream$$Lambda+0x00000001004a95d0.run()V ??
    #6 io.grpc.SynchronizationContext.drain()V SynchronizationContext.java:96
    #7 io.grpc.SynchronizationContext.execute(Ljava/lang/Runnable;)V SynchronizationContext.java:128
    #8 io.grpc.xds.client.ControlPlaneClient$AdsStream.onStatusReceived(Lio/grpc/Status;)V ControlPlaneClient.java:428
    #9 io.grpc.xds.GrpcXdsTransportFactory$EventHandlerToCallListenerAdapter.onClose(Lio/grpc/Status;Lio/grpc/Metadata;)V GrpcXdsTransportFactory.java:149
    #10 io.grpc.PartialForwardingClientCallListener.onClose(Lio/grpc/Status;Lio/grpc/Metadata;)V PartialForwardingClientCallListener.java:39
    ...

  Previous write of size 8 at 0x00008dec9d50 by thread T4 (mutexes: write M0, write M1, write M2, write M3):
    #0 io.grpc.internal.FakeClock.forwardTime(JLjava/util/concurrent/TimeUnit;)I FakeClock.java:368
    #1 io.grpc.xds.XdsClientFallbackTest.connect_then_mainServerDown_fallbackServerUp()V XdsClientFallbackTest.java:358
    ...
```
2025-01-22 16:00:00 -08:00
Eric Anderson fc86084df5 xds: Rename grpc.xds.cluster to grpc.lb.backend_service
The name is being changed to allow the value to be used in more metrics
where xds-specifics are awkward.
2025-01-17 17:16:32 -08:00
Eric Anderson a0a42fc8e6 Update README etc to reference 1.69.1 2025-01-17 13:30:22 -08:00
Eric Anderson f299ef5e58 compiler: Prepare for C++ protobuf using string_view
Protobuf is interested in using absl::string_view instead of const
std::string&. Just copy to std::string as the C++17 build isn't yet
operational and that level of performance doesn't matter.

cl/711732759 b/353571051
2025-01-17 10:44:01 -08:00
MV Shiva b44ebce45d
xds: Envoy proto sync to 2024-11-11 (#11816) 2025-01-17 14:58:52 +05:30
Larry Safran 4d8aff72dc
stub: Eliminate invalid test cases where different threads were calling close from the thread writing. (#11822)
* Eliminate invalid test cases where different threads were calling close from the thread writing.
* Remove multi-thread cancel/write test
2025-01-15 10:43:48 -08:00
Eric Anderson 87c7b7a375 interop-testing: Move soak out of AbstractInteropTest
The soak code grew considerably in 6a92a2a22e. Since it isn't a JUnit
test and doesn't resemble the other tests, it doesn't belong in
AbstractInteropTest. AbstractInteropTest has lots of users, including it
being re-compiled for use on Android, so moving it out makes the
remaining code more clear for the more common cases.
2025-01-14 13:28:10 -08:00
zbilun 87b27b1545
interop-testing: fix peer extraction issue in soak test iterations
This PR resolves an issue with peer address extraction in the soak
test. 

In current `TestServiceClient` implementation, the same
`clientCallCapture` atomic is shared across threads, leading to
incorrect peer extraction. This fix ensures that each thread uses a
local variable for capturing the client call.
2025-01-13 17:57:39 -08:00
Larry Safran 228dcf7a01
core: Alternate ipV4 and ipV6 addresses for Happy Eyeballs in PickFirstLeafLoadBalancer (#11624)
* Interweave ipV4 and ipV6 addresses as per gRFC.
2025-01-13 16:38:16 -08:00
Eric Anderson 7162d2d661 xds: Pass grpc.xds.cluster label to tracer
This is in service to gRFC A89. Since the gRFC isn't finalized this
purposefully doesn't really do anything yet. The grpc-opentelemetry
change to use this optional label will be done after the gRFC is merged.
grpc-opentelemetry currently has a hard-coded list (one entry) of labels
that it looks for, and this label will need to be added.

b/356167676
2025-01-13 11:54:36 -08:00
Larry Safran 176f3eed12
xds: Enable Xds Client Fallback by default (#11817) 2025-01-10 15:25:15 -08:00
Eric Anderson d65d3942e6 xds: Increase speed of fallback test
These changes reduce connect_then_mainServerDown_fallbackServerUp test
time from 20 seconds to 5 s by faking time for the the does-no-exist
timer.

XdsClientImpl only uses the TimeProvider for CSDS cache details, so any
implementation should be fine. FakeXdsClient provides an implementation,
so might as well use it as it is one less clock to think about.
2025-01-10 08:28:48 -08:00
Eric Anderson 82403b9bfa util: Increase modtime in AdvancedTlsX509TrustManagerTest
I noticed an old JDK 8u275 failed on the test because the modification
time's resolution was one second. A newer JDK 8u432 worked fine, so it's
not really a problem for me, but increasing the time difference is
cheap. I used two seconds as that's the resolution available on FAT
(which is unlikely to be TMPDIR, even on Windows).
2025-01-10 08:17:12 -08:00
Eric Anderson 70825adce6 Replace jsr305's GuardedBy with Error Prone's
We should avoid jsr305 and error prone's has the same semantics.
2025-01-10 08:16:48 -08:00
Eric Anderson 7b5d0692cc
Replace jsr305's CheckReturnValue with Error Prone's (#11811)
We should avoid jsr305 and error prone's has the same semantics.

Fixes #8687
2025-01-09 13:45:35 -08:00
Albumen Kevin 73721acc0d
Add UnitTest to verify updateTrustCredentials rotate (#11798)
* Add lastUpdateTime to avoid read
2025-01-09 11:53:36 -08:00
Eric Anderson e61b03cb9f netty: Fix getAttributes() data races in NettyClientTransportTest
Since approximately the LBv2 API (the current API) was introduced, gRPC
won't use a transport until it is ready. Long ago, transports could be
used before they were ready and these old tests were not waiting for the
negotiator to complete before starting. We need them to wait for the
handshake to complete to avoid a test-only data race in getAttributes()
noticed by TSAN.

Throwing away data frames in the Noop handshaker is necessary to act
like a normal handshaker; they don't allow data frames to pass until the
handshake is complete. Without the handling, it goes through invalid
code paths in NettyClientHandler where a terminated transport becomes
ready, and a similar data race.

```
  Write of size 4 at 0x00008db31e2c by thread T37:
    #0 io.grpc.netty.NettyClientHandler.handleProtocolNegotiationCompleted(Lio/grpc/Attributes;Lio/grpc/InternalChannelz$Security;)V NettyClientHandler.java:517
    #1 io.grpc.netty.ProtocolNegotiators$GrpcNegotiationHandler.userEventTriggered(Lio/netty/channel/ChannelHandlerContext;Ljava/lang/Object;)V ProtocolNegotiators.java:937
    #2 io.netty.channel.AbstractChannelHandlerContext.invokeUserEventTriggered(Ljava/lang/Object;)V AbstractChannelHandlerContext.java:398
    #3 io.netty.channel.AbstractChannelHandlerContext.invokeUserEventTriggered(Lio/netty/channel/AbstractChannelHandlerContext;Ljava/lang/Object;)V AbstractChannelHandlerContext.java:376
    #4 io.netty.channel.AbstractChannelHandlerContext.fireUserEventTriggered(Ljava/lang/Object;)Lio/netty/channel/ChannelHandlerContext; AbstractChannelHandlerContext.java:368
    #5 io.grpc.netty.ProtocolNegotiators$ProtocolNegotiationHandler.fireProtocolNegotiationEvent(Lio/netty/channel/ChannelHandlerContext;)V ProtocolNegotiators.java:1107
    #6 io.grpc.netty.ProtocolNegotiators$WaitUntilActiveHandler.channelActive(Lio/netty/channel/ChannelHandlerContext;)V ProtocolNegotiators.java:1011
    ...

  Previous read of size 4 at 0x00008db31e2c by thread T4 (mutexes: write M0, write M1, write M2, write M3):
    #0 io.grpc.netty.NettyClientHandler.getAttributes()Lio/grpc/Attributes; NettyClientHandler.java:345
    #1 io.grpc.netty.NettyClientTransport.getAttributes()Lio/grpc/Attributes; NettyClientTransport.java:387
    #2 io.grpc.netty.NettyClientTransport.newStream(Lio/grpc/MethodDescriptor;Lio/grpc/Metadata;Lio/grpc/CallOptions;[Lio/grpc/ClientStreamTracer;)Lio/grpc/internal/ClientStream; NettyClientTransport.java:198
    #3 io.grpc.netty.NettyClientTransportTest$Rpc.<init>(Lio/grpc/netty/NettyClientTransport;Lio/grpc/Metadata;)V NettyClientTransportTest.java:953
    #4 io.grpc.netty.NettyClientTransportTest.huffmanCodingShouldNotBePerformed()V NettyClientTransportTest.java:631
    ...
```

```
  Read of size 4 at 0x00008f983a3c by thread T4 (mutexes: write M0, write M1):
    #0 io.grpc.netty.NettyClientHandler.getAttributes()Lio/grpc/Attributes; NettyClientHandler.java:345
    #1 io.grpc.netty.NettyClientTransport.getAttributes()Lio/grpc/Attributes; NettyClientTransport.java:387
    #2 io.grpc.netty.NettyClientTransport.newStream(Lio/grpc/MethodDescriptor;Lio/grpc/Metadata;Lio/grpc/CallOptions;[Lio/grpc/ClientStreamTracer;)Lio/grpc/internal/ClientStream; NettyClientTransport.java:198
    #3 io.grpc.netty.NettyClientTransportTest$Rpc.<init>(Lio/grpc/netty/NettyClientTransport;Lio/grpc/Metadata;)V NettyClientTransportTest.java:973
    #4 io.grpc.netty.NettyClientTransportTest$Rpc.<init>(Lio/grpc/netty/NettyClientTransport;)V NettyClientTransportTest.java:969
    #5 io.grpc.netty.NettyClientTransportTest.handlerExceptionDuringNegotiatonPropagatesToStatus()V NettyClientTransportTest.java:425
    ...

  Previous write of size 4 at 0x00008f983a3c by thread T56:
    #0 io.grpc.netty.NettyClientHandler$FrameListener.onSettingsRead(Lio/netty/channel/ChannelHandlerContext;Lio/netty/handler/codec/http2/Http2Settings;)V NettyClientHandler.java:960
    ...
```
2025-01-07 10:25:22 -08:00
MV Shiva ae109727d3
Start 1.71.0 development cycle (#11801) 2025-01-07 14:33:09 +05:30
MV Shiva 1edc4d84d4
xds: Parsing xDS Cluster Metadata (#11741) 2025-01-07 10:03:13 +05:30
Larry Safran 4222f77587
xds:Move creating the retry timer in handleRpcStreamClosed to as late as possible and call close() (#11776)
* Move creating the retry timer in handleRpcStreamClosed to as late as possible and call `close` so that the `call` is cancelled.
Also add some debug logging.
2025-01-06 13:09:42 -08:00
Eric Anderson 6c12c2bd24 xds: Remember nonces for unknown types
If the control plane sends a resource type the client doesn't understand
at-the-moment, the control plane will still expect the client to include
the nonce if the client subscribes to the type in the future.

This most easily happens when unsubscribing the last resource of a type.
Which meant 1cf1927d1 was insufficient.
2025-01-06 11:54:35 -08:00
Eric Anderson 4a0f707331 xds: Avoid depending on io.grpc.xds.Internal* classes
Internal* classes should generally be accessors that are used outside of
the package/project. Only one attribute was used outside of xds, so
leave only that one attribute in InternalXdsAttributes. One attribute
was used by the internal.security package, so move the definition to the
same package to reduce the circular dependencies.
2025-01-03 16:01:10 -08:00
Eric Anderson 1cf1927d1a
xds: Preserve nonce when unsubscribing type
This fixes a regression introduced in 19c9b998.

b/374697875
2025-01-03 12:34:47 -08:00
Eric Anderson 9a712c3f77 xds: Make XdsClient.ResourceStore package-private
There's no reason to use the interface outside of
XdsClientImpl/ControlPlaneClient. Since XdsClientImpl implements the
interface directly, its methods are still public. That can be a future
cleanup.
2025-01-03 11:45:55 -08:00
Benjamin Peterson bac8b32043
Fix equality and hashcode of CancelServerStreamCommand. (#11785)
In e036b1b198, CancelServerStreamCommand got another field. But, its hashCode and equals methods were not updated.
2025-01-03 10:42:42 -08:00
Eric Anderson b272f634c1 Disable Gradle Module Metadata resolution
The module metadata in Guava causes the -jre version to be selected even
when you choose the -android version. Gradle did not give any clues that
this was happening, and while
`println(configurations.compileClasspath.resolve())` shows the different
jar in use, most other diagonstics don't. dependencyInsight can show you
this is happening, but only if you know which dependency has a problem
and read Guava's module metadata first to understand the significance of
the results.

You could argue this is a Guava-specific problem. I was able to get
parts of our build working with attributes and resolutionStrategy
configurations mentioned at
https://github.com/google/guava/releases/tag/v32.1.0 , so that only
Guava would be changed. But it was fickle giving poor error messages or
silently swapping back to the -jre version.

Given the weak debuggability, the added complexity, and the lack of
value module metadata is providing us, disabling module metadata for our
entire build seems prudent.

See https://github.com/google/guava/issues/7575
2025-01-03 09:29:31 -08:00
Eric Anderson fdb9a5a94f gae-interop-testing: Remove duplicate repositories
These repositories are already included from the main build.gradle, so
they don't do anything. Much less do they need to be defined twice in
the same file.
2025-01-03 09:29:08 -08:00
Eric Anderson c96e926e65 examples: Remove references to maven-central.storage-download.googleapis.com
As stated [on its main page][index], it isn't officially supported, so
we shouldn't include it in our examples.

[index]: https://maven-central.storage-download.googleapis.com/index.html
2025-01-03 09:28:42 -08:00
Benjamin Peterson 8c261c3f28
Fix typo in deprecated blocking stub javadoc. (#11772) 2024-12-26 13:31:34 -08:00
vinodhabib 5e8abc6774
examples: Updated the attachHeaders to newAttachHeadersInterceptor in HeaderClientInterceptor (#11759) 2024-12-24 12:18:03 +05:30
John Cormie 1126a8e30b
binder: A standard API for pointing resolvers at a different Android User. (#11775) 2024-12-23 13:29:40 -08:00
Eric Anderson 805cad3782 bazel: Restore DoNotCall ErrorProne check
In e08b9db20 we added `@DoNotCall` annotations to some call sites, but
Bazel used an older version of ErrorProne that complained at times it
shouldn't. The minimum version of Bazel we test/support is now Bazel 6,
well past Bazel 3.4+.
2024-12-23 12:45:42 -08:00
Eric Anderson aafab74087 api: Use package-private IgnoreJRERequirement
This avoids the dependency on animalsniffer-annotations. grpc-api, and
particularly grpc-context, are used many low-level places and it is
beneficial for them to be very low dependency. This brings grpc-context
back to zero-dependency.
2024-12-23 12:45:26 -08:00
Alex Panchenko ebe2b48677
api: StatusRuntimeException without stacktrace - Android compatibility (#11072)
This is an alternative to e36f099be9 that avoids the "fillInStaceTrace"
constructor which is only available starting at Android API level 24.
2024-12-21 17:09:57 -08:00
Vindhya Ningegowda 6516c7387e
xds: Remove xds authority label from metric registration (#11760)
* Remove `grpc.xds.authority` label while registering `grpc.xds_client.resources` gauge, until the label value is available to record.
2024-12-20 19:50:09 -08:00
Larry Safran ea8c31c305
Bidi Blocking Stub (#10318) 2024-12-20 16:16:17 -08:00
Kannan J 7b29111cd0
Update README etc to reference 1.69.0 2024-12-20 11:15:54 -08:00
John Cormie 0b2d44098f
Introduce custom NameResolver.Args (#11669)
grpc-binder's upcoming AndroidIntentNameResolver needs to know the target Android user so it can resolve target URIs in the correct place. Unfortunately, Android's built in intent:// URI scheme has no way to specify a user and in fact the android.os.UserHandle object can't reasonably be encoded as a String at all.

We solve this problem by extending NameResolver.Args with the same type-safe and domain-specific Key<T> pattern used by CallOptions, Context and CreateSubchannelArgs. New "custom" arguments could apply to all NameResolvers of a certain URI scheme, to all NameResolvers producing a particular type of java.net.SocketAddress, or even to a specific NameResolver subclass.
2024-12-19 23:32:47 -08:00
Larry Safran ef7c2d59c1
xds: Fix XDS control plane client retry timer backoff duration when connection closes after results are received (#11766)
* Fix retry timer backoff duration.

* Reset stopwatch when we had results on AdsStream rather than change the delay calculation logic.
2024-12-19 14:46:58 -08:00
Eric Anderson 7601afc213 Bump android animalsniffer signature to API 21
This should have been done as part of 2b4f649b
2024-12-19 10:07:29 -08:00
Eric Anderson 8ea3629378
Re-enable animalsniffer, fixing violations
In 61f19d707a I swapped the signatures to use the version catalog. But I
failed to preserve the `@signature` extension and it all seemed to
work... But in fact all the animalsniffer tasks were completing as
SKIPPED as they lacked signatures. The build.gradle changes in this
commit are to fix that while still using version catalog.

But while it was broken violations crept in. Most violations weren't
too important and we're not surprised went unnoticed. For example, Netty
with TLS has long required the Java 8 API
`setEndpointIdentificationAlgorithm()`, so using `Optional` in the same
code path didn't harm anything in particular. I still swapped it to
Guava's `Optional` to avoid overuse of `@IgnoreJRERequirement`.

One important violation has not been fixed and instead I've disabled the
android signature in api/build.gradle for the moment.  The violation is
in StatusException using the `fillInStackTrace` overload of Exception.
This problem [had been noticed][PR11066], but we couldn't figure out
what was going on. AnimalSniffer is now noticing this and agreeing with
the internal linter. There is still a question of why our interop tests
failed to notice this, but given they are no longer running on pre-API
level 24, that may forever be a mystery.

[PR11066]: https://github.com/grpc/grpc-java/pull/11066
2024-12-19 07:54:54 -08:00
vinodhabib f8f613984f
xds: fixed unsupported unsigned 32 bits issue for circuit breaker (#11735)
Added change for circuit breaking by converting signed 32-bit Int to Unsigned 64-bit Long For MaxRequest negative value ( -1)

Fixes #11695
2024-12-16 21:37:22 -08:00
Eric Anderson 8a5f7776db .github/workflows: Stop testing Bazel 6
Bazel 8 is now out. We support the two most recent releases.

FWIW, I have compiled with Bazel 8 and didn't experience any problems.
2024-12-16 20:54:22 -08:00
Eric Anderson fe752a290e xds: Move specialized APIs out of XdsResourceType
StructOrError is a more generic API, but we have StatusOr now so we
don't want new usages of StructOrError. Moving StructOrError out of
io.grpc.xds.client will make it easier to delete StructOrError once
we've migrated to StatusOr in the future.

TRANSPORT_SOCKET_NAME_TLS should also move, but it wasn't immediately
clear to me where it should go.
2024-12-16 16:03:59 -08:00
ZachChuba a0982ca0a1
fix security issue with okhttp (#11749)
* Validate that hostname is ascii in OkHostnameVerifier.java
2024-12-16 13:31:36 -08:00
Eric Anderson e8ff6da2cf xds: Unexpected types in server_features should be ignored
It was clearly defined in gRFC A30. The relevant text was copied as a
comment in the code.

As discovered due to grpc/grpc-go#7932
2024-12-16 07:29:51 -08:00
Larry Safran 3b39a83621
Add cfg for java psm-interop fallback test (#11743) 2024-12-13 18:09:30 -08:00
Larry Safran 486b8ba67f
Fix tsan error (#11742)
Eliminate unneeded fakeClock.forwardTime() that was causing the conflict.
2024-12-11 17:48:19 -08:00
Eric Anderson f1109e4215 examples: Simplify graceful shutdown in Hostname example
I've slept since I wrote the original code, so now I see a less
repetitive implementation.
2024-12-11 08:12:11 -08:00
Eric Anderson 6055adca5a
core: Simplify DnsNameResolver by using ObjectPool
ObjectPool is our standard solution for dealing with the
sometimes-shutdown resources. This was implemented by a contributor not
familiar with regular tools.

There are wider changes that can be made here, but I chose to just do a
smaller change because this class is used by GrpclbNameResolver.
2024-12-10 12:53:24 -08:00
Larry Safran 210f9c083e
Xds fallback (#11254)
* XDS Client Fallback
2024-12-09 15:42:27 -08:00
Eric Anderson 99a2696c48 s2a: Restore static token state mutated in tests
This is the easy-to-fix state, but GetAuthenticationMechanisms can save
these temporary states used in tests, so more fixes will be necessary.
2024-12-09 14:12:32 -08:00
MV Shiva 65b32e60e0
okhttp: Fix for ipv6 link local with scope (#11725) 2024-12-05 23:07:32 +05:30
Eric Anderson c080b52f95
.github/workflows: Split Bazel into two jobs
The two Bazel versions are completely separate; no need to run them
serially.
2024-12-02 16:31:04 -08:00
vinodhabib f66d7fc54d
netty: Fix ByteBuf leaks in tests (#11593)
Part of #3353
2024-12-02 11:09:25 -08:00
Eric Anderson 7f9c1f39f3
rls: Reduce RLS channel logging
The channel log is shared by many components and is poorly suited to
the noise of per-RPC events. This commit restricts RLS usage of the
logger to no more frequent than cache entry events. This may still be
too frequent, but should substantially improve the signal-to-noise and
we can do further rework as needed.

Many of the log entries were poor because they lacked enough context.
They weren't even clear they were from RLS. The cache entry events now
regularly include the request key in the logs, allowing you to follow
events for specific keys. I would have preferred using the hash code,
but NumberFormat is annoying and toString() may be acceptable given its
convenience.

This commit reverts much of eba699ad. Those logs have not proven to be
helpful as they produce more output than can be reasonably stored.
2024-11-27 11:37:45 -08:00
Vindhya Ningegowda ebb43a69e7
Add "#server" as dataplane target value for xDS enabled gRPC servers. (#11715)
As mentioned in [A71 xDS Fallback]( https://github.com/grpc/proposal/blob/master/A71-xds-fallback.md#update-csds-to-aggregate-configs-from-multiple-xdsclient-instances):
updated dataplane target to "#server" for xDS-enabled gRPC servers.
2024-11-27 10:59:54 -08:00
Eric Anderson 0192bece47 api: DeadlineSubject should include actual on failure
This was noticed because of a CallOptionsTest flake that had a
surprising error:
```
expected                    : 59.983387319
but was                     : 59.983387319
outside tolerance in seconds: 0.01
```
2024-11-27 10:55:34 -08:00
Riya Mehta 55cef6330f
s2a: Load resources from classpath instead of from disk 2024-11-27 10:48:59 -08:00
Kannan J 229a010f55
Start 1.70.0 development cycle (#11708)
* Start 1.70.0 development cycle
2024-11-26 21:36:50 +05:30
Riya Mehta 29dd9bad3f change s2av2_credentials to s2a 2024-11-26 08:01:08 -08:00
Yash Tibrewal a79982c7fd
[CSM] Use xds-enabled server and xds credentials in examples (#11706) 2024-11-25 21:07:52 -08:00
Vindhya Ningegowda 20d09cee57
xds: Add counter and gauge metrics (#11661)
Adds the following xDS client metrics defined in [A78](https://github.com/grpc/proposal/blob/master/A78-grpc-metrics-wrr-pf-xds.md#xdsclient).

Counters
- grpc.xds_client.server_failure
- grpc.xds_client.resource_updates_valid
- grpc.xds_client.resource_updates_invalid

Gauges
- grpc.xds_client.connected
- grpc.xds_client.resources
2024-11-25 16:47:32 -08:00
vinodhabib 92de2f34dc
testing: enabled smallLatency test (#11671) 2024-11-22 11:20:25 -08:00
Eric Anderson 32f4cf432a gae-interop-testing: Upgrade to Java 17
Java 11 is out-of-support on GAE. Unfortunately the docs use the term
"deprecated" as "deleted," not "discouraged." So they talk about it
being deprecated _after_ it is no longer supported.

https://cloud.google.com/appengine/docs/standard/lifecycle/support-schedule#java
https://cloud.google.com/appengine/docs/flexible/lifecycle/support-schedule#java
2024-11-20 08:30:58 -08:00
John Cormie e58c998a42
AndroidComponentAddress includes a target UserHandle (#11670)
The target UserHandle is best modeled as part of the SocketAddress not the Channel since it's part of the server's location.

This change allows a NameResolver to select different target users over time within a single Channel.
2024-11-18 17:31:01 -08:00
zbilun 6a92a2a22e
interop-testing: Add concurrency condition to the soak test using existing blocking api
The goal of this PR is to increase the test coverage of the C2P E2E load test by improving the rpc_soak and channel_soak tests to support concurrency.

**rpc_soak:**
The client performs many large_unary RPCs in sequence over the same channel. The test can run in either a concurrent or non-concurrent mode, depending on the number of threads specified (soak_num_threads):
  - Non-Concurrent Mode: When soak_num_threads = 1, all RPCs are performed sequentially on a single thread.
  - Concurrent Mode: When soak_num_threads > 1, the client uses multiple threads to distribute the workload. Each thread performs a portion of the total soak_iterations, executing its own set of RPCs concurrently.

**channel_soak:**
Similar to rpc_soak, but this time each RPC is performed on a new channel. The channel is created just before each RPC and is destroyed just after. Note on Concurrent Execution and Channel Creation: In a concurrent execution setting (i.e., when soak_num_threads > 1), each thread performs a portion of the total soak_iterations and creates and destroys its own channel for each RPC iteration.
- createNewChannel Function: In channel_soak, the createNewChannel function is used by each thread to create a new channel before every RPC. This function ensures that each RPC has a separate channel, preventing race conditions by isolating channels between threads. It shuts down the previous channel (if any) and creates a new one for each iteration, ensuring accurate latency measurement per RPC.

- Thread-specific logs will include the thread_id, helping to track performance across threads, especially when each thread is managing its own channel lifecycle.
2024-11-18 11:57:02 -08:00
vinodhabib 4ae04b7d94
core: increased test tolerance to 1 second
Fixes #11680
2024-11-18 07:42:51 -08:00
Eric Anderson 5431bf7e77 services: Don't track code coverage of reflection.v1 gencode
Generated code for v1alpha was ignored, but not v1. Ignoring v1 reduces
lines being checked from 16,145 to 6,303, significantly improving the
overall code coverage and removing noise. This was noticed because there
was a very clear drop at 0aa976c4 visible in the coveralls.io coverage
graph, the point when v1 was introduced.
2024-11-15 08:22:13 -08:00
Eric Anderson 1f159d7899 xds: Fix XdsSecurityClientServerTest TrustManagerStore race
When spiffe support was added it caused
tlsClientServer_useSystemRootCerts_validationContext to become flaky.
This is because test execution order was important for whether the race
would occur.

Fixes #11678
2024-11-14 22:01:38 -08:00
Eric Anderson 4e8f7df589
util: Remove resolvedAddresses from MultiChildLb.ChildLbState
It isn't actually used by MultiChildLb, and using the health API gives
us more confidence that health is properly plumbed.
2024-11-14 12:56:24 -08:00
John Cormie b1703345f7
Make channelz work with proto lite (#11685)
Allows android apps to expose internal grpc state for debugging.
2024-11-13 16:50:14 -08:00
MV Shiva 921f88ae30
services: Deprecate V1alpha (#11681) 2024-11-12 12:27:40 +05:30
Eric Anderson 8237ae270a util: Remove EAG conveniences from MultiChildLb
This is a step toward removing ResolvedAddresses from ChildLbState,
which isn't actually used by MultiChildLb. Most usages of the EAG usages
can be served more directly without peering into MultiChildLb's
internals or even accessing ChildLbStates, which make the tests less
sensitive to implementation changes. Some changes do leverage the new
behavior of MultiChildLb where it preserves the order of the entries.

This does fix an important bug in shutdown tests. The tests looped over
the ChildLbStates after shutdown, but shutdown deleted all the children
so it looped over an entry collection. Fixing that exposed that
deliverSubchannelState() didn't function after shutdown, as the listener
was removed from the map when the subchannel was shut down. Moving the
listener onto the TestSubchannel allowed having access to the listener
even after shutdown.

A few places in LeastRequestLb lines were just deleted, but that's
because an existing assertion already provided the same check but
without digging into MultiChildLb.
2024-11-11 13:16:21 -08:00
Riya Mehta 546efd79f1
s2a: fix flake in FakeS2AServerTest (#11673)
While here:
 * add an awaitTermination to after calling shutdown on server
 * don't use port picker

Fixes #11648
2024-11-08 10:25:49 -08:00
Kannan J 5081e60626
xds: Replace null check with has value check because proto fields can never be null. (#11675) 2024-11-08 13:17:24 +05:30
erm-g d6c80294a7
xds: Spiffe Trust Bundle Support (#11627)
Adds verification of SPIFFE based identities using SPIFFE trust bundles.

For in-progress gRFC A87.
2024-11-07 21:03:15 -08:00
MV Shiva 76705c235c
xds: Implement GcpAuthenticationFilter (#11638) 2024-11-06 16:39:00 +05:30
Colin Alworth a5db67d0cb Deframe failures should be logged on the server as warnings
This brings grpc-servlet in line with the grpc-netty implementation found
in NettyServerStream.TransportState.
2024-11-05 13:28:16 -08:00
Kannan J dae078c0a6
api: When forwarding from Listener onAddresses to Listener2 continue to use onResult (#11666)
When forwarding from Listener onAddresses to Listener2 continue to use onResult and not onResult2 because the latter requires to be called from within synchronization context and it breaks existing code that didn't need to do so when using the old Listener interface.
2024-11-05 23:52:20 +05:30
Eric Anderson 664f1fcf8a xds: Remove Bazel dependency on xds v2
feab4e54 removed xds v2 for the Gradle build. Testing with a deploy.jar,
I see the same 4 MB size reduction (31 -> 27 MB) here.

While an orca dependency is deleted in this commit, it is only a direct
dependency. It remains in the :orca target, so doesn't contribute a size
reduction.
2024-11-05 10:02:23 -08:00
MV Shiva 88596868a4
xds: Envoy proto sync to 2024-10-23 (#11664) 2024-11-05 10:56:33 +05:30
Eric Anderson 1993e68b03
Upgrade depedencies (#11655) 2024-11-01 07:50:08 -07:00
Kannan J ef1fe87373
okhttp: Use failing "source" for read bytes when sending GOAWAY due to insufficient thread pool size
Create `ClientFrameHandler` with failing source to be used in case of failed 2nd thread scheduling. Fixes NPE from https://github.com/grpc/grpc-java/pull/11503.
2024-10-31 11:51:40 +05:30
Kannan J c167ead851
xds: Per-rpc rewriting of the authority header based on the selected route. (#11631)
Implementation of A81.
2024-10-30 21:11:41 +05:30
Eric Anderson 3562380da5 Upgrade Gradle to 8.10.2 and upgrade plugins
com.github.johnrengelman.shadow is now com.gradleup.shadow (note the
redirect)
https://github.com/johnrengelman/shadow/releases/tag/8.3.0
2024-10-30 07:00:57 -07:00
SreeramdasLavanya 766b92379b
api: Add java.time.Duration overloads to CallOptions, AbstractStub taking TimeUnit and a time value (#11562) 2024-10-30 18:49:53 +05:30
Eric Anderson b5ef09c548
RELEASING.md: Fix interop_matrix image name (#11653) 2024-10-30 10:59:03 +05:30
Eric Anderson 1612536f86 Update README etc to reference 1.68.1 2024-10-29 14:09:15 -07:00
Eric Anderson a431e3664b binder: Remove unnecessary uses of LooperMode(PAUSED)
PAUSED Looper mode has been the default for many years, maybe around
robolectric 4.5 (9ae9f0b6a6). Explicitly specifying PAUSED Looper mode
is not necessary.

cl/690684542
2024-10-29 08:01:40 -07:00
vinodhabib 9176b55286
core: Make timestamp usage in Channelz use nanos from Java.time.Instant when available (#11604)
When java.time.Instant is available use the timestamp from this class in nano precision rather than using System.currentTimeInMillis and converting it to nanos.

Fixes #5494.
2024-10-29 10:19:47 +05:30
Ran 735b3f3fe6
netty: add soft Metadata size limit enforcement. (#11603) 2024-10-28 10:25:17 -07:00
John Cormie fe350cfd50
Update error codes doc for new "Safer Intent" rules. (#11639) 2024-10-25 14:41:03 -07:00
Kannan J 0b2c17d0da
Xds: Implement using system root trust CA for TLS server authentication (#11470)
Allow using system root certs for server cert validation rather than CA root certs provided by the control plane when the validation context provided by the control plane specifies so.
2024-10-25 14:36:27 +05:30
Eric Anderson 370e7ce27c
Revert "stub: Ignore unary response on server if status is not OK" (#11636)
This reverts commit 99f86835ed.

The change doesn't handle `null` messages, which don't happen with
protobuf, but can happen with other marshallers, especially in tests.
See cl/689445172

This will reopen #5969.
2024-10-25 12:09:22 +05:30
Luwei Ge ba8ab796e7
alts: support altsCallCredentials in GoogleDefaultChannelCredentials (#11634) 2024-10-24 15:18:53 -07:00
Eric Anderson 31dad6af49 Start 1.69.0 development cycle 2024-10-24 10:57:29 -07:00
John Cormie 46c1b387fa
Update binderDied() error description to spell out the possibilities for those unfamiliar with Android internals. (#11628)
Callers are frequently confused by this message and waste time looking for problems in the client when the root cause is simply a server crash. See b/371447460 for more context.
2024-10-24 10:52:44 -07:00
MV Shiva b65cbf5081
inprocess: Support tracing message sizes guarded by flag (#11629) 2024-10-24 01:22:41 +05:30
hlx502 62f409810d
netty: Avoid TCP_USER_TIMEOUT warning when not using epoll (#11564)
In NettyClientTransport, the TCP_USER_TIMEOUT attribute can be set only
if the channel is of the AbstractEpollStreamChannel.

Fixes #11517
2024-10-22 12:17:39 -07:00
Lucas Mirelmann 00c8bc78dd
Minor grammar fix in Javadoc (#11609) 2024-10-18 11:29:35 +05:30
erm-g 4be69e3f8a
core: SpiffeUtil API for extracting Spiffe URI and loading TrustBundles (#11575)
Additional API for SpiffeUtil:
 - extract Spiffe URI from certificate chain
 - load Spiffe Trust Bundle from filesystem [json spec][] [JWK spec][]

JsonParser was changed to reject duplicate keys in objects.

[json spec]: https://github.com/spiffe/spiffe/blob/main/standards/SPIFFE_Trust_Domain_and_Bundle.md
[JWK spec]: https://github.com/spiffe/spiffe/blob/main/standards/X509-SVID.md#61-publishing-spiffe-bundle-elements
2024-10-17 11:11:07 -07:00
Eng Zer Jun 1e0928fb79 api: fix javadoc of CallCredentials.applyRequestMetadata
It is the `Executor appExecutor` that should be given an asynchronous
task, not `CallCredentials.MetadataApplier applier`.

Signed-off-by: Eng Zer Jun <engzerjun@gmail.com>
2024-10-17 10:13:12 -07:00
Eric Anderson 23ebf364d4 inprocess: Delete "standalone" internal transport
This had been used for a time with a combined inprocess+binder server.
However, just having multiple servers worked fine and this is no longer
used/needed.
2024-10-17 09:47:20 -07:00
Vindhya Ningegowda 84d30afad6
Get mesh_id local label from "CSM_MESH_ID" environment variable, rather than parsing from bootstrap file (#11621) 2024-10-16 16:12:27 -07:00
Eric Anderson b692b9d26e core: Handle NR/LB exceptions when panicking
If a panic is followed a panic, we'd ignore the second. But if an
exception happens while entering panic mode we may fail to update the
picker with the first error. This is "fine" from a correctness
standpoint; all bets are off when panicking and we've already logged the
first error. But failing RPCs can often be more easily seen than just
the log.

Noticed because of http://yaqs/8493785598685872128
2024-10-16 13:26:45 -07:00
Naveen Prasanna V 99f86835ed
stub: Ignore unary response on server if status is not OK
Fixes #5969
2024-10-16 09:23:22 -07:00
jiangyuan 36e29abf41
fix XdsTestServer/TestServiceServer listenAddresses conflict (#11612) 2024-10-14 12:33:06 -07:00
MV Shiva ca43d78f58
inprocess: Support tracing message sizes (#11406) 2024-10-11 10:28:51 +05:30
Riya Mehta a01a9e2340
Enable publishing. (#11581) 2024-10-10 16:32:10 -07:00
Riya Mehta d628396ec7
s2a: Add S2AStub cleanup handler. (#11600)
* Add S2AStub cleanup handler.

* Give TLS and Cleanup handlers name + update comment.

* Don't add TLS handler twice.

* Don't remove explicitly, since done by fireProtocolNegotiationEvent.

* plumb S2AStub close to handshake end + add integration test.

* close stub when TLS negotiation fails.
2024-10-10 16:31:18 -07:00
yifeizhuang 2129078dee
core: fix test flakiness in retriableStream hedging deadlock test (#11606) 2024-10-08 17:44:40 -07:00
Vindhya Ningegowda 2e9c3e19fb
xds: Update error handling for ADS stream close and failure scenarios (#11596)
When an ADS stream in closed with a non-OK status after receiving a response, new status will be updated to OK status. This makes the fail behavior consistent with gRFC A57.
2024-10-08 17:28:14 -07:00
yifeizhuang e59ae5fad0
rename grpc-context-override-opentelemetry and publish artifact (#11599) 2024-10-08 17:00:33 -07:00
Riya Mehta 9d252c2466
Don't use Utils.pickUnusedPort. (#11601) 2024-10-08 10:57:32 -07:00
Riya Mehta 0a3c03446c
s2a: Correct type of exception thrown (#11588)
* throw IllegalArgumentException in ProtoUtil.

* throw exception in TrustManager in more standard way.

* handle IllegalArgumentException in SslContextFactory.

* Don't throw error on unknown TLS version.
2024-10-08 10:56:43 -07:00
yifeizhuang 2aae68e117
report uncompressed message size when it does not need compression (#11598) 2024-10-07 10:44:27 -07:00
Kannan J 1ded8aff81
On result2 resolution result have addresses or error (#11330)
Combined success / error status passed via ResolutionResult to the NameResolver.Listener2 interface's onResult2 method - Addresses in the success case or address resolution error in the failure case now get set in ResolutionResult::addressesOrError by the internal name resolvers.
2024-10-07 17:55:56 +05:30
vinodhabib 94a0a0d1c7
example-gauth: Use application default creds instead of file argument (#11595)
Also removed unnecessary refreshAccessToken() and fixed the reference to README.md.

Fixes #5677
2024-10-04 11:42:25 +05:30
Riya Mehta 35f0d56894
s2a: don't use reflection to load token manager (#11590) 2024-10-03 14:45:01 -07:00
Larry Safran 9bb06af963
Change PickFirstLeafLoadBalancer to only have 1 subchannel at a time (#11520)
* Change PickFirstLeafLoadBalancer to only have 1 subchannel at a time if environment variable GRPC_SERIALIZE_RETRIES == true.

Cache serializingRetries value so that it doesn't have to look up the flag every time.

Clear the correct task when READY in processSubchannelState and move the logic to cancelScheduledTasks

Cleanup based on PR review

remove unneeded checks for shutdown.

* Fix previously broken tests

* Shutdown previous subchannel when run off end of index.

* Provide option to disable subchannel retries to let PFLeafLB take control of retries.

* InternalSubchannel internally goes to IDLE when sees TF when reconnect is disabled.
Remove an extra index.increment in LeafLB
2024-10-02 17:03:47 -07:00
Eric Anderson 6f3542297c okhttp: Don't warn about missing Conscrypt
When running on the JDK, it is quite normal for Conscrypt not to be
present. We'll end up using the JDK 9 ALPN API and everything will be
fine. On Android, it would be extremely rare for someone to completely
remove the default Android security providers, so the warning was almost
never going to trigger on that platform anyway.
2024-10-02 16:03:53 -07:00
Riya Mehta 959060a824
s2a: Address comments on S2A channel + stub (#11584)
* delete HandshakerServiceChannel.

* remove usage of S2AGrpcChannelPool + avoid creating Channel ref per conn.
2024-10-02 16:01:23 -07:00
Riya Mehta b8a0ba44af
s2a: clean up usage of certs (#11583)
* use CertificateUtils.

* Different names for each ec cert.

* Generate rsa certs with ::1 IP + delete CSRs.

* try.
2024-10-02 12:55:21 -07:00
Eric Anderson 9ab35a761b
util: Store only a list of children in MultiChildLB
A map of children is still needed, but is created temporarily on update.
The order of children is currently preserved, but we could use regular
HashMaps if that is not useful.
2024-10-02 11:03:44 -07:00
Riya Mehta 927d21541d
s2a: Move s2a implementation to internal package 2024-10-01 08:24:18 -07:00
MV Shiva f9ff526885
Update README etc to reference 1.67.1 2024-10-01 08:09:24 -07:00
Kannan J fa26a8bc5e
Make address resolution error use the default service config (#11577)
Fixes #11040.
2024-10-01 11:21:08 +05:30
Riya Mehta 50e442fea6
s2a: Include full exception in IOException 2024-09-30 15:05:14 -07:00
Riya Mehta 7b4b109309
s2a: remove channelPool from S2AChannelCredentials builder. (#11573) 2024-09-30 12:55:42 -07:00
Riya Mehta a140e1bb0c
s2a: Combine MtlsToS2ChannelCredentials and S2AChannelCredentials. (#11544)
* Combine MtlsToS2ChannelCredentials and S2AChannelCredentials.

* Check if file exists.

* S2AChannelCredentials API requires credentials used for client-s2a channel.

* remove MtlsToS2A library in BUILD.

* Don't check state twice.

* Don't check for file existence in tests.
2024-09-30 09:49:09 -07:00
Eric Anderson 795e2cc3ff util: Simplify MultiChildLB.getChildLbState()
Tests were converted to use getChildLbStateEag() if the argument was an
EAG, so the instanceof was no longer necessary.
2024-09-30 08:17:24 -07:00
Eric Anderson 8c3496943c xds: Have ClusterManagerLB use child map for preserving children
Instead of doing a dance of supplementing config so the later
createChildAddressesMap() won't delete children, just look at the
existing children and don't delete any that shouldn't be deleted.
2024-09-30 08:17:10 -07:00
Eric Anderson a908b5e40d android: For UDS, use fake IP instead of localhost
This avoids a DNS lookup, which can be slow and fail.

Fixes #11442
2024-09-30 08:16:42 -07:00
yifeizhuang d169a5de6f
interop-test: add opentelemetry tracing context propagation test (#11538) 2024-09-27 17:22:38 -07:00
Riya Mehta fa18fec36e
s2a: Address minor comments on PR#11113 (#11540)
* Use StandardCharsets in FakeS2AServerTest.
* Use add instead of offer in S2AStub.
* remove dead code in ProtoUtil.java.
* Mark convertTlsProtocolVersion as VisibleForTesting.
* S2AStub doesn't return responses at front of queue.
* Remove global SHARED_RESOURCE_CHANNELS.
* Don't suppress RethrowReflectiveOperationExceptionAsLinkageError.
* Update javadoc.
* Make clear which certs are used in tests + add how to regenerate.
2024-09-27 08:47:56 -07:00
Eric Anderson 9faa0f4eb0 xds: Update ClusterImpl test to work with PFLeafLB 2024-09-26 09:54:04 -07:00
erm-g 1c069375ce
core: SpiffeId parser (#11490)
SpiffeId parser compliant with [official spec](https://github.com/spiffe/spiffe/blob/main/standards/SPIFFE-ID.md)
2024-09-26 12:01:11 -04:00
Kannan J 64e3801538
Update RELEASING.md (#11559)
1. Removing $ when looking for the commit 'Start of  development cycle...' because it produces empty result with the $. It seems how the squash was done may influence whether $ will work or not.

2. Added an explicit git push instruction at step 5 of tagging and what base branch to use, since it will cause conflict with the default base branch used of master.
2024-09-26 21:04:57 +05:30
Eric Anderson 5dbca0e80c xds: Improve ClusterImpl's FakeSubchannel to verify state changes
The main goal was to make sure subchannels went CONNECTING only after a
connection was requested (since the test doesn't transition to
CONNECTING from TF). That helps guarantee that the test is using the
expected subchannel.

The missing ClusterImplLB.requestConnection() doesn't actually matter
much, as cluster manager doesn't propagate connection requests.
2024-09-25 11:11:44 -07:00
Vindhya Ningegowda 3e8ef8cf0c
xds: Check for validity of xdsClient in ClusterImplLbHelper (#11553)
* Added null check for xdsClient in onSubChannelState. This avoids NPE
for xdsClient when LB is shutdown and onSubChannelState is called later
as part of listener callback. As shutdown is racy and eventually consistent,
this check would avoid calculating locality after LB is shutdown.
2024-09-24 16:18:34 -07:00
Eric Anderson c92453fb14
s2a: Disabling publishing until it is ready for users 2024-09-24 15:40:40 -07:00
Mark S. Lewis 2ff837ab60 Update protobuf-java to address CVE-2024-7254
Signed-off-by: Mark S. Lewis <Mark.S.Lewis@outlook.com>
2024-09-24 07:39:50 -07:00
John Cormie 99be6e9852
Address Android 11's package visibility rules. (#11551) 2024-09-23 20:37:09 -07:00
Riya Mehta d8f73e0456
s2a: Address comments on PR#11113 (#11534)
* Mark S2A public APIs as experimental.

* Rename S2AChannelCredentials createBuilder API to newBuilder.

* Remove usage of AdvancedTls.

* Use InsecureChannelCredentials.create instead of Optional.

* Invoke Thread.currentThread().interrupt() in a InterruptedException block.
2024-09-20 15:53:14 -07:00
Riya Mehta e75a044107
s2a,netty: S2AHandshakerServiceChannel doesn't use custom event loop. (#11539)
* S2AHandshakerServiceChannel doesn't use custom event loop.

* use executorPool.

* log when channel not shutdown.

* use a cached threadpool.

* update non-executor version.
2024-09-20 12:32:54 -07:00
yifeizhuang 782a44ad62
Implement ContextStorageOverride for opentelemetry context bridge (#11523) 2024-09-19 09:52:38 -07:00
Eric Anderson 9b0c19e698 s2a: Cleanups to IntegrationTest
Move unused and unimportant fields to local variables. pickUnusedPort()
is inherently racy, so avoid using it when unnecessary. The channel's
default executor is fine to use, but if you don't like it
directExecutor() would be an option too. But blocking stub doesn't even
use the executor for unary RPCs. Thread.join() does not propagate
exceptions from the Thread; it just waits for the thread to exit.
2024-09-18 09:52:03 -07:00
Larry Safran bdc0530e1d
Fix slow tests that took 40 seconds to get through tearDown. (#11530) 2024-09-17 11:12:27 -07:00
Eric Anderson ce33df4a6f s2a: Use new-style syntax for plugins and remove unused deps
There may be more unused deps, but #11527 makes it far too painful for
me to bother to clean it up more.
2024-09-16 15:44:34 -07:00
yifeizhuang 5bec9096a2
Otel server context interceptor (#11500)
Add opentelemetry tracing API, guarded by environmental variable(disabled by default).
Use server interceptor to explicitly propagate span to the application thread.
2024-09-16 14:43:27 -07:00
MV Shiva 3a6be9ca1e
Detect transport executors with no remaining threads (#11503)
Detect misconfigured transport executors with too few threads that could further throttle the transport.

Fixes #11271
2024-09-16 16:32:52 +05:30
Riya Mehta b8c1aa517a
s2a: Add gRPC S2A (#11113) 2024-09-13 17:11:17 -07:00
Vindhya Ningegowda f3cf7c3c75
xds: Add xDS node ID in few control plane errors (#11519) 2024-09-12 15:40:20 -07:00
Eric Anderson 15cd2f9443 buildscripts: OS X env should be in macos.sh
unix.sh is shared by multiple OSes and environments. Clear JAVA_HOME,
since we never want to use that as PATH is more reliable, better
supported, and more typical.
2024-09-12 11:01:56 -07:00
Larry Safran 5de65a6d50
use an attribute from resolved addresses IS_PETIOLE_POLICY to control whether or not health checking is supported (#11513)
* use an attribute from resolved addresses IS_PETIOLE_POLICY to control whether or not health checking is supported so that top level versions can't do any health checking, while those under petiole policies can.

Fixes #11413
2024-09-06 11:43:07 -07:00
Vindhya Ningegowda f6d2f20fcd
Fix assertion to resolve flakiness in upstreamLocalityStatsList order (#11514) 2024-09-06 09:15:14 -07:00
Eric Anderson 721d063d55 core: touch() buffer when detach()ing
Detachable lets a buffer outlive its original lifetime. The new lifetime
is application-controlled. If the application fails to read/close the
stream, then the leak detector wouldn't make clear what code was
responsible for the buffer's lifetime. With this touch, we'll be able to
see detach() was called and thus know the application needs debugging.

Realized when looking at b/364531464, although I think the issue is
unrelated.
2024-09-05 14:39:33 -07:00
MV Shiva 8adfbf9ac5
Start 1.68.0 development cycle (#11507) 2024-09-04 19:33:28 +05:30
Vindhya Ningegowda 1dae144f0a
xds: Fix load reporting when pick first is used for locality-routing. (#11495)
* Determine subchannel's network locality from connected address, instead of assuming that all addresses for a subchannel are in the same locality.
2024-08-31 16:07:53 -07:00
yifeizhuang 421e2371e9
add OpenTelemetryTracingModule (#11477) 2024-08-30 12:17:28 -07:00
Terry Wilson c63e354883
rls: Fix log statements incorrectly referring to "LRS" (#11497) 2024-08-29 16:12:59 -07:00
Eric Anderson cfecc4754b Focus MultiChildLB updates around ResolvedAddresses of children
This makes ClusterManagerLB more straight-forward, focusing on just the
things that are relevant to it, and it avoids specialized map key
handling in updateChildrenWithResolvedAddresses().
2024-08-29 13:13:57 -07:00
Eric Anderson 4cb6465194 util: MultiChildLB children know if they are active
No need to look up in the map to see if they are still a child.
2024-08-29 08:05:16 -07:00
Eric Anderson 01389774d5 util: Remove child policy config from MultiChildLB state
The child policy config should be refreshed every address update, so it
shouldn't be stored in the ChildLbState. In addition, none of the
current usages actually used what was stored in the ChildLbState in a
meaningful way (it was always null).

ResolvedAddresses was also removed from createChildLbState(), as nothing
in it should be needed for creation; it varies over time and the values
passed at creation are immutable.
2024-08-29 08:04:50 -07:00
Eric Anderson 10d6002cbd xds: ClusterManagerLB must update child configuration
While child LB policies are unlikey to change for each cluster name (RLS
returns regular cluster names, so should be unique), and the
configuration for CDS policies won't change, RLS configuration can
definitely change.
2024-08-28 14:34:56 -07:00
Larry Safran d034a56cb0
Xds client split (#11484) 2024-08-23 13:05:38 -07:00
Eric Anderson ee3ffef3ee core: In PF, disjoint update while READY should transition to IDLE
This is the same as if we received a GOAWAY. We wait for the next RPC to
begin connecting again. This is InternalSubchannel's behavior.
2024-08-22 11:23:11 -07:00
Eric Anderson f20167d602 util: Replace RR.EmptyPicker with FixedResultPicker 2024-08-22 10:29:06 -07:00
Eric Anderson 6c9f92a725 interop-testing: Move interop tests only used by test client to the test client
This removes the auth dependency and the implicit xds/orca from
AbstractInteropTest for things that weren't used in all but one case.
2024-08-22 10:28:41 -07:00
Kurt Alfred Kluever 2fe1a13cd0
Migrate from `Charsets` to `StandardCharsets`. (#11482) 2024-08-22 12:11:43 +05:30
Eng Zer Jun 66075eab85
.github/workflows: Bump action major versions from Node16 to Node20 (#11476)
GitHub began the Node16 deprecation process a year ago [1][2]. This
commit updates all workflows to use the latest Node20 actions.

[1]: https://github.blog/changelog/2023-09-22-github-actions-transitioning-from-node-16-to-node-20/
[2]: https://github.blog/changelog/2024-03-07-github-actions-all-actions-will-run-on-node20-instead-of-node16-by-default/
2024-08-22 12:01:02 +05:30
Eric Anderson 9762945f81 core: In PF, remove extraneous index.reset()
The index was just reset by updateGroups().
2024-08-21 07:16:29 -07:00
Eric Anderson 82a8d57396 core: In PF, remove useless requestConnection for CONNECTING subchannel
It doesn't do anything.

Call scheduleNextConnection() unconditionally since it is responsible
for checking if `enableHappyEyeballs == true`. It's also surprising to
check in the CONNECTING case but not the IDLE case.
2024-08-21 07:16:29 -07:00
Eric Anderson 2c93791c98 core: PF.requestConnection() is possible when READY
requestConnection() is public API, and it is allowed to be called even
if the load balancer is already READY.
2024-08-21 07:16:29 -07:00
Eric Anderson 4914ffc59a core: Avoid exception handling in PF for invalid index
It is trivial to avoid the exception from
addressIndex.getCurrentAddress(). The log message was inaccurate, as the
subchannel might have been TRANSIENT_FAILURE. The only important part of
the condition was whether the subchannel was the current subchannel.
2024-08-21 07:16:29 -07:00
Eric Anderson 33687d3983 core: Remove useless NPE check for syncContext in PF
It will never throw, because it would only throw if helper is null, but
helper is checkNotNull()ed in the constructor. It could have checked for
a null return value instead; since it hasn't been, it is clear we don't
need this check.
2024-08-21 07:16:29 -07:00
Eric Anderson 8bd97953ad core: Never have null PF Index
This prevents many null checks and combines two code paths, with no
additional allocations.
2024-08-21 07:16:29 -07:00
Eric Anderson 778a00b623 util: Remove MultiChildLB.getImmutableChildMap()
No usages actually needed a map nor a copy.
2024-08-17 08:55:22 -07:00
Eric Anderson c120e364d2 core: PF Index.size() should be number of addresses
This would impact TRANSIENT_FAILURE and refreshNameResolver() logic for
dual-stack endpoints.
2024-08-17 08:54:18 -07:00
John Cormie 6dbd1b9d5a
Add newAttachMetadataServerInterceptor() MetadataUtil (#11458) 2024-08-14 16:11:49 +00:00
sunpe 6a9bc3ba17 example: delete duplicate and unused code in KeepAliveClient.java 2024-08-14 07:24:47 -07:00
Eric Anderson ff8e413760
Remove direct dependency on j2objc
Bazel had the dependency added because of #5046, where Guava was
depending on it as compile-only and Bazel build have "unknown enum
constant" warnings. Guava now has a compile dependency on j2objc, so
this workaround is no longer needed. There are currently no version skew
issues in Gradle, which was the only usage.
2024-08-13 21:33:55 -07:00
Eric Anderson 909c4bc382 util: Remove minor convenience functions from MultiChildLB
These were once needed to be overridden (e.g., by RoundRobinLB), but
now nothing overrides them and MultiChildLB doesn't even call one of
them.
2024-08-13 21:29:08 -07:00
Eric Anderson 75012a5be2
examples: Upgrade Maven plugin versions
Upgrade Maven to 3.8.8, the oldest supported version, as the plugins required a
newer version.
2024-08-13 16:43:44 -07:00
Kannan J d5840448d4
Update README etc to reference 1.66.0 (#11472) 2024-08-13 23:52:35 +05:30
Eric Anderson c2eccca3bc cronet: Add internal API to specify Network
cl/661194496
2024-08-13 11:22:01 -07:00
Eric Anderson fd8734f341 xds: Delegate more RingHashLB address updates to MultiChildLB
Since 04474970 RingHashLB has not used
acceptResolvedAddressesInternal(). At the time that was needed because
deactivated children were part of MultiChildLB. But in 9de8e443, the
logic of RingHashLB and MultiChildLB.acceptResolvedAddressesInternal()
converged, so it can now swap back to using the base class for more
logic.
2024-08-12 16:40:00 -07:00
Eric Anderson b5989a5401 util: MultiChildLb children should always start with a NoResult picker
That's the obvious default, and all current usages use (something
equivalent to) that default.
2024-08-12 16:39:44 -07:00
Eric Anderson a6f8ebf33d Remove implicit requestConnection() on IDLE from MultiChildLB
One LB no longer needs to extend ChildLbState and one has to start, so
it is a bit of a wash. There are more LBs that need the auto-request
logic, but if we have an API where subclasses override it without
calling super then we can't change the implementation in the future.
Adding behavior on top of a base class allows subclasses to call super,
which lets the base class change over time.
2024-08-12 15:40:01 -07:00
Eric Anderson 4ab34229fb netty: Use DefaultELG with LocalChannel in test
LocalChannel is not guaranteed to be compatible with NioEventLoopGroup,
and is failing with Netty 4.2.0.Alpha3-SNAPSHOT.

See #11447
2024-08-12 15:39:12 -07:00
Eric Anderson 0d47f5bd1b
xds: WRRPicker must not access unsynchronized data in ChildLbState
There was no point to using subchannels as keys to
subchannelToReportListenerMap, as the listener is per-child. That meant
the keys would be guaranteed to be known ahead-of-time and the
unsynchronized getOrCreateOrcaListener() during picking was unnecessary.

The picker still stores ChildLbStates to make sure that updating weights
uses the correct children, but the picker itself no longer references
ChildLbStates except in the constructor. That means weight calculation
is moved into the LB policy, as child.getWeight() is unsynchronized, and
the picker no longer needs a reference to helper.
2024-08-12 11:23:37 -07:00
Eric Anderson 0d2ad89016 xds: Remove useless ExperimentalApi for WRR
A package-private class isn't visible and `@Internal` is stronger than
experimental. The only way users should use WRR is via the
weight_round_robin string, and that's already not suffixed with
_experimental.

Closes #9885
2024-08-12 11:19:56 -07:00
yifeizhuang 043ba556b8
otel tracing: add binary format, grpcTraceBinContextPropagator (#11409)
* otel tracing: add binary format, grpcTraceBinContextPropagator

* exception handling, use api base64 encoder omit padding
remove binary format abstract class in favor of binary marshaller
2024-08-12 11:16:54 -07:00
Eric Anderson d1dcfb0451 xds: Replace WrrHelper with a per-child Helper
There's no need to assume which child makes a subchannel based on the
subchannel address.
2024-08-09 16:24:51 -07:00
Eric Anderson 2f4f7f0ece util: Delete unused MultiChildLB.ChildLbState.getSubchannels() 2024-08-09 15:38:20 -07:00
Eric Anderson f866c805c2 util: SocketAddress.toString() cannot be used for equality
Some addresses are equal even though their toString is different
(InetSocketAddress ignores the hostname when it has an address). And
some addresses are not equal even though their toString might be the
same (AnonymousInProcessSocketAddress doesn't override toString()).

InetSocketAddress/InetAddress do not cache the toString() result. Thus,
even in the worst case that uses a HashSet, this should use less memory
than the earlier approach, as no strings are formatted. It probably also
significantly improves performance in the reasonably common case when an
Endpoint is created just for looking up a key, because the string
creation in the constructor isn't then amorized.
updateChildrenWithResolvedAddresses(), for example, creates n^2 Endpoint
objects for lookups.
2024-08-09 15:38:03 -07:00
Larry Safran 72a977bf7f
Dualstack example (#11451) 2024-08-08 15:59:57 -07:00
Petr Portnov | PROgrm_JARvis 40e2b165b7
Make once-set fields of `AbstractClientStream` `final` (#11389) 2024-08-08 10:48:12 +05:30
Eric Anderson 18d73a3681
CONTRIBUTING.md: Update commit guidelines
It came up in #11073, and I saw it could use a little updating. Notably,
I'm linking to a guide to what Git commit messages should look like. I
also tried to make the language less heavy-handed and demanding.
2024-08-07 16:34:11 -07:00
Kannan J 70ae83288d
Upgrade Netty to 4.1.110 and tcnative to 2.0.65 (#11444)
Upgrade Netty to 4.1.110 and tcnative to 2.0.65.
2024-08-06 20:38:08 +05:30
Kurt Alfred Kluever 06135a0745 Migrate from the deprecated `Charsets` constants (in Guava) to the `StandardCharsets` constants (in the JDK)
cl/658539667
2024-08-05 13:31:08 -07:00
Eric Anderson 9bed655c56 Revert "Netty upgrade to 4.1.110 in grpc-java (#11273)"
This reverts commit f9b072cfe2.

Changes from the release process got mixed in with the commit.
2024-08-02 15:30:31 -07:00
Eric Anderson 15456f8f0a core: In PF, pass around SubchannelData instead of Subchannel
Each usage of the subchannel immediately looked up the SubchannelData.
2024-08-02 14:23:25 -07:00
Kannan J f9b072cfe2
Netty upgrade to 4.1.110 in grpc-java (#11273)
* Bump Netty to 4.1.110.Final.
2024-08-03 01:05:44 +05:30
Eric Anderson e567b4427a
core: Don't reuse channels in PickFirstLeafLB test
PickFirstLeafLB uses channel reference equality to see if it has
re-created subchannels. The tests reusing channels breaks the expected
invariant.
2024-08-02 11:40:02 -07:00
Sergii Tkachenko c29763d886
xds: Import RLQS protos (#11418)
Imports the protos of Rate Limiting Quota Service (RLQS) and Rate
Limit Quota HTTP Filter.

Note: the list below only shows the new top-level protos, and excludes
their direct and transitional dependencies (those from import
statements).

#### RLQS Imports
- Service — envoy/service/rate_limit_quota/v3/rlqs.proto
  (Service): 7b8a304
- HTTP Filter —
  envoy/extensions/filters/http/rate_limit_quota/v3/rate_limit_quota.proto:
  49c77c4

#### CEL Imports
- Initial third-party repo setup: 99a64bd
- Parsed CEL Expression: cel/expr/syntax.proto: 99a64bd
- Parsed and type-checked CEL Expression: cel/expr/checked.proto:
  99a64bd


#### Required typed_config extensions
##### `bucket_matchers` predicate input
- `HttpAttributesCelMatchInput` —
  xds/type/matcher/v3/http_inputs.proto: 54924e0
- `HttpRequestHeaderMatchInput` —
  envoy/type/matcher/v3/http_inputs.proto: 49c77c4

##### `bucket_matchers` predicate custom_match
- `CelMatcher` — xds/type/matcher/v3/cel.proto: 54924e0
2024-08-02 10:35:29 -07:00
Kurt Alfred Kluever 00136096ed Migrate from the deprecated Charsets constants (in Guava) to the StandardCharsets constants (in the JDK).
cl/658546708
2024-08-02 09:54:05 -07:00
Eric Anderson 1f9d502261 interop-testing: Remove unused implementation deps
googleapis and rls can still be used at runtime.
2024-08-02 09:52:34 -07:00
Eric Anderson 780e4ba086 api: Move ClientStreamTracerTest from core to api
It uses nothing from core and tests an api class.
2024-08-02 09:06:04 -07:00
Eric Anderson b8e3ae9a4b android-interop-testing: Enable -Xlint:deprecation 2024-08-02 09:05:47 -07:00
Kannan J 90d0fabb1f
Introduce onResult2 in NameResolver Listener2 that returns Status
Lets the Name Resolver receive the status of the acceptance of the name resolution by the load balancer.
2024-08-02 20:40:31 +05:30
Eric Anderson 9bc1a93f6e xds: Add test that uses real DnsNR with ClusterResolverLB
This can detect failures like the UnsupportedOperationException from
ebffb0a6.
2024-08-02 07:26:11 -07:00
Larry Safran cc1cbe9871
Revert "Enable new PickFirst LB (#11348)" (#11425)
This reverts commit ccfd351a2e.
2024-08-01 11:30:36 -07:00
Larry Safran 941a1c37a3
Add dualstack interop test kokoro config (#11422) 2024-07-31 14:56:07 -07:00
Eric Anderson ebffb0a6b2 Revert "Introduce onResult2 in NameResolver Listener2 that returns Status (#11313)"
This reverts commit 9ba2f9dec5.

It causes a channel panic due to unimplemented onResult2().

```
java.lang.UnsupportedOperationException: Not implemented.
        at io.grpc.NameResolver$Listener2.onResult2(NameResolver.java:257)
        at io.grpc.internal.DnsNameResolver$Resolve.lambda$run$0(DnsNameResolver.java:334)
        at io.grpc.SynchronizationContext.drain(SynchronizationContext.java:94)
        at io.grpc.SynchronizationContext.execute(SynchronizationContext.java:126)
	at io.grpc.internal.DnsNameResolver$Resolve.run(DnsNameResolver.java:333)
```

b/356669977
2024-07-31 14:16:01 -07:00
Eric Anderson dc83446d98 xds: Stop extending RR in WRR
They share very little code, and we really don't want RoundRobinLb to be
public and non-final. Originally, WRR was expected to share much more
code with RR, and even delegated to RR at times. The delegation was
removed in 111ff60e. After dca89b25, most of the sharing has been moved
out into general-purpose tools that can be used by any LB policy.

FixedResultPicker now has equals to makes it as a EmptyPicker
replacement. RoundRobinLb still uses EmptyPicker because fixing its
tests is a larger change. OutlierDetectionLbTest was changed because
FixedResultPicker is used by PickFirstLeafLb, and now RoundRobinLb can
squelch some of its updates for ready pickers.
2024-07-31 13:32:49 -07:00
Kannan J 0090a526d7
Start 1.67.0 development cycle (#11416) 2024-07-31 11:13:59 +05:30
Sergii Tkachenko 0017c98f6b
xds: cncf/xds proto sync to 2024-07-24 (#11417)
`cncf/xds`: Sync protos to the latest imported version
cncf/xds@024c85f (commit 2024-07-23, cl/655545156).

Should be a noop, just a routine xDS proto update to make upcoming
RLQS-related imports simpler, see related #11401.

Note that CEL is only added as a bazel dependency as now it's required
to build cncf/xds. Actual third-party source import will be done in
the follow up PR, where RLQS dependencies are added to the import
scripts.
2024-07-30 12:17:49 -07:00
Jiajing LU 448ec4f37e
xds: XdsClient should unsubscribe on last resource (#11264)
Otherwise, the server will continue sending updates and if we
re-subscribe to the last resource, the server won't re-send it. Also
completely remove the per-type state, as it could only add confusion.
2024-07-30 08:46:01 -07:00
Sergii Tkachenko 96a788a349
xds: Envoy proto sync to 2024-07-06 (#11401)
`envoyproxy/envoy`: Sync protos to the latest imported version
ab911ac2ff
(commit 2024-07-06, cl/651956889).

Should be a noop, just a routine xDS proto update to make upcoming
RLQS-related imports simpler.
2024-07-29 09:18:18 -07:00
Kannan J 9ba2f9dec5
Introduce onResult2 in NameResolver Listener2 that returns Status (#11313)
Introducing NameResolver listener method "Status Listener2::onResult2(ResolutionResult)" that returns Status of the acceptance of the name resolution by the load balancer, and the Name Resolver will call this method for both success and error cases.
2024-07-26 15:43:36 +05:30
Eric Anderson 786523dca4 xds: WRR rr_fallback should trigger with one endpoint weight
From gRFC A58:
> When less than two subchannels have load info, all subchannels will
> get the same weight and the policy will behave the same as round_robin
2024-07-25 11:14:21 -07:00
Eric Anderson b108ed3ddf
api: Give instruments a toString() including their name
This makes it much easier when testing to understand what the
values/arguments are at various parts of the code.
2024-07-24 21:30:10 -07:00
subhraOffGit eb4cdf7959
Update MAINTAINERS.md (#11241)
Removed sanjaypujare from Active Maintainers list and added him to
Emeritus Maintainers list. Removed the org names from Emeritus
maintainers list
2024-07-24 10:19:10 -07:00
Eric Anderson d3c2f5a2da bazel: Don't use artifact() for protobuf deps
We don't include protobuf in IO_GRPC_GRPC_JAVA_ARTIFACTS, so there might
not actually be an alias available for it to @com_google_protobuf. While
we could add it, it is easier to use the @com_google_protobuf references
directly.

This was preventing `bazel query 'deps(//...)' from succeeding, because
it couldn't find javalite.
2024-07-24 07:56:09 -07:00
Eric Anderson 7a25e68958 bazel: Use com_google_protobuf instead of com_google_protobuf_javalite
Since Bazel 6 [1], Bazel has used com_google_protobuf for javalite. We
only used the other repo because Bazel expected it, which was because
Protobuf split out javalite to a separate branch for a while. Since
everything is now reunified, we can use a singular protobuf repo.

1. abdb1d6bfe
2024-07-24 07:55:17 -07:00
Eric Anderson 5ec0187e23 examples: Fix WORKSPACE to allow referencing grpc-xds 2024-07-23 16:11:44 -07:00
Eric Anderson 36e687f9d9 examples: Add bzlmod support
This also updates the version number of the grpc-java module as part of
the release process.
2024-07-23 08:32:13 -07:00
Eric Anderson 85e0a01ecd util: Mark GracefulSwitchLB.switchTo() deprecated 2024-07-23 08:31:49 -07:00
Eric Anderson 9269050125 examples: For Bazel, remove compat repo for maven_install
It hasn't been needed since 0064991. In that commit the main WORKSPACE
was cleaned up, but not the examples.
2024-07-22 16:35:42 -07:00
Kannan J 0aa976c4eb
V1reflectionservice (#11237)
V1 version of the proto reflection service, as the v1.alpha service has been deprecated.

* Create V1 alpha service wrapping underlying V1 service, by modifying the ServerServiceDefinition.

* Create ProtoReflectionService for the v1alpha proto by producing a ServerServiceDefinition constructed from that of the v1 service but with the service and method names and proto descriptors modified.

Issue #6724.
2024-07-19 19:27:13 +05:30
Eric Anderson 704123ed65 Upgrade Truth to 1.4.4 2024-07-17 21:02:23 -07:00
Eric Anderson 1ec5fab749
RELEASING.md: Simplify steps and add post-release upgrade (#11384) 2024-07-16 09:43:36 -07:00
erm-g 516dec989a
util: Align AdvancedTlsX509{Key and Trust}Manager (#11385)
* Swap internal key/cert args

* Deprecate *FromFile methods

* Test for client trusted socket
2024-07-16 12:33:19 -04:00
Sreenithi Sridharan 92f4fde61b
Increase timeout of the LB test suite to 5 hours (#11356). 2024-07-16 10:58:19 +05:30
Eric Anderson 7ba293f49f
Upgrade ErrorProne Core to 2.28.0 2024-07-12 14:59:20 -07:00
Eric Anderson 2452730192 Name old undertow servlet lib with version number
This makes it clearer it isn't intended to be upgraded. We do this
already for the other servlet containers (e.g., jetty-servlet10).
2024-07-12 11:31:24 -07:00
Eric Anderson 8ce4456f2c kokoro: Port android.sh to Kokoro Ubuntu 22.04
Java 8 isn't installed, and was needed by the old Android SDK. With the
current SDK, it can work on Java 11 but it needs some dependencies
installed.

Python 2.7 isn't available any more, but instead of porting to Python 3,
it was just replaced with a curl command.
2024-07-12 07:47:42 -07:00
Eric Anderson 64ac792b5e Upgrade Gradle and Gradle plugins 2024-07-11 16:28:51 -07:00
Eric Anderson a977385187
Upgrade dependencies
The GSON upgrade slightly changed an error string, so the test was
updated to be less of a change detector.

Some OpenTelemetry dependencies are alpha versions, so needed an
adjustment in build.gradle to accept the versions. Similarly, Undertow
includes Final in its version numbers which needs to be accepted.
2024-07-11 15:09:00 -07:00
maleo 6dd6ca9f90 Remove udpa aa repo alias for xds 2024-07-11 10:47:23 -07:00
cfredri4 dcb1c018c6 Fix AdvancedTlsX509TrustManager to handle client side validation of socket 2024-07-11 10:25:00 -07:00
erm-g 658cbf6cfe
util: Stabilize AdvancedTlsX509TrustManager 2024-07-11 09:11:48 -07:00
Andrey Ermolov b181e495ab ExperimantalApi to deprecated methods 2024-07-11 08:21:19 -07:00
Larry Safran 506192872e
Restore old behavior of NettyAdaptiveCumulator, but avoid using that class if Netty is on version 4.1.111 or later. (#11367) 2024-07-10 10:38:46 -07:00
erm-g ecae9b797d
security: Add updateIdentityCredentials methods to AdvancedTlsX509KeyManager. (#11358)
Add new 'updateIdentityCredentials' methods with swapped (chain, key) signatures.
2024-07-10 12:30:27 +05:30
John Cormie 21dec30924
Establish a default connect timeout. (#11359)
Enables the timer added in #11137
2024-07-09 12:46:21 -07:00
Eric Anderson 0ff3f8e4ac kokoro: Adjust android CIs to work with Ubuntu 22.04 image
It doesn't have Android SDK nor the VERSION file. See also d654707838
2024-07-09 08:16:24 -07:00
Eric Anderson 77b3bb77ef buildSrc: Avoid duplicating group in checkForUpdates
getModule() returns a ModuleIdentifier, not a string. And the
identifier's toString() includes the module's group.
2024-07-09 08:12:55 -07:00
Eric Anderson 47aa7b9bca Upgrade Checkstyle to 10.17.0
The code changes are to place all overloaded methods next to each other.
2024-07-09 08:12:33 -07:00
Matthieu MOREL 37d19babff
use grpc-proto bazel_dep instead of http_archive (#11349) 2024-07-09 13:01:43 +05:30
Eric Anderson 64cf9e8c20 Update README etc to reference 1.65.0 2024-07-08 12:43:25 -07:00
Eric Anderson 71eb5fb9f0
compiler: Upgrade from CentOS 7 to AlmaLinux 8
CentOS 7 became end-of-life on July 1st and is no longer working. We now
dynamically link against libstdc++, as RHEL 8 doesn't support static
linking: https://access.redhat.com/articles/rhel8-abi-compatibility

We now use objdump in check-artifact for all linux architectures. This
avoids using a mix of objdump and ldd. ldd shows transitive
dependencies, which is less convenient.
2024-07-03 13:26:14 -07:00
Eric Anderson 0454b9e328 xds: Avoid switchTo in PriorityLb 2024-07-03 10:32:38 -07:00
Eric Anderson dfb22ba97c xds: Avoid switchTo in ClusterImplLb and ClusterResolverLb 2024-07-03 10:32:38 -07:00
Eric Anderson 749b2e0abc util: Avoid switchTo in OutlierDetectionLb 2024-07-03 10:32:38 -07:00
Eric Anderson 2c49cc4197 xds: Avoid switchTo in WrrLocalityLb and WeightedTargetLb 2024-07-03 10:32:38 -07:00
Eric Anderson ebed04798c util: Add GracefulSwitchLb config
This is to replace switchTo(), to allow composing GracefulSwitchLb with
other helpers like MultiChildLb. It also prevents users of
GracefulSwitchLb from needing to use ServiceConfigUtil.
2024-07-03 10:32:38 -07:00
João Vitor Stein 062ebb4d77
grpc-core: use retryThrottling from defaultServiceConfig 2024-07-03 08:19:22 -07:00
Benjamin Peterson 6e25c03a7b core: remove GrpcUtil.getHost
This utility is not relevant on supported JDK versions anymore.
2024-07-02 08:18:03 -07:00
Larry Safran ccfd351a2e
Enable new PickFirst LB (#11348) 2024-06-28 16:30:54 -07:00
Larry Safran 0b68eff120
core:Change address deduping to be across EAGs (#11345)
* Change dedup to be cross EAG, not just within an EAG
2024-06-28 14:58:50 -07:00
yifeizhuang 9e2145970a
doc: add document on WRR configure examples from service config and xds (#11344) 2024-06-27 16:55:38 -07:00
Larry Safran 7a53fa8bc1
Dualstack interop testing enablement (#11231)
* Have java test server listen on appropriate address based upon new optional flag "address_type"
2024-06-27 16:37:48 -07:00
Larry Safran 3777c303f5
deduplicate addresses within a single EAG (#11342) 2024-06-27 16:12:24 -07:00
Larry Safran 603033f1fa
Add null check to cleanup to avoid NPE (#11340) 2024-06-27 14:08:05 -07:00
cooper 25a8b7c507 Support setting onReadyThreshold through AbstractStub
Add copy of the onReadyThreshold property when copying CallOptions(fix bug)
2024-06-27 09:36:49 -07:00
Eric Anderson e7c3803b5a
xds: Remove unused opencensus-proto dependency
opencensus-proto is old generated code, which is not compatible with
protobuf-java 4.27.2 and may not be fixed since the project is dead.
Since it is unused, I think this doesn't cause any trouble for
downstream users trying to use protobuf-java 4.x. Related to #11015.
2024-06-26 15:30:31 -07:00
John Cormie 5770114d08
google-java-format binder/src/*/*.java (#11297)
https://github.com/grpc/grpc-java/blob/master/CONTRIBUTING.md#code-style

We've been talking about an incremental approach in https://github.com/grpc/grpc-java/issues/1664 but https://github.com/google/google-java-format/issues/1114 causes a bunch of manual formatting toil every time I run ~/google-java-format-diff.py because we have a LOT of lines >100 characters. Establishing a gjf-clean baseline will make things a lot easier for me.
2024-06-24 09:42:31 -07:00
Matthew Stevenson 46e54aeb4b
util: Add ExperimentalApi to AdvancedTlsX509KeyManager
There may be reordering of `updateIdentityCredentialsFromFile()`
arguments. Avoid making it stable while it is being evaluated.
2024-06-24 09:20:43 -07:00
Vindhya Ningegowda 4849e0a191
core: Add label values size validation in MetricRecorder (#11306)
Enhance MetricRecorder: Validate label values count against registered label keys count for default record APIs
2024-06-21 17:06:55 -07:00
Vindhya Ningegowda 1eec1459c2
Remove unused imports from CSM Observability example (#11307) 2024-06-21 16:17:33 -07:00
Vindhya Ningegowda 9e287f939e
all:Add GCP CSM Observability (#11305) 2024-06-21 14:35:39 -07:00
Vindhya Ningegowda 1aabc12955
Upgrade OpenTelemetry to 1.39.0 (#11300) 2024-06-21 14:35:24 -07:00
Vindhya Ningegowda a409a1b459
examples: Add gRPC OpenTelemetry example (#11299)
Add gRPC OpenTelemetry example. The example uses Prometheus exporter to export metrics and can be verified locally.
It also provides an example using LoggingMetricExporter to export and log the metrics using java.util.logging.
2024-06-21 14:35:02 -07:00
Larry Safran 9b39b3ec6b
Eliminate NPE after recovering from a temporary name resolution failure. (#11298)
* Eliminate NPE after recovering from a temporary name resolution failure.

* Add test case for 2 failing subchannels to make sure it causes channel to go into TF.
2024-06-21 13:20:44 -07:00
Larry Safran 0fea7dd32e
netty:Fix Netty composite buffer merging to be compatible with Netty 4.1.111 (#11294)
* Use addComponent instead of addFlattenedComponent and do not append to components that are composites.
2024-06-20 15:55:06 -07:00
Sergii Tkachenko d57f2719b2
services: restore //services:binarylog bazel target (#11292)
The target was wrongly deleted in 75492c8 / #10832.
See details in https://github.com/grpc/grpc-java/issues/4017#issuecomment-2159516522.
2024-06-20 15:40:52 -07:00
John Cormie 15ad9f546c
binder: Simplify ownership of ServerAuthInterceptor's executor. (#11293)
Allocating this executor before BinderServer even exists is convoluted and actually leaks if the built server is never actually start()ed. Instead, have BinderServer own this executor directly, with a lifetime from start() until termination. Pass it to the ServerAuthInterceptor via TransportAuthorizationState Attribute instead of at construction time.
2024-06-18 18:56:33 -07:00
Eric Anderson c540993aaa
bazel: Upgrade and fix import issues with envoy_api
Bazel was not updated as part of feab4e54. Also, `(( X++ ))` exits 1 if
X is zero. The patch to data-plane-api was upstreamed in
https://github.com/envoyproxy/envoy/pull/34759
2024-06-17 14:58:14 -07:00
Vindhya Ningegowda 889893dd8c
examples: Add GCP CSM Observability example (#11267)
Add GCP CSM observability example client and example server.
2024-06-13 13:12:01 -07:00
Terry Wilson 85ed053006
api: Stabilize ServerBuilder.AddServices() (#11285) 2024-06-13 13:06:01 -07:00
Vindhya Ningegowda b43d2830e4
opentelemetry: Add explicit histogram buckets for per-call metrics (#11281)
Add explicit histogram buckets for per-call metrics as specified in gRFC A66 https://github.com/grpc/proposal/blob/master/A66-otel-stats.md#units.
2024-06-12 16:57:33 -07:00
Eric Anderson a4ef77174d
Disable ErrorProne's MutableConstantField check (#11283)
It is simultaneously overly zealous and doesn't notice basic cases. As
noticed in #11281.
2024-06-12 13:42:20 -07:00
Mike Kruskal 5322414505
Advertise editions support in plugin 2024-06-12 10:47:54 -07:00
Kannan J 14fd81f59b
Adding missing synchronization in the runnable that is causing access guard violation error. (#11277) 2024-06-12 11:09:59 +05:30
John Cormie 7fee6a3fea
Don't block an offload thread when the client's SecurityPolicy is async (#11272)
https://github.com/grpc/grpc-java/issues/10566
2024-06-09 22:38:41 -07:00
Eric Anderson 47249c5f00 Start 1.66.0 development cycle 2024-06-07 10:33:57 -07:00
Daniel Liu 4943b4c1e5 fix logging to be compatible with Android for AdvancedTlsX509KeyManager 2024-06-07 10:02:06 -07:00
Mateus Azis 34ee600dce
Wait for all BinderServerTransports to terminate before ... (#11240)
... returning security policy executor to the object pool.

Fixes #10897.
2024-06-06 14:52:11 -07:00
John Cormie 1670e97f74
Reject further SETUP_TRANSPORT requests post-BinderServer shutdown (#11260)
Fixes https://github.com/grpc/grpc-java/issues/8931
2024-06-06 14:18:45 -07:00
Eric Anderson a28357e197 okhttp: Workaround SSLSocket not noticing socket is closed
Using --runs_per_test=1000, this changes the flake rate of TlsTest from
2% to 0%.

While I believe it is possible to write a reliable test for this
(including noticing the SSLSocket behavior), it was becoming too
invasive so I gave up.

Fixes #11012
2024-06-06 09:39:35 -07:00
Eric Anderson 0a4df9f93c binder: Make transport notification methods package-private
These are overrides of BinderTransport itself, so not used elsewhere.
They are essentially private. It was scary seeing `@GuardedBy` for a
public method. I copied the annotation to the base class to make sure
ErrorProne could verify the calls.
2024-06-06 08:59:32 -07:00
John Cormie 791f894e25
binder: Add a connection timeout (#11255)
Timeout is initially infinite so that we can release/import the supporting code and the behavior change independently.

Fixes #11137
2024-06-05 15:11:30 -07:00
Eric Anderson 22642465d3 gcp-csm-o11y: Add resource attributes from environment
This fixes csm_remote_workload_namespace_name being unknown when running
the interop test.
2024-06-05 10:21:50 -07:00
Eric Anderson 9e2cca08fa gcp-csm-o11y: Use xds's shadow configuration
This prevents mixing shaded and non-shaded class files. We do the same
thing in all the other projects that depend on xds.
2024-06-05 06:56:27 -07:00
Eric Anderson 0358c508da gcp-csm-o11y: Enable maven-publish plugin 2024-06-05 06:23:42 -07:00
Eric Anderson 839d2770ab
interop-testing: Add gcp-csm-o11y testing support 2024-06-04 17:15:58 -07:00
Eric Anderson b2731f27ad core: Delete AbstractTransportTest.clientShutdownBeforeStartRunnable
The test was added in e4e7f3a06 when InProcess stopped returning a
Runnable from start(). In c5a63a1 we realized (indirectly) that there's
no point in using the Runnable any more.

This test failed with Binder (which seems to have been using the
Runnable unnecessarily), and InProcess, Netty, and OkHttp don't use the
Runnable. Instead of fixing it, we'll just move toward stopping using
Runnable.

I'm not removing the Runnable usage from Binder in this commit because
this test is currently causing CI failures and I don't want to do a
behavior change when fixing it.
2024-06-04 13:43:14 -07:00
Eric Anderson 62cf8427be gcp-csm-o11y: s/csm.service_namespace/csm.service_namespace_name/
Just a typo, maybe because service_namespace is used in filter metadata
from CDS.
2024-06-04 13:41:22 -07:00
Eric Anderson 9792c9f106 kokoro: Remove unavailable API levels 21-23
There are no longer any devices (virtual or otherwise) that support API
level 21, 22, or 23. Google Play services is still supporting API level
21 (although there is a pattern of notifying of dropped levels in July,
and dropping them in August).
2024-06-04 13:05:15 -07:00
Eric Anderson c5a63a16a7 core: Remove "can't call transport listener from start()" restriction
This hasn't been needed since f8f569e07, when InternalSubchannel stopped
calling start() with a lock held. Note that also means no transport
needs to return a Runnable (but some still are).

I had noticed in e4e7f3a06 that it was safe for InProcess to call the
listener directly within start(), but I didn't notice this Javadoc that
said it wasn't allowed.
2024-06-04 11:26:08 -07:00
Eric Anderson 0fcd8cc19f kokoro: Add psm-csm build config 2024-06-03 11:12:36 -07:00
Eric Anderson dc490ae0cb
gcp-csm-observibility: Fill in experimental issue URL 2024-05-30 16:42:18 -07:00
erm-g 781b4c4575
security: Stabilize AdvancedTlsX509KeyManager. (#11139)
* Clean up and de-experimentalization of KeyManager

* Unit tests for API validity.
2024-05-30 13:54:11 -04:00
Eric Anderson df8cfe9ddc Create gcp-csm-observability 2024-05-29 14:40:44 -07:00
Eric Anderson 6dde844c04 opentelemetry: Plumb plugins for CSM o11y 2024-05-29 14:40:44 -07:00
Eric Anderson 5c6b80881d rls: Make LinkedHashLruCache non-threadsafe
CachingRlsLbClient already calls it with a lock held. The only reason
the cache needs to manage the lock itself is for the periodic cleanup.
Let the consumer of the cache handle the timer.
2024-05-29 08:24:56 -07:00
Mir3605 c31dbf48ad
Minor - add missing instruction (#11131)
The "list" instruction was missing, so the command didn't work properly
2024-05-29 12:45:44 +05:30
John Cormie df01271687
Use a builder to eliminate BinderServer's long list of ctor params (#11235) 2024-05-28 19:34:55 -07:00
Eric Anderson e4e7f3a068
inprocess: Fix listener race if transport is shutdown while starting
Returning the runnable did nothing, as both the start method and the
runnable are run within the synchronization context. I believe the
Runnable used to be required in the previous implementation of
ManagedChannelImpl (the lock-based implementation before we created
SynchronizationContext).

This fixes a NPE seen in ServerImpl because the server expects proper
ordering of transport lifecycle events.
```
Uncaught exception in the SynchronizationContext. Panic!
java.lang.NullPointerException: Cannot invoke "java.util.concurrent.Future.cancel(boolean)" because "this.handshakeTimeoutFuture" is null
	at io.grpc.internal.ServerImpl$ServerTransportListenerImpl.transportReady(ServerImpl.java:440)
	at io.grpc.inprocess.InProcessTransport$4.run(InProcessTransport.java:215)
	at io.grpc.SynchronizationContext.drain(SynchronizationContext.java:94)
```

b/338445186
2024-05-28 15:47:15 -07:00
Eric Anderson 107fdb4b7c core: Make RPC buffering comment more clear
It wasn't entirely clear what "it" referred to.
2024-05-28 15:26:13 -07:00
Eric Anderson 75fa441fc9
xds: Plumb the Cluster's filterMetadata to RPCs
This will be used by CSM observability, and may get exposed to further
uses in the future.
2024-05-24 15:08:36 -07:00
Eric Anderson 018917ae59 core: Restore optimization for InProcess RPC order
fea577c80 disabled an optimization that some tests notice, as it can
change execution order. This restores the old behavior, at slight
expense to seeing relationship between in-use tracking and idle mode.
2024-05-24 13:02:17 -07:00
Eric Anderson 960012d76e api: Add ClientStreamTracer.inboundHeaders(Metadata)
This will be used by the metadata exchange of CSM. When recording
per-attempt metrics, we really need per-attempt data and can't leverage
ClientInterceptors.
2024-05-24 11:28:40 -07:00
Eric Anderson fea577c804
core: Exit idle mode when delayed transport is in use
8844cf7b8 triggered a regression where a new RPC wouldn't cause the
channel to exit idle mode, if an RPC was still progressing on an old
transport. This was already possible previously, but was racy.
8844cf7b8 made it less racy and more obvious.

The two added `exitIdleMode()` calls in this commit are companions to
those in `enterIdleMode()`, which detect whether the channel should
immediately exit idle mode.

Noticed in cl/635819804.
2024-05-23 14:45:38 -07:00
John Cormie 0b5f38d942
Use the builder pattern to replace BinderClientTransport's long ctor arg list (#11220) 2024-05-23 11:50:37 -07:00
Colin Alworth 6aa063990a
servlet: Update Servlet container test versions (#11212)
Verifies that latest versions of Tomcat/Undertow/Jetty pass
integration tests - I manually verified that all ignored tests still
fail.

Two tests failed in Jetty, it appears that the integration test
anticipates that the server implementation is willing to send larger
trailers than the client SETTINGS frame allows for. Since the server
refuses to send too large of headers/trailers, the client does not
receive the too-large payloads, and doesn't fail with the expected
message. This change was introduced in Jetty 10.0.15/11.0.11. Those
tests are ignored.
2024-05-23 09:49:34 -07:00
Eric Anderson db96219be1
core: Remove direct test dependency on inprocess
An inprocess class was just being abused. Note that grpc-testing depends
on inprocess, so there is still an indirect dependency on inprocess
present.
2024-05-22 14:50:26 -07:00
Eric Anderson 58bab7434a opentelemetry: Use dep from gradle/libs.versions.toml 2024-05-21 10:29:27 -07:00
Terry Wilson 8aaace12eb
Update README etc to reference 1.64.0 (#11213) 2024-05-15 13:31:10 -07:00
Nikolay Firov f995c121e9
Include com_google_protobuf_javalite to MODULE.bazel to fix bzlmod querying graph in end-user repo (#11147)
* Fix 3d party dependency use_repo

* remove protobuf as it is already added as module dep

* fix

* fix

* fix

* return com_google_protobuf_javalite archive and use it in MODULE.bazel
2024-05-15 17:21:23 +05:30
Eric Anderson 8844cf7b87 core: Fully delegate picks to DelayedClientTransport
DelayedClientTransport already had to handle all the cases, so
ManagedChannelImpl picking was acting only as an optimization.
Optimizing DelayedClientTransport to avoid the lock when not queuing
makes ManagedChannelImpl picking entirely redundant, and allows us to
remove the duplicate race-handling logic.

This avoids double-picking when queuing, where ManagedChannelImpl does a
pick, decides to queue, and then DelayedClientTransport re-performs the
pick because it doesn't know which pick version was used. This was
noticed with RLS, which mutates state within the picker.
2024-05-14 11:37:14 -07:00
Eric Anderson d9e09c285b all: Add opentelemetry
This adds opentelemetry to the shared javadoc (but also other things
like having its tests contribute to code coverage).
2024-05-14 10:28:02 -07:00
Eric Anderson e82b8f0674
opentelemetry: Mark registerGlobal() as experimental 2024-05-14 10:26:56 -07:00
Eric Anderson f9b6e5f92d rls: Guarantee backoff will update RLS picker
Previously, picker was likely null if entering backoff soon after
start-up. This prevented the picker from being updated and directing
queued RPCs to the fallback. It would work for new RPCs if RLS returned
extremely rapidly; both ManagedChannelImpl and DelayedClientTransport do
a pick before enqueuing so the ManagedChannelImpl pick could request
from RLS and DelayedClientTransport could use the response. So the test
uses a delay to purposefully avoid that unlikely-in-real-life case.

Creating a resolving OOB channel for InProcess doesn't actually change
the destination from the parent, because InProcess uses directaddress.
Thus the fakeRlsServiceImpl is now being added to the fake backend
server, because the same server is used for RLS within the test.

b/333185213
2024-05-13 16:29:05 -07:00
Vindhya Ningegowda 77a1e77e11
xds, rls: Experimental metrics are disabled by default (#11196)
Experimental metrics (i.e WRR and RLS metrics) are disabled by default. Users are expected to explicitly enable while configuring metrics.
2024-05-10 17:46:58 -07:00
Vindhya Ningegowda 5ba1a55637
opentelemetry: Publish grpc opentelemetry (#11187)
publish grpc opentelemetry
2024-05-09 13:24:52 -07:00
Terry Wilson 511b9c3a5b
rls: Add gauge metric recording (#11175)
Adds these gauges:
- grpc.lb.rls.cache_entries
- grpc.lb.rls.cache_size
2024-05-08 15:15:34 -07:00
Eric Anderson 7a663f633c api: Hide internal metric APIs
Some APIs were marked experimental but had internal APIs in their
surface. These were all changed to internal. And then the internal APIs
were mostly hidden from generated documentation.

All these APIs will eventually become public and maybe even stable. But
they need some iteration before we're ready for others to start using
them.
2024-05-08 10:24:24 -07:00
Larry Safran 59b189bf91
Change HappyEyeballs and new pick first LB flags default value to false (#11120)
* Change HappyEyeballs flag default value to false since some G3 users are seeing problems.
Put the flag logic in a common place for PickFirstLeafLoadBalancer & WRR's test.

* Set expected requestConnection count based on whether happy eyeballs is enabled or not

* Disable new PickFirstLB

* Fix test expectations to handle both new and old PF LB paths.
2024-05-08 10:08:23 -07:00
Eric Anderson d366d74fa6
opentelemetry: Rename and stabilize API OpenTelemetryModule
OpenTelemetryModule is renamed to GrpcOpenTelemetry. The Builder is now
`final`, although that should only impact mocks as it had a private
constructor.

Fixes #10591
2024-05-08 07:51:17 -07:00
Eric Anderson 5a6745b97e opentelemetry: Missing locality should be empty string
From gRFC A78:

> If no locality information is available, the label will be set to the
> empty string.
2024-05-08 07:50:28 -07:00
Eric Anderson 45a91bd035 xds: Add WRR metric test with real channel 2024-05-08 07:50:09 -07:00
Terry Wilson 2bc4306940
xds: Include locality label in WRR metrics (#11170) 2024-05-07 11:40:03 -07:00
Eric Anderson 54ac06ae30 rls: Add metric test with real channel 2024-05-07 10:06:46 -07:00
Eric Anderson 6bede04d9f opentelemetry: Add optional grpc.lb.locality to per-call metrics
The optional label API was added in 4c78a974 and xds_cluster_impl was
plumbed in 077dcbf9.

From gRFC A78:

> ### Optional xDS Locality Label
>
> When xDS is used, it is desirable for some metrics to include an optional
> label indicating which xDS locality the metrics are associated with.
> We want to provide this optional label for the metrics in both the
> existing per-call metrics defined in [A66] and in the new metrics for
> the WRR LB policy, described below.
>
> If locality information is available, the value of this label will be of
> the form `{region="${REGION}", zone="${ZONE}", sub_zone="${SUB_ZONE}"}`,
> where `${REGION}`, `${ZONE}`, and `${SUB_ZONE}` are replaced with the
> actual values.  If no locality information is available, the label will
> be set to the empty string.
>
> #### Per-Call Metrics
>
> To support the locality label in the per-call metrics, we will provide
> a mechanism for LB picker to add optional labels to the call attempt
> tracer.  We will then use this mechanism in the `xds_cluster_impl`
> policy's picker to set the locality label. ...
>
> This label will be available on the following per-call metrics:
> - `grpc.client.attempt.duration`
> - `grpc.client.attempt.sent_total_compressed_message_size`
> - `grpc.client.attempt.rcvd_total_compressed_message_size`
2024-05-07 09:00:08 -07:00
hakusai22 6ec744f2a0
Fix various typos (#11144) 2024-05-06 20:29:44 -07:00
Eric Anderson 354b028cae
Add gauge metric API and Otel implementation
This is needed by gRFC A78 for xds metrics, and for RLS metrics. Since
gauges need to acquire a lock (or other synchronization) in the
callback, the callback allows batching multiple gauges together to avoid
acquiring-and-requiring such locks.

Unlike other metrics, gauges are reported on-demand to the MetricSink.
This means not all sinks will receive the same data, as the sinks will
ask for the gauges at different times.
2024-05-06 11:38:04 -07:00
Eric Anderson 8516cfef9c opentelemetry: Add grpc.target label to per-call metrics
As defined by gRFC A66, the target is on all client-side per-call
metrics (both call and attempt).
2024-05-06 10:53:46 -07:00
Eric Anderson ca35577327 Add internal channel builder API to get target
This will be used for gRFC A66's OTel per-RPC metric label:

> `grpc.target` : Canonicalized target URI used when creating gRPC
> Channel, e.g. "dns:///pubsub.googleapis.com:443",
> "xds:///helloworld-gke:8000". Canonicalized target URI is the form
> with the scheme included if the user didn't mention the scheme
> (`scheme://[authority]/path`).

The majority of the changes are to move target computation from
ManagedChannelImpl into the builder. A small hack API was added to
ManagedChannelBuilder to get the target to create an interceptor.
2024-05-06 10:53:46 -07:00
Eric Anderson cffc12a074 opentelemetry: Fix checking wrong metric for null 2024-05-06 10:06:36 -07:00
Eric Anderson c368a0f9f8
Migrate GlobalInterceptors to ConfiguratorRegistry
This should preserve all the existing behavior of GlobalInterceptors as
used by grpc-gcp-observability, including it disabling the implicit
OpenCensus integration.

Both the old and new API are internal. I hid Configurator and
ConfiguratorRegistry behind Internal-prefixed classes, like had been
done with GlobalInterceptors to further discourage use until the API is
ready.

GlobalInterceptorsTest was modified to become ConfiguratorRegistryTest.
2024-05-06 07:27:41 -07:00
Eric Anderson 077dcbf90f xds: Plumb locality in xds_cluster_impl and weighted_target
As part of gRFC A78:

> To support the locality label in the WRR metrics, we will extend the
> `weighted_target` LB policy (see A28) to define a resolver attribute
> that indicates the name of its child. This attribute will be passed
> down to each of its children with the appropriate value, so that any
> LB policy that sits underneath the `weighted_target` policy will be
> able to use it.

xds_cluster_impl is involved because it uses the child names in the
AddressFilter, which must match the names used by weighted_target.
Instead of using Locality.toString() in multiple policies and assuming
the policies agree, we now have xds_cluster_impl decide the locality's
name and pass it down explicitly. This allows us to change the name
format to match gRFC A78:

> If locality information is available, the value of this label will be
> of the form `{region="${REGION}", zone="${ZONE}",
> sub_zone="${SUB_ZONE}"}`, where `${REGION}`, `${ZONE}`, and
> `${SUB_ZONE}` are replaced with the actual values. If no locality
> information is available, the label will be set to the empty string.
2024-05-03 12:42:31 -07:00
Vindhya Ningegowda 13a929025b
Add MetricSink implementation for gRPC OpenTelemetry
This adds the following components that are required for gRPC A79
non-per-call metrics architecture.

- MetricSink implementation for gRPC OpenTelemetry
- Configurator for plumbing per call metrics ClientInterceptor and
  ServerStreamTracer.Factory via unified OpenTelemetryModule.
2024-05-03 10:45:46 -07:00
Sergii Tkachenko 6585d053b1
buildscripts: simplify PSM interop Kokoro buildscripts (#11121)
Integrates the new features of the the Kokoro PSM Interop install library introduced in grpc/psm-interop#73.

Nearly all common functionality was moved from per-language/per-branch PSM Interop build scripts to [psm_interop_kokoro_lib.sh](https://github.com/grpc/psm-interop/blob/main/.kokoro/psm_interop_kokoro_lib.sh):
1. The list of tests in the each test suite 
2. Per-test-suite flag customization
3. `run_test` methods
4. `build_docker_images_if_needed` methods
5. Generic `build_test_app_docker_images` methods (simple docker build + docker push + docker tag). grpc-java is one exception, as it doesn't run docker directly, but a cloudbuild flow.

Now all PSM Interop jobs share the same buildscripts by all test suites:
1.  buildscript that invokes the test: `psm-interop-test-{language}.sh` (configured as `build_file` in the build cfg)
2. buildscript that builds the xDS test client/server and publishes them as a Docker image: `psm-interop-build-{language}.sh` (conventional name called from `psm_interop_kokoro_lib.sh`)

`psm-interop-test-{language}.sh`:
1. Sets `GRPC_LANGUAGE`, `BUILD_SCRIPT_DIR` environment variables.
2. Downloads the shared `psm_interop_kokoro_lib.sh` from the main branch of the psm-interop repo.
3. Sources `psm-interop-build-{language}.sh`
4. Calls `psm::run "${PSM_TEST_SUITE}"` (`PSM_TEST_SUITE` configured in the cfg file).

`psm-interop-build-{language}.sh`:
1. Defines `psm::lang::build_docker_images` which is called from `psm_interop_kokoro_lib.sh`.
2. Invokes any repo-specific logic.
3. May use `psm::build::docker_images_generic` for generic Docker build, tag, push, or provide implement its own build/publish method.

References:
- b/288578634
- See the full list of the new features at grpc/psm-interop#73.
- Additional fixes to the shared lib: grpc/psm-interop#78, grpc/psm-interop#79
2024-05-03 09:58:03 -07:00
Terry Wilson 64ae9f057a
Start 1.65.0 development cycle (#11143) 2024-05-01 16:58:08 -07:00
Terry Wilson a1d19327fe
rls: Add the target label to RLS counter metrics (#11142) 2024-05-01 16:19:56 -07:00
Terry Wilson 35a171bc1d
xds: include the target label to WRR metrics (#11141) 2024-05-01 15:20:38 -07:00
Terry Wilson a9fb272b78
rls: add counter metrics (#11138)
Adds the following metrics to the RlsLoadBalancer:
- grpc.lb.rls.default_target_picks
- grpc.lb.rls.target_picks
- grpc.lb.rls.failed_picks
2024-05-01 11:24:38 -07:00
Eric Anderson 4561bb5b80 Plumb target to load balancer
gRFC A78 has WRR and pick-first include a `grpc.target` label, defined
in A66:

> `grpc.target` : Canonicalized target URI used when creating gRPC
> Channel, e.g. "dns:///pubsub.googleapis.com:443",
> "xds:///helloworld-gke:8000". Canonicalized target URI is the form
> with the scheme included if the user didn't mention the scheme
> (`scheme://[authority]/path`). For channels such as inprocess channels
> where a target URI is not available, implementations can synthesize a
> target URI.
2024-05-01 09:19:45 -07:00
Eric Anderson 27d57585cd api: Return a noop MetricRecorder from Helper by default
Since 06df25b65d, WRR has been calling this method, and it will get an
exception. We don't want WRR to be broken until we have MetricRecorder
fully plumbed.
2024-04-30 07:18:56 -07:00
Eric Anderson 4c78a9746c
Plumb optional labels from LB to ClientStreamTracer
As part of gRFC A78:

> To support the locality label in the per-call metrics, we will provide
> a mechanism for LB picker to add optional labels to the call attempt
> tracer.
2024-04-29 16:30:51 -07:00
Terry Wilson 06df25b65d
core,xds: Metrics recording in WRR LB (#11129)
Adds the recording of the four metrics documented in:

https://github.com/grpc/proposal/blob/master/A78-grpc-metrics-wrr-pf-xds.md#weighted-round-robin-lb-policy
2024-04-26 15:59:49 -07:00
Vindhya Ningegowda 795ee0f6e3
Add MetricRecorder implementation (#11128)
* added MetricRecorderImpl and unit tests for MetricInstrumentRegistry

* updated MetricInstrumentRegistry to use array instead of ArrayList

* renamed record<>Counter APIs to add<>Counter. Added check for mismatched label values

* added lock for instruments array
2024-04-26 13:47:55 -07:00
Eric Anderson da619e2bde rls: Fix time handling in CachingRlsLbClient
`getMinEvictionTime()` was fixed to make sure only deltas were used for
comparisons (`a < b` is broken; `a - b < 0` is okay). It had also
returned `0` by default, which was meaningless as there is no epoch for
`System.nanoTime()`. LinkedHashLruCache now passes the current time into
a few more functions since the implementations need it and it was
sometimes already available. This made it easier to make some classes
static.
2024-04-25 15:38:39 -07:00
Eric Anderson 056195401f rls: Document RefCountedChildPolicyWrapperFactory as non-threadsafe
Instead of having docs in RefCountedChildPolicyWrapperFactory saying
that every method was guarded by a lock, I added `@GuardedBy("lock")`
within CachingRlsLbClient, so now it is clearly not thread-safe and the
lock protects access. The AtomicLong was replaced with a long since
1) there was no multi-threading and 2) the logic was not atomic-safe
which was misleading.
2024-04-25 15:35:50 -07:00
Eric Anderson 2840fd6b47 opentelemetry: Remove delayed attempt recording
In OpenCensus recording an attempt was delayed in order to wait for
inboundUncompressedSize(). But we don't need that in OpenTelemetry, and
could have removed this code when copying from OpenCensus.
2024-04-25 14:59:33 -07:00
rtadepalli 5c9b492318
Add `StatusProto.toStatusException` overload to accept `Throwable` (#11083)
* Add `StatusProto.toStatusException` overload to accept `Throwable`
---------

Co-authored-by: Eric Anderson <ejona@google.com>
2024-04-24 18:05:54 -07:00
Ryan P. Brewster e036b1b198 netty: Allow deframer errors to close stream with a status code
Today, deframer errors cancel the stream without communicating a status code
to the peer. This change causes deframer errors to trigger a best-effort
attempt to send trailers with a status code so that the peer understands
why the stream is being closed.

Fixes #3996
2024-04-24 14:37:37 -07:00
Eric Anderson 11612b484a Upgrade OpenTelemetry to 1.36.0 2024-04-23 17:24:47 -07:00
Larry Safran 9bf04db0d3
reorder bazel rule parameters to satisfy CheckBzlFormat (#11118) 2024-04-22 16:14:47 -07:00
Benjamin Peterson fb9a10809f
netty: Release SendGrpcFrameCommand when stream is missing (#11116)
`sendGrpcFrame` owns the buffer in `SendGrpcFrameCommand`. If the frame is not handed off to netty, it needs to be released in the method.

https://github.com/grpc/grpc-java/issues/11115
2024-04-22 10:27:39 -07:00
Ashok Varma 77e59b29dd cronet: Update to StandardCharsets and assertNotNull API's 2024-04-22 09:54:49 -07:00
Ashok Varma 163efa3716 cronet: Update to Java-8 API's and tighten the scopes 2024-04-22 09:54:49 -07:00
Ashok Varma c703a1ee07 cronet: @javadoc update android permission MODIFY_NETWORK_ACCOUNTING (deprecated) => UPDATE_DEVICE_STATS 2024-04-22 09:54:49 -07:00
Ashok Varma 5a8da19f32 cronet: Update Cronet to latest release + Move to Stable Cronet APIs. 2024-04-22 09:54:49 -07:00
Eric Anderson 9de8e44384 util: Remove deactivation and GracefulSwitchLb from MultiChildLb
It is easy to manage these things outside of MultiChildLb and it makes
the shared code easier and use less memory. In particular, we don't want
to use many instances of GracefulSwitchLb in virtually every policy
simply because it was needed in one or two cases.
2024-04-22 07:48:49 -07:00
Eric Anderson 7f0a1910d3 xds: Directly manage deactivation in cluster manager 2024-04-22 07:48:49 -07:00
Eric Anderson 61bf21e2a1 xds: Swap RingHashLb to use lazy child, instead of deactivation 2024-04-22 07:48:49 -07:00
Alex Panchenko 8a21afcc9e
compiler: add option `@generated=omit` (#11086)
related to #11081
2024-04-18 18:34:04 -07:00
Laglangyue 52e65ec0d8
minor: remove the unnecessary final,static (#11098) 2024-04-18 15:26:01 -07:00
hvadehra add8c37a41
Add `load()` statements for the Bazel builtin top-level java symbols (#11105)
Loads are being added in preparation for moving the symbols out of Bazel and into `rules_java`.
2024-04-17 16:43:21 -07:00
Vindhya Ningegowda c404c9f66c
Add MetricRecorder and MetricSink interface (#11109)
Adds interfaces required for recording metrics from gRPC components. And added API to get `MetricRecorder` in `LoadBalancer.Helper` and add `MetricSink` to `ManagedChannelBuilder`.
2024-04-17 15:10:57 -07:00
Sergii Tkachenko e490273edd
netty: Handle write queue promise failures (#11016)
Handles Netty write frame failures caused by issues in the Netty
itself.

Normally we don't need to do anything on frame write failures because
the cause of a failed future would be an IO error that resulted in
the stream closure.  Prior to this PR we treated these issues as a
noop, except the initial headers write on the client side.

However, a case like netty/netty#13805 (a bug in generating next
stream id) resulted in an unclosed stream on our side. This PR adds
write frame future failure handlers that ensures the stream is
cancelled, and the cause is propagated via Status.

Fixes #10849
2024-04-16 16:27:51 -07:00
Vindhya Ningegowda 497e155217
Add Metric Instrument Registry (#11103)
* added metric instrument registry
2024-04-12 13:42:40 -07:00
Sergii Tkachenko 34e241a60e
buildscripts: Migrate PSM Interop to Artifact Registry (#11079)
From Container Registry (gcr.io) to Artifact Registry (pkg.dev).
2024-04-08 10:27:09 -07:00
yifeizhuang 167a2031e2
Update README etc to reference 1.63.0 (#11076) 2024-04-05 10:40:01 -07:00
Eric Anderson 1d6f1f1b42 bazel: Verify Maven deps in bzlmod and WORKSPACE match
The text between the GRPC_DEPS_{START,END} must be identical in
formatting. Probably not a problem in general and not necessarily bad.
But it is simplistic.

Eric waking up this morning:
> We need more sed.
2024-04-04 14:05:05 -07:00
Eric Anderson 32d48ae89a bazel: Fix formatting with buildifier
Keys and dependencies are sorted.
2024-04-04 11:50:07 -07:00
Keith Smiley d1890c0acc
bazel: Add support for bzlmod (#11046) 2024-04-04 08:36:55 -07:00
Sergii Tkachenko b6ca908de8
MAINTAINERS.md: Add Kannan (#11057)
- [kannanjgithub](https://github.com/kannanjgithub), Google LLC
2024-04-03 14:28:14 -07:00
Eric Anderson 6e97b180b4
rls: Synchronization fixes in CachingRlsLbClient
This started with combining handleNewRequest with asyncRlsCall, but that
emphasized pre-existing synchronization issues and trying to fix those
exposed others. It was hard to split this into smaller commits because
they were interconnected.

handleNewRequest was combined with asyncRlsCall to use a single code
flow for handling the completed future while also failing the pick
immediately for thottled requests. That flow was then reused for
refreshing after backoff and data stale. It no longer optimizes the RPC
completing immediately because that would not happen in real life; it
only happens in tests because of inprocess+directExecutor() and we don't
want to test a different code flow in tests. This did require updating
some of the tests.

One small behavior change to share the combined asyncRlsCall with
backoff is we now always invalidate an entry after the backoff.
Previously the code could replace the entry with its new value in one
operation if the asyncRlsCall future completed immediately. That only
mattered to a single test which now sees an EXPLICIT eviction.

SynchronizationContext used to provide atomic scheduling in
BackoffCacheEntry, but it was not guaranteeing the scheduledRunnable was
only accessed from the sync context. The same was true for calling up
the LB tree with `updateBalancingState()`. In particular, adding entries
to the cache during a pick could evict entries without running the
cleanup methods within the context, as well as the RLS channel
transitioning from TRANSIENT_FAILURE to READY. This was replaced with
using a bare Future with a lock to provide atomicity.

BackoffCacheEntry no longer uses the current time and instead waits for
the backoff timer to actually run before considering itself expired.
Previously, it could race with periodic cleanup and get evicted before
the timer ran, which would cancel the timer and forget the
backoffPolicy. Since the backoff timer invalidates the entry, it is
likely useless to claim it ever expires, but that level of behavior was
preserved since I didn't look into the LRU cache deeply.

propagateRlsError() was moved out of asyncRlsCall because it was not
guaranteed to run after the cache was updated. If something was already
running on the sync context, then RPCs would hang until another update
caused updateBalancingState().

Some methods were moved out of the CacheEntry classes to avoid
shared-state mutation in constructors. But if we add something in a
factory method, we want to remove it in a sibling method to the factory
method, so additional code is moved for symmetry. Moving shared-state
mutation ouf of constructors is important because 1) it is surprising
and 2) ErrorProne doesn't validate locking within constructors. In
general, having shared-state methods in CacheEntries also has the
problem that ErrorProne can't validate CachingRlsLbClient calls to
CacheEntry. ErrorProne can't know that "lock" is already held because
CacheEntry could have been created from a _different instance_ of
CachingRlsLbClient and there's no way for us to let ErrorProne prove it
is the same instance of "lock".

DataCacheEntry still mutates global state that requires a lock in its
constructor, but it is less severe of a problem and it requires more
choices to address.
2024-04-03 12:22:04 -07:00
Rostislav 58de563fa4
examples: support retry policy example for bazel build
According to the docs, I can use bazel to build examples, but
retry-example is not supported in bazel config. So If you'll try to
build this example with bazel, you'll get an error:


```
examples git:(master) ✗ bazel build :retrying-hello-world-server :retrying-hello-world-client
ERROR: Skipping ':retrying-hello-world-client': no such target '//:retrying-hello-world-client': target 'retrying-hello-world-client' not declared in package '' defined by /Users/rostik404/projects/grpc-java/examples/BUILD.bazel
ERROR: no such target '//:retrying-hello-world-client': target 'retrying-hello-world-client' not declared in package '' defined by /Users/rostik404/projects/grpc-java/examples/BUILD.bazel
INFO: Elapsed time: 0.331s
INFO: 0 processes.
ERROR: Build did NOT complete successfully
```
2024-04-01 15:07:10 -07:00
François JACQUES 8050723397
OkHttpServer: support maxConcurrentCallsPerConnection (Fixes #11062). (#11063)
* Add option in OkHttpServerBuilder
* Add value as MAX_CONCURRENT_STREAM setting in settings frame sent by the server to the client per connection
* Enforce limit by sending a RST frame with REFUSED_STREAM error
2024-04-01 08:39:33 -07:00
Alex Panchenko e36f099be9
StatusException/StatusRuntimeException hide stack trace in a simpler way (#11064) 2024-04-01 08:31:13 -07:00
Eric Anderson 0866e716d6 README.md: Mention the netty-shaded "transport"
You have to dig deep into SECURITY.md to hear about what's in
netty-shaded. Add a small blub for it in the README.

Inspired by discussion on #10931
2024-03-29 11:02:29 -07:00
François JACQUES d21fe32bea
okhttp: Remove finished stream even if a pending stream was started
Fixes #11053
2024-03-29 10:00:32 -07:00
Kannan J 097a46b761 Use empty string instead of null for endpoint identification algorithm to disable server hostname verification, since null value gets ignored in Sun's SSLEngine implementation. 2024-03-28 16:58:48 -07:00
David Burns 00649913b0
bazel: Use the `artifact` macro for loading maven deps
The recommended way to load dependencies from `rules_jvm_external`
is to make use of the `@maven` workspace, and the most readable
way of doing that is to use the `artifact` macro provides.

This removes the need to generate the "compat" namespaces, which
`rules_jvm_external` provided for backwards compatibility with
older releases. This change also sets things up for supporting
`bzlmod`: this requires all workspaces accessed by a library to
be named "up front" in the `MODULE.bazel` file. This way, the
only repo that needs to be exported is `@maven`, rather than the
current huge list.
2024-03-28 14:33:32 -07:00
Larry Safran 4ef1baddd2
core: Remove useless ExperimentalApi annotation from pick first
PickFirstLeafLoadBalancer is in internal and also isn't public.
2024-03-28 08:07:53 -07:00
Eric Anderson 569b426d62 core: Improve clarity of RpcProgress meanings 2024-03-27 16:11:26 -07:00
Eric Anderson e6305930de Specify a locale for upper/lower case conversions
None of these conversions should use the arbitrary system locale. Error
Prone will help prevent these getting introduced in the future.

Fixes #10372
2024-03-27 15:58:34 -07:00
Ran 37263b774d
Make setOnReadyThreshold() a noop method instead of abstract. (#11044)
Make setOnReadyThreshold() a noop method instead of abstract
2024-03-27 14:56:13 -07:00
Kannan J 2c5f0c22cd
core: Transition to CONNECTING immediately when exiting idle
The name resolver takes some time before it returns addresses. While waiting the channel will be IDLE instead of the proper CONNECTING. This generally doesn't matter since RPCs behave similarly for IDLE and CONNECTING, but is confusing for users when watching channel.getState() closely.

Fixes #10517.
2024-03-27 11:40:13 -07:00
hypnoce f7ee5f3182 servlet: Check log fine level before hex string conversion. Fixes #11031. 2024-03-25 08:18:44 -07:00
abtom 537dbe826a
binder: Helper class to allow in process servers to use peer uids in test (#11014) 2024-03-22 15:57:29 -07:00
Terry Wilson 10cb4a3bed
util: Status desc for outlier detection ejection (#11036)
Including a Status description makes it easier to debug subchannel
closure issues if it's clear that a subchannel became unavailable because
of an outlier detection ejection.
2024-03-22 14:40:06 -07:00
Larry Safran bdb623031f
Fix retry race condition that can lead to double decrementing inFlightSubStreams and so miss calling closed (#11026) 2024-03-22 10:01:58 -07:00
yifeizhuang b3ffb5078d
Start 1.64.0 development cycle (#11030) 2024-03-22 09:32:10 -07:00
Eric Anderson 3abab95e75
core: Provide DEADLINE_EXCEEDED insights for context deadline
We provided extra details when the RPC is killed by CallOptions'
Deadline, but didn't do the same for Context.

To avoid duplicating code, things were restructured, including the
threading. There are more code flows now, but I think the
multi-threading came out more obvious and less error-prone. I didn't
change the status when the deadline is already expired, because the
text is shared with DelayedClientCall and AbstractInteropTest doesn't
distinguish between the two cases.

This is a roll-forward that avoids a NPE when cancel() is called
without an earlier call to start().

As seen at b/300991330
2024-03-21 17:02:06 -07:00
Larry Safran 51f811df86
Enable Happy Eyeballs by default (#11022)
* Flip the flag

* Fix test flakiness where IPv6 was not considered loopback
2024-03-21 16:59:54 -07:00
James Duong 2c83ef0632
Allow configuration of the queued byte threshold at which a Stream is considered not ready (#10977)
* Allow the queued byte threshold for a Stream to be ready to be configurable

- on clients this is exposed by setting a CallOption
- on servers this is configured by calling a method on ServerCall or ServerStreamListener
2024-03-21 15:37:26 -07:00
Terry Wilson 68eb639b1c
Revert "core: Provide DEADLINE_EXCEEDED insights for context deadline" (#11024)
This reverts commit 0e31ac9303.
2024-03-19 10:06:01 -07:00
Larry Safran 38f968fafb
Have EDS resource parse the additional addresses from envoy message (#11011)
* Have EDS resource parse the additional addresses from envoy message
* Update respositories.bzl to point to current grpc-proto instead of a 2021 version.
* Update respositories.bzl to point to recent cncf/xds and envoyproxy/data-plane-api
* Add cncf_upda to repositories.bzl
2024-03-15 12:26:21 -07:00
Eric Anderson 0e31ac9303 core: Provide DEADLINE_EXCEEDED insights for context deadline
We provided extra details when the RPC is killed by CallOptions'
Deadline, but didn't do the same for Context.

To avoid duplicating code, things were restructured, including the
threading. There are more code flows now, but I think the
multi-threading came out more obvious and less error-prone. I didn't
change the status when the deadline is already expired, because the
text is shared with DelayedClientCall and AbstractInteropTest doesn't
distinguish between the two cases.

As seen at b/300991330
2024-03-15 10:44:44 -07:00
Sergii Tkachenko fafd99db52
(minor) Add missing update notes for cronet to libs.versions.toml (#11007)
Related issue blocking the update (#10396) was created during
dependency update #10359, but I forgot to add the note to
libs.versions.toml.
2024-03-14 10:40:00 -07:00
Larry Safran 36e9f0dfac
core: Eliminate NPE seen in PickFirstLeafLoadBalancer (#11013)
ref b/329420531
2024-03-13 20:53:34 -07:00
Larry Safran 8a9ce990b0
Enable new PF by default (#11002) 2024-03-12 14:50:40 -07:00
Larry Safran 27a3d8e278
Eliminate validation so that code path is more heavily exercised (#11005)
* Eliminate validation so that code path is more heavily exercised
2024-03-12 13:41:03 -07:00
Sergii Tkachenko b3475a0e46
api: Remove ExperimentalApi from Attributes.Builder.discard (#11004)
Now tracked together with Attributes:
https://github.com/grpc/grpc-java/issues/1764.

Closes #5777.
2024-03-11 16:15:03 -07:00
Sergii Tkachenko 0d749c5943
xds: Stabilize CsdsService (#11003)
To make it stable, this PR hides protobuf from being exposed via the
API.

Note: this breaks ABI of `CsdsService.streamClientStatus` and
`CsdsService.fetchClientStatus`, but these methods should not
normally be called by the user.

Closes #8016.
2024-03-11 16:14:05 -07:00
Eric Anderson 403aa8189d Upgrade to Gradle 8.6 and upgrade plugins
The gradle wrapper was removed from example-oauth because we don't want
to maintain the wrapper copy in each example (at least right now it
doesn't make sense for it to be the only other example to have the
gradle wrapper).
2024-03-11 15:44:20 -07:00
Larry Safran d1c406bd23
Prepare to switch flag to use new PickFirstLeafLoadBalancer by default (#10998)
* Fix PickFirstLeafLoadBalancer and tests to work when it is used.
* Actually use EAG attributes for subchannels.
2024-03-11 14:12:56 -07:00
Sergii Tkachenko ebbe0673f3
alts,census,gcp-observability: Explicitly set grpc-context as an implementation dependency (#10997)
Override google-auth `io.grpc:grpc-context` dependency with our own
`project(":grpc-context")`.

This fixes the issue with classes depending on `grpc-alts`
implementation receiving very (!) old `io.grpc:grpc-context:1.27.2`
as a transitive dependency of `com.google.auth`.

Projects `grpc-census` `grpc-gcp-observability` are affected in the
similar way, except `io.grpc:grpc-context:1.59.1` is pulled as  a
transitive dependency of `io.opencensus`.

### Before
```
❯ ./gradlew -q :grpc-xds:dependencyInsight --configuration=compileClasspath --dependency=io.grpc:grpc-context
*** Skipping the build of codegen and compilation of proto files because skipCodegen=true
  * Skipping the build of Android projects because skipAndroid=true
io.grpc:grpc-context:1.27.2
  Variant compile:
    | Attribute Name                 | Provided | Requested    |
    |--------------------------------|----------|--------------|
    | org.gradle.status              | release  |              |
    | org.gradle.category            | library  | library      |
    | org.gradle.libraryelements     | jar      | classes      |
    | org.gradle.usage               | java-api | java-api     |
    | org.gradle.dependency.bundling |          | external     |
    | org.gradle.jvm.environment     |          | standard-jvm |
    | org.gradle.jvm.version         |          | 8            |

io.grpc:grpc-context:1.27.2
\--- io.opencensus:opencensus-api:0.31.1
     +--- com.google.http-client:google-http-client:1.43.3
     |    +--- com.google.auth:google-auth-library-oauth2-http:1.22.0
     |    |    \--- project :grpc-alts
     |    |         \--- compileClasspath
     |    \--- com.google.http-client:google-http-client-gson:1.43.3
     |         \--- com.google.auth:google-auth-library-oauth2-http:1.22.0 (*)
     \--- io.opencensus:opencensus-contrib-http-util:0.31.1
          \--- com.google.http-client:google-http-client:1.43.3 (*)

(*) - Indicates repeated occurrences of a transitive dependency subtree. Gradle expands transitive dependency subtrees only once per project; repeat occurrences only display the root of the subtree, followed by this annotation.
```

### After
```
❯ ./gradlew -q :grpc-xds:dependencyInsight --configuration=compileClasspath --dependency=io.grpc:grpc-context
*** Skipping the build of codegen and compilation of proto files because skipCodegen=true
  * Skipping the build of Android projects because skipAndroid=true
project :grpc-context
  Variant apiElements:
    | Attribute Name                 | Provided | Requested    |
    |--------------------------------|----------|--------------|
    | org.gradle.category            | library  | library      |
    | org.gradle.dependency.bundling | external | external     |
    | org.gradle.jvm.version         | 8        | 8            |
    | org.gradle.libraryelements     | jar      | classes      |
    | org.gradle.usage               | java-api | java-api     |
    | org.gradle.jvm.environment     |          | standard-jvm |
   Selection reasons:
      - By conflict resolution: between versions 1.63.0-SNAPSHOT and 1.27.2

project :grpc-context
\--- project :grpc-alts
     \--- compileClasspath

io.grpc:grpc-context:1.27.2 -> project :grpc-context
\--- io.opencensus:opencensus-api:0.31.1
     +--- com.google.http-client:google-http-client:1.43.3
     |    +--- com.google.auth:google-auth-library-oauth2-http:1.22.0
     |    |    \--- project :grpc-alts
     |    |         \--- compileClasspath
     |    \--- com.google.http-client:google-http-client-gson:1.43.3
     |         \--- com.google.auth:google-auth-library-oauth2-http:1.22.0 (*)
     \--- io.opencensus:opencensus-contrib-http-util:0.31.1
          \--- com.google.http-client:google-http-client:1.43.3 (*)

(*) - Indicates repeated occurrences of a transitive dependency subtree. Gradle expands transitive dependency subtrees only once per project; repeat occurrences only display the root of the subtree, followed by this annotation.
```
2024-03-11 14:00:12 -07:00
Eric Anderson aa90768129
rls: Fix a local and remote race
The local race passes `rlsPicker` to the channel before
CachingRlsLbClient is finished constructing. `RlsPicker` can use
multiple of the fields not yet initialized. This seems not to be
happening in practice, because it appears like it would break things
very loudly (e.g., NPE).

The remote race seems incredibly hard to hit, because it requires an RPC
to complete before the pending data tracking the RPC is added to a map.
But with if a system is at 100% CPU utilization, maybe it can be hit. If
it is hit, all RPCs needing the impacted cache entry will forever be
buffered.
2024-03-08 09:47:11 -08:00
John Cormie 8f45a97be6
binder: remove existing warnings and allow failOnWarnings (#10989) 2024-03-07 09:56:37 -08:00
Touko Vainio-Kaila 0b82f01260
api: Fix a typo in ServerInterceptor JavaDoc (#10990) 2024-03-06 10:43:14 -08:00
Eric Anderson 9ee5e9f008 xds: Move node id logging out of xds.client
This removes a grpc-ism environment variable. Note that the logger is
still registered under XdsClientImpl. That could maybe change, but it is
a bit unclear what it should become and it seemed better for this to
have no behavior changes.
2024-03-06 07:25:54 -08:00
Eric Anderson 42b2cbdec3 xds: Move LR and RLS experimental flags to where they are used
That's better for code organization and also removes some grpc-isms from
XdsResourceType.
2024-03-06 07:25:33 -08:00
John Cormie d894c8385d
Use a realistic Executor in BinderServerTransportTest (#10979) 2024-03-05 15:24:43 -08:00
Eric Anderson 85e52cd113 xds: Remove WRR and PF experimental flags
They have been on by default for a good while, and seem stable. This
also removes some grpc-isms from XdsResourceType.
2024-03-05 13:21:53 -08:00
Eric Anderson 27824469bf xds: Provide default XdsResourceType.extractResourceName impl
This method is only needed sometimes, and with time will be needed less
and less. Don't require new types to implement it, instead relying on
control planes to use the new approach.
2024-03-05 11:30:35 -08:00
Eric Anderson 8feb919167 netty/shaded: Add missing evaluationDependsOn
`project(':grpc-netty').configurations` requires the grpc-netty project
to be configured, which requires evaluationDependsOn. Without
evaluationDependsOn, project loading order is arbitrary and you can get
random errors after small configuration changes.
2024-03-05 10:38:55 -08:00
Eric Anderson 9947a25765 binder: Fix unused imports and parameter name mismatch 2024-03-05 10:04:30 -08:00
Eric Anderson 6b3526d200 examples: Error information is not in the server response
Or rather, server response is ambiguous and this usage is not generally
what we mean when we say it. The example shows how to get an error for
any failed RPC, not just those coming from a failing server.

The existing comment caused confusion at
https://stackoverflow.com/a/78104828
2024-03-05 10:04:14 -08:00
Anirudh Ramachandra 867e469404
xds: Support retrieving names from wrapped resource containers (#10975)
The xDS library only honored names retrieved from the inner resource
containers, but for wrapped resources the outer layer could contain the
required name. This commit prefers the name on the wrapped container
over the inner resource name.
2024-03-05 07:22:18 -08:00
Terry Wilson e5ed55399d
android-interop-testing: Improve errror logging (#10972) 2024-03-04 11:23:17 -08:00
Eric Anderson ac62c8b055 Fix tests and warnings on Java 17
SelfSignedCertificate is not available on Java 17 because
OpenJdkSelfSignedCertGenerator is not available. This only impacted
tests.

AccessController is being removed, and these locations are doing simple
reflection which is unlikely to require it even when a security policy
is in effect. There's other places we do reflection without the
AccessController, so either no security policies care or the users can
update their policies to allow it.
2024-02-29 16:55:46 -08:00
Sergii Tkachenko feab4e5449
xds: Get rid of xDS v2 dependencies (#10968)
xDS v2 support was dropped about a year ago, but the xds package still
had a few xDS v2 usages. This PR:

- Removes all leftover usages of xDS v2 classes in gprc-xds
- Removes all imported xDS v2 protos and their leaf dependencies:
- Removes xDS v2 generated services
- Makes minor improvements to the xds import script output

### Before
```sh
# Imported 154 protos.
❯ find . -iname "*xds*.jar" -exec du -h {} \; | col -x
  13M ./build/libs/grpc-xds-1.63.0-SNAPSHOT-original.jar
  6.1M ./build/libs/grpc-xds-1.63.0-SNAPSHOT-sources.jar
  388K ./build/libs/grpc-xds-1.63.0-SNAPSHOT-javadoc.jar
  14M ./build/libs/grpc-xds-1.63.0-SNAPSHOT.jar

```

### After
```sh
# Imported 86 protos.
❯ find . -iname "*xds*.jar" -exec du -h {} \; | col -x
  9.1M ./build/libs/grpc-xds-1.63.0-SNAPSHOT-original.jar
  4.1M ./build/libs/grpc-xds-1.63.0-SNAPSHOT-sources.jar
  388K ./build/libs/grpc-xds-1.63.0-SNAPSHOT-javadoc.jar
  9.1M ./build/libs/grpc-xds-1.63.0-SNAPSHOT.jar ```

Reduction:
- Number of protos: 44%
- Jar size: 35%
2024-02-29 10:33:18 -08:00
Prashanth Swaminathan e697eccc51
roboelectric: Remove references to kitkat (#10953)
In addition to removing a test that only applies to KitKat, switch tests
that require 19 to not specifying the SDK version as we only support min
sdk version 21, which has the required API.

Also removes the SDK version check from isProfileOwner, to trigger a
runtime exception when too low of an SDK version is used.
2024-02-28 09:55:03 -08:00
Terry Wilson ce2adcca93
binder: Add missing Android API annotations (#10841) 2024-02-28 08:02:58 -08:00
Eric Anderson 935f8f0afc servlet: Move deps to version catalog
This allows the checkForUpdates task to notice the dependencies and
suggest updates.

I plan to upgrade some of the servers after this change in hopes it
reduces test flakiness.
2024-02-27 21:48:19 -08:00
John Cormie a654d2ebb3
binder: Add fault injection hooksunit tests for BinderClientTransport (#10928) 2024-02-27 14:28:50 -08:00
Eric Anderson af117e9764 core: Don't use real time when comparing deadline in ClientCallImplTest
We can just compare the Deadline instances instead of asserting that
very little time has passed during the test. Real time probably still
matters in the test, but only insofar that the deadline is not expired
by the time ClientCallImpl sees it.

This fixes a test failure seen in the emulated aarch64 CI. Note that the
message says "ns" when it should say "ms", but this change deletes the
code with that typo.

```
java.lang.AssertionError: timeout: 548 ns
	at org.junit.Assert.fail(Assert.java:89)
	at org.junit.Assert.assertTrue(Assert.java:42)
	at io.grpc.internal.ClientCallImplTest.assertTimeoutBetween(ClientCallImplTest.java:1102)
	at io.grpc.internal.ClientCallImplTest.contextDeadlineShouldBePropagatedToStream(ClientCallImplTest.java:828)
```
2024-02-27 12:54:58 -08:00
Larry Safran 2c6d6e62dc
Update README to v1.62.2 (#10965) 2024-02-27 12:52:59 -08:00
Eric Anderson 9b53bcaf66 xds: Increase timeouts in XdsClientFederationTest
`isolatedResourceDeletions()` has failed with a timeout waiting on
onChanged when running under TSAN. TSAN can slow things down, so let's
increase the timeout to ensure it isn't just timeout flake.
2024-02-27 11:28:24 -08:00
yifeizhuang c61fe69803
util, dual stack: change address based outlier detection to endpoint based (#10939) 2024-02-27 10:35:59 -08:00
Larry Safran 8087977c0b
Move xds classes for Stubby to xds.client package (#10912)
* Move bootstrap, XdsClient, load reporting, XdsLogger and XdsResourceType to xds.client package.
2024-02-26 16:41:16 -08:00
yifeizhuang 78b3972ff3
xds: fix xdsNameResolver virtual host lookup authority, use service authority instead of ldsResourceName (#10960) 2024-02-26 16:33:20 -08:00
Eric Anderson 0ffcd40ab6 buildscripts: Remove unused Kokoro files for Bazel
Bazel testing has been using GitHub Actions since 445efe74.
2024-02-26 10:03:35 -08:00
Eric Anderson 89d8a13d10 compiler: Support up-to-date checking in golden tests 2024-02-26 10:03:13 -08:00
Eric Anderson 5f8958f65c Use Javadoc's -linkoffline instead of -link
`-link` does I/O to download the package list, for every javadoc
invocation. There is no caching, so this happens many times per build.
Swap to offline mode to avoid spamming the servers, and avoid build
failures if the servers aren't entirely healthy.
2024-02-23 17:22:48 -08:00
Eric Anderson 871aaac0f0 compiler: actually add dependency on golden tests
We had 'test.dependsOn', but it is only run if the golden tasks are
configured, which they generally won't be because nothing depends on
them. This prevented the test from actually running. This bug was
introduced in 0ff9f37b because previously the golden tasks were eagerly
constructed.

Remove the "extraPackage" argument because it is a constant and it
confused me for a bit wondering when it was necessary.
2024-02-23 16:19:35 -08:00
Eric Anderson f768c4222b Remove build usages of Jetty ALPN
It wasn't actually being used. Since Java 8u252 in early 2020 we've been
using ALPN from the JDK. The Jetty ALPN Agent has been a noop.

We do keep the Jetty ALPN support in the code and tests, but we don't
have the infrastructure to actually run it.
2024-02-23 15:27:33 -08:00
Eric Anderson 569956e022 xds: Pre-add fallback to xds client pool accessor
When we implement A71, we're no longer going to have a single xds
client, but instead one per channel target. Add that parameter now, even
though it is unused, to avoid managing the (internal) API breakage when
we implement fallback.
2024-02-23 14:12:46 -08:00
Eric Anderson c7e87d2180 buildscripts: Use Java 11 on Windows CI
This version of Java is old, but not as old as the Java 8 version.
2024-02-23 14:12:11 -08:00
Eric Anderson bfc0f959cd xds: Avoid nonexistent DNS resolution in XdsClientImplV3Test
The DNS lookups are taking considerable time on the Windows CI (~11s),
which causes the test to time out:

```
Wanted but not invoked:
ldsResourceWatcher.onError(<any>);
-> at io.grpc.xds.XdsClientImplTestBase.sendToNonexistentHost(XdsClientImplTestBase.java:3733)
Actually, there were zero interactions with this mock.

	at io.grpc.xds.XdsClientImplTestBase.sendToNonexistentHost(XdsClientImplTestBase.java:3733)
```

The ARM build, which uses an emulator, has had this test succeed, so the
failure seems unrelated to CPU usage. We want to avoid external I/O
anyway during tests, so removing the DNS lookup is good.

The TSAN comment referenced XdsClientImplTestBase.sendToNonexistentHost,
but the test no longer calls fakeClock.forwardTime so the comment was
out-of-date. Change the comment to make clear the race involved.
2024-02-23 11:44:06 -08:00
Eric Anderson d7628a3aba
xds: Fix flow control data race in ControlPlaneClient
As discovered by TSAN, the adsStream field is not synchronized.
```
WARNING: ThreadSanitizer: data race (pid=1625)
  Read of size 4 at 0x00009b66fc88 by thread T23 (mutexes: write M0):
    #0 io.grpc.xds.ControlPlaneClient.isReady()Z ControlPlaneClient.java:203
    #1 io.grpc.xds.ControlPlaneClient.readyHandler()V ControlPlaneClient.java:211
    #2 io.grpc.xds.ControlPlaneClient$AdsStream.onReady()V ControlPlaneClient.java:328
    #3 io.grpc.xds.GrpcXdsTransportFactory$EventHandlerToCallListenerAdapter.onReady()V GrpcXdsTransportFactory.java:145
    #4 io.grpc.PartialForwardingClientCallListener.onReady()V PartialForwardingClientCallListener.java:44
    #5 io.grpc.ForwardingClientCallListener.onReady()V ForwardingClientCallListener.java:23
    #6 io.grpc.ForwardingClientCallListener$SimpleForwardingClientCallListener.onReady()V ForwardingClientCallListener.java:40
    #7 io.grpc.PartialForwardingClientCallListener.onReady()V PartialForwardingClientCallListener.java:44
    #8 io.grpc.ForwardingClientCallListener.onReady()V ForwardingClientCallListener.java:23
    #9 io.grpc.ForwardingClientCallListener$SimpleForwardingClientCallListener.onReady()V ForwardingClientCallListener.java:40
    #10 io.grpc.internal.DelayedClientCall$DelayedListener.onReady()V DelayedClientCall.java:497
    #11 io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl$1StreamOnReady.runInternal()V ClientCallImpl.java:781
    #12 io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl$1StreamOnReady.runInContext()V ClientCallImpl.java:772
    #13 io.grpc.internal.ContextRunnable.run()V ContextRunnable.java:37
    #14 io.grpc.internal.SerializingExecutor.run()V SerializingExecutor.java:133
    #15 java.util.concurrent.ThreadPoolExecutor.runWorker(Ljava/util/concurrent/ThreadPoolExecutor$Worker;)V ThreadPoolExecutor.java:1130
    #16 java.util.concurrent.ThreadPoolExecutor$Worker.run()V ThreadPoolExecutor.java:630
    #17 java.lang.Thread.run()V Thread.java:830
    #18 (Generated Stub) <null>

  Previous write of size 4 at 0x00009b66fc88 by thread T4 (mutexes: write M1, write M2, write M3, write M4, write M5):
    #0 io.grpc.xds.ControlPlaneClient$AdsStream.cleanUp()V ControlPlaneClient.java:424
    #1 io.grpc.xds.ControlPlaneClient$AdsStream.close(Ljava/lang/Exception;)V ControlPlaneClient.java:418
    #2 io.grpc.xds.ControlPlaneClient$1.run()V ControlPlaneClient.java:130
    #3 io.grpc.SynchronizationContext.drain()V SynchronizationContext.java:94
    #4 io.grpc.SynchronizationContext.execute(Ljava/lang/Runnable;)V SynchronizationContext.java:126
    #5 io.grpc.xds.XdsClientImpl.shutdown()V XdsClientImpl.java:207
    #6 io.grpc.xds.SharedXdsClientPoolProvider$RefCountedXdsClientObjectPool.returnObject(Ljava/lang/Object;)Lio/grpc/xds/XdsClient; SharedXdsClientPoolProvider.java:144
    #7 io.grpc.xds.SharedXdsClientPoolProvider$RefCountedXdsClientObjectPool.returnObject(Ljava/lang/Object;)Ljava/lang/Object; SharedXdsClientPoolProvider.java:102
    #8 io.grpc.xds.XdsClientFederationTest.cleanUp()V XdsClientFederationTest.java:86
```
2024-02-22 14:43:29 -08:00
Sergii Tkachenko de7e649e04
(minor) Fix a typo in ReflectableMarshaller docstring (#10942)
`it's` -> `its`
2024-02-21 13:29:51 -08:00
Eric Anderson e19f1f15a9 examples: Fix file paths in debug example README 2024-02-21 08:34:19 -08:00
Eric Anderson 071a784795
Change GAE interop tests to use java11 runtime (#10933)
The Java 8 runtime is end of support. Leaving this a gae-jdk8 for now.
The gae-jdk8 was because AppEngine changed dramatically from Java 7 to
Java 8. Nowadays the versions are more in line with OpenJDK and not very
different from each other.

Fixes #10925
2024-02-20 10:52:22 -08:00
David Ankin 0d39c2c701
implement ability to skip generation of javax annotation (#10927)
* commit to implement feedback from #10786 to partially fix #9179
2024-02-16 17:49:20 -08:00
Eric Anderson 3994b15fea buildscripts: Avoid vswhere crashing Gradle
I'm trying to upgrade to a newer Windows Kokoro image, but the new one
has an old vswhere installed that breaks Gradle. Our old image doesn't
have vswhere at all. If vswhere isn't found, this rename prints some
errors, but the bat script continues executing. So this change is
compatible with both the older and newer image.
2024-02-16 15:12:14 -08:00
Eric Anderson f4cc166f18 xds: Copy data in least request to avoid picker data race
In 0d39bf50 the ReadyPicker was changed holding List<Subchannel> to
List<ChildLbState>, but ChildLbState mutates over time and is not
synchronized. We want the picker to have a snapshot of the data, so copy
the data from ChildLbState instead of using it directly.

Unfortunately the tests depended on the ChildLbState a bit, so we need
to save the EAG only to use it in tests. That's okay for now, but in the
future we'll probably want to remove that unnecessary memory usage.
2024-02-16 13:44:25 -08:00
Eric Anderson a231d80756 Remove semi-circular dependency between core and util
Add the 'fake' dependency to grpc-netty instead of grpc-core.
grpc-okhttp already depends on grpc-util and probably would be fine
without round_robin on Android.

There's not actually a circular dependency, but some tools can't handle
the compile vs runtime distinction. Such tools are broken, but fixes
have been slow and this approach works with no real downfalls.

Works around #10576 #10701
2024-02-16 12:31:54 -08:00
Alex Panchenko 257d1c2db4 servlet: introduce ServletServerBuilder.buildServlet() 2024-02-16 12:21:42 -08:00
Benjamin Peterson a68399a9b6
netty: improve server handling of writes to reset streams (#10258)
* netty: improve server handling of writes to reset streams

A server stream can be reset by the client while server writes are still queued. After the stream is reset, the netty connection will forget the stream object. The `NettyServerHandler` must deal with that situation. `sendResponseHandlers` already had some code to do that. This change standardizes that code and adds it to `sendGrpcFrame`. This fixes a potential bug where a `SendGrpcFrameCommand` with `endOfStream=true` would raise an `AssertionError` if written to a reset stream. (This bug is not currently reachable because `endOfStream=false` for all server `SendGrpcFrameCommand` objects.)

* Do not call into the encoder when we know the stream is gone.
2024-02-16 11:08:09 -08:00
Alex Panchenko 2f025b2b24
servlet: missing @Rule annotation in GrpcServletSmokeTest (#10922) 2024-02-16 10:29:45 -08:00
Larry Safran 67dfe49ae6 Fix compile failure 2024-02-15 21:28:37 -08:00
Terry Wilson eba699ad16
rls: Adding extra debug logs (#10902) 2024-02-15 15:23:36 -08:00
Larry Safran 044749706a
util:MultiChildLoadBalancer cleanup (#10780)
* add final, change method permissions, add javadoc, cleanup unneeded, move updateOverallBalancingState to ClusterManagerLB and make it abstract

* Restructure to eliminate the flags as protected methods

* Move methods around so that the candidates for override are near the top.

* Reorder picker methods lower
2024-02-15 14:12:40 -08:00
John Cormie f20c853c40
Factor out MainThreadScheduledExecutorService. (#10916)
So it can be used by other robolectric tests.
2024-02-15 11:11:43 -08:00
Terry Wilson 08f8ed1bc3 util: MultiChildLoadBalance.shutdown() log to FINE
The log level of this method is set to INFO, which is too spammy. Bring
it down to the FINE level.
2024-02-13 14:12:33 -08:00
Eric Anderson 7787673992 xds: Replace isEquivalentTo with equals in LeastRequest
This is similar to the changes to round robin in dca89b25.
2024-02-13 08:29:31 -08:00
Eric Anderson 7e72413233 okhttp: Move HostnameVerifier tests to TlsTest
Http2OkHttp is now unnecessary, as Http2Test tests OkHttp client to
Netty server. receivedDataForFinishedStream() was the only remaining
unique test and it seems already covered by AbstractInteropTest these
days.
2024-02-12 19:40:33 -08:00
Eric Anderson 92463f62bf interop-testing: Avoid Netty-specific APIs to creating channels
We prefer to test using the stable APIs, as they are what our users
should be using. Http2Client continues using NettyChannelBuilder because
it is intended to test grpc-netty.
2024-02-12 07:52:31 -08:00
Eric Anderson 372a535615 auth: Add support for Retryable interface
Retryable was added in google-auth-library 1.5.3 to make clear the
situations that deserve a retry of the RPC. Upgrading to that caused
problems because of transitive dependency issues syncing into Google so
it was reverted in 369f87be. google-auth-library 1.11.0 changed the
approach to avoid the transitive dependency updates. cl/601545581
upgraded to 1.22.0 inside Google. Bump to that version and swap away
from the imprecise IOException heuristic. go/auth-correct-retry

Fixes #6808
2024-02-09 15:15:18 -08:00
yifeizhuang ff34d51c73
api: stabilize server.getListenerSockets (#10910) 2024-02-09 14:40:54 -08:00
Anirudh Ramachandra 608bb8499c
Mark couple of helper functions in XdsClient as public. (#10871) 2024-02-09 12:53:03 -08:00
Anirudh Ramachandra 52b11c1d08
Expose the getOrCreate method via the InternalSharedXdsClientPoolProvider. This is needed for internal users to both set the bootstrap and interact with the XdsClient via the shared object pool (#10872) 2024-02-09 12:50:26 -08:00
Eric Anderson d568a8dc19 kokoro: Avoid using Kokoro's env_vars setting
It makes it hard to run ephemeral jobs, and we don't actually need it
here because we aren't changing the setting with manual runs.
2024-02-09 12:47:16 -08:00
Larry Safran 6847219657
Start 1.63.0 development cycle (#10906) 2024-02-08 13:11:38 -08:00
Eric Anderson 95b847e799 interop-testing: Use separate event loops in RetryTest
The RetryTest was flaky, and it seems to have been caused by the client
and server getting assigned to the same event loop. Separating the two
reduces the flake rate from ~3% to less than 0.1% (no flakes in a 1000).

While I was here fixing the executors, I reduced the number of threads
created and shut down the threads after they are no longer used. This
had no impact to the flake rate (no flakes in 1000).
2024-02-08 07:26:31 -08:00
Larry Safran 7ba0718bb9
Change log level from WARNING to FINER for expected exception (#10899)
* Change log level from WARNING to FINER.  Fixes #10816
2024-02-07 17:31:27 -08:00
Larry Safran 5faab7f47e
Revert "Fix retries that timeout hanging forever. (#10855)" (#10901)
This reverts commit c0a9d315d3.
2024-02-07 15:05:21 -08:00
yifeizhuang 03decafa1f
XdsClient is experimental (#10876) 2024-02-06 17:43:30 -08:00
yifeizhuang f6d9221b65
xds: hide TlsContextManager in XdsResourceType.Args (#10894) 2024-02-06 15:41:24 -08:00
Sergii Tkachenko 4f7ec131ec
xds: Googleapis proto sync to 2023-01-10 (#10896)
Sync googleapis protos to
googleapis/googleapis@114a745b28 for
consistency with Envoy and cncf/xds.

The same version is used in [envoy]
(62e7c59374/api/bazel/repository_locations.bzl (L69))
and [cncf/xds]
(0fa0005c9c/bazel/repository_locations.bzl (L23))
since Jan 2023.

Function-wise, this is a noop.
2024-02-05 18:52:55 -08:00
Sergii Tkachenko 68334a019a
xds: Envoy proto sync to 2024-01-24 (#10895)
`envoyproxy/envoy`: Sync protos to the latest imported version
147e6b9523
(commit 2024-01-24, cl/604403196).

Should be a noop, just a routine xDS proto update to make upcoming
RLQS-related imports simpler.
2024-02-05 17:21:51 -08:00
Larry Safran 374dbe9461
Fix flaky retry tests (#10887)
* Reorder tracing and actually closing listener to eliminate test flakiness
* Use real value rather than mock for flaky test
2024-02-05 10:54:55 -08:00
Anirudh Ramachandra 3202370684
Allow users to start watching xDS resources (#10864) 2024-02-01 09:21:00 -08:00
yifeizhuang a97f21b61e
xds: fix NPE in wrr in TF state (#10868) 2024-02-01 09:06:46 -08:00
Larry Safran c0a9d315d3
Fix retries that timeout hanging forever. (#10855)
Fixes #10336
2024-01-31 13:15:35 -08:00
yifeizhuang 8d280c97e3
xds: move filterRegistry and loadBalancerRegistry out of XdsResourceType.Args (#10843) 2024-01-31 09:45:37 -08:00
yifeizhuang 20abea47bc
xds: move tlsContextManager (#10859)
Minor refactor to the tlsContextManager to not expose itself on the xdsClientImpl constructor.
This is to allow people who plugins xdsTransportFactory to use the API easily.
2024-01-30 12:59:33 -08:00
Mateus Azis c2a3792a04
binder: Create a new RobolectricBinderSecurityTest (#10835)
Exercises async security policies codepaths.
2024-01-30 11:36:53 -08:00
Larry Safran ac428c14fd
Relax some timeouts that have been flaky for the automated CI testing. (#10858)
* Relax some timeouts that have been flaky for the automated CI testing.
2024-01-29 17:43:21 -08:00
Larry Safran ae5fdd5faa
Add check for empty addresses and if not there disable ipV6. (#10848)
* Add check for empty addresses and if not there dissable ipV6.
2024-01-29 17:20:11 -08:00
Larry Safran 7f4c16e068
internal:Happy eyeballs (#10731)
* implement happy eyeballs

---------

Co-authored-by: tonyjongyoonan <tonyjan@google.com>
2024-01-29 12:50:58 -08:00
yifeizhuang 8e1cc943b0
xds: change controlPlaneClient and loadReportClient to use xdsTransportFactory (#10829) 2024-01-25 17:05:12 -08:00
Anirudh Ramachandra 6d96e6588e
Allow users outside of io.grpc.xds package to create custom xDS resources (#10834)
Currently few of the interfaces needed to define and start a watch for a xDS resource are package private, which can't be used externally outside of io.grpc.xds. Exposing them outside allows users to define their own custom resources and start a watch along with the default supported resources.

Also as part of this change, move an Exception defined in the XdsClientImpl into XdsResourceType. As XdsClientImpl is an implementation package, it makes more sense to expose it via the XdsResourceType class.
2024-01-24 19:48:52 -08:00
Mateus Azis 3e8e56feea
Make AsyncSecurityPolicy.checkAuthorizationAsync public. (#10836)
I initially omitted the visibility modifier because this class began as an interface. Since it moved to an abstract class, we must make it public so it can be overriden by subclasses in the integrator's packages.

Part of #10566.
2024-01-22 15:54:48 -08:00
Mateus Azis 9b9e53359f
Add unit test coverage for PendingAuthListener. (#10806)
Part of #10566.
2024-01-22 15:06:16 -08:00
John Cormie 09acf2f6b7
transports can send a msg larger than their flow control window (#10842) 2024-01-22 10:30:32 -08:00
Terry Wilson c9db8fa4fe
buildscripts: Break up android-interop gradle builds (#10839)
Splits the :grpc-android-interop-testing:assembleDebug and
:grpc-android-interop-testing:assembleDebugAndroidTest build
targets with hopes of avoiding OOMs.
2024-01-22 09:05:46 -08:00
John Cormie fdd6f5001f
binder: fix up BinderClientTransportTest (#10822)
- Multiple test cases assumed all messages would arrive on a single MessageProducer but this isn't guaranteed by the API contract.
- testBadTransactionStreamThroughput_b163053382 was writing `serverCallsCompleted` on one thread and reading it on another without synchronization. A deeper problem was that waiting for the call to complete on the server doesn't mean messages are  immediately available on the client.
- Replaced 100ms polling loops with wait()/notifyAll()
- Close() InputStreams that we read as required by the MessageProducer#next contract.

Passes with --runs_per_test=1000
2024-01-19 17:47:08 -08:00
Eric Anderson 65a6b3bc21 java_grpc_library.bzl: Support runfiles for protoc and the plugin
To support runfiles, the rule has to track more than just the
executable. `files_to_run` has both the runfile and executable
information (as separate fields), as does `files`, (combined as depset).
So using those when able is inherently "safe." `files_to_run.executable`
is only the executable, so does not propagate dependency information,
so we make sure to pass `files` to the rule in addition.
(`files_to_run.executable` is formatted into a string, so it wouldn't
carry depset information anyway.)

As originally noticed in cl/597962426
2024-01-19 17:02:55 -08:00
Sergii Tkachenko 75492c8b36
services: Remove deprecated `io.grpc.services.BinaryLogs` (#10832)
* services: Remove deprecated `io.grpc.services.BinaryLogs`
* services: Remove //services:binarylog bazel target

Was deprecated more than 2 years ago in bab1fe3.
`io.grpc.protobuf.services.BinaryLogs` should be used instead.

Experimental tracking ticket:
https://github.com/grpc/grpc-java/issues/4017
2024-01-18 11:29:19 -08:00
yifeizhuang 005f8c006d
xds: add xdsTransportFactory interface (#10827)
This interface will be used to replace XdsChannelTransport.
2024-01-16 17:41:24 -08:00
Larry Safran a151099820
change since javadoc in ClientTransportFilter.java (#10817)
Change from 1.61 to 1.62 since it wasn't released in 1.61
2024-01-16 09:54:56 -08:00
Sergii Tkachenko be74bbdfe0
Bump gradle from 8.3 to 8.5 (#10791)
`./gradlew wrapper --gradle-version=8.5`

Changelog:
- [Gradle 8.4 Release Notes](https://docs.gradle.org/8.4/release-notes.html)
- [Gradle 8.5 Release Notes](https://docs.gradle.org/8.5/release-notes.html)
2024-01-12 16:01:48 -08:00
Sergii Tkachenko 1e69c712f7
Update README etc to reference 1.61.0 (#10821)
* Update README etc to reference 1.61.0
* Update README protoc references to 3.25.1
2024-01-12 11:48:14 -08:00
Eric Anderson 91cfa97c28 netty: Avoid volatile attributes on client-side
6efa9ee3 added `volatile` to `attributes` after TSAN detected a data
race that was added in 91d15ce4. The race was because attributes may be
read from another thread after `transportReady()`, and the
post-filtering assignment occurred after `transportReady()`. The code
now filters the attributes separately so they are updated before calling
`transportReady()`.

Original TSAN failure:
```
  Read of size 4 at 0x0000cd44769c by thread T23:
    #0 io.grpc.netty.NettyClientHandler.getAttributes()Lio/grpc/Attributes; NettyClientHandler.java:327
    #1 io.grpc.netty.NettyClientTransport.getAttributes()Lio/grpc/Attributes; NettyClientTransport.java:363
    #2 io.grpc.netty.NettyClientTransport.newStream(Lio/grpc/MethodDescriptor;Lio/grpc/Metadata;Lio/grpc/CallOptions;[Lio/grpc/ClientStreamTracer;)Lio/grpc/internal/ClientStream; NettyClientTransport.java:183
    #3 io.grpc.internal.MetadataApplierImpl.apply(Lio/grpc/Metadata;)V MetadataApplierImpl.java:74
    #4 io.grpc.auth.GoogleAuthLibraryCallCredentials$1.onSuccess(Ljava/util/Map;)V GoogleAuthLibraryCallCredentials.java:141
    #5 com.google.auth.oauth2.OAuth2Credentials$FutureCallbackToMetadataCallbackAdapter.onSuccess(Lcom/google/auth/oauth2/OAuth2Credentials$OAuthValue;)V OAuth2Credentials.java:534
    #6 com.google.auth.oauth2.OAuth2Credentials$FutureCallbackToMetadataCallbackAdapter.onSuccess(Ljava/lang/Object;)V OAuth2Credentials.java:525
    ...

  Previous write of size 4 at 0x0000cd44769c by thread T24:
    #0 io.grpc.netty.NettyClientHandler$FrameListener.onSettingsRead(Lio/netty/channel/ChannelHandlerContext;Lio/netty/handler/codec/http2/Http2Settings;)V NettyClientHandler.java:920
    #1 io.netty.handler.codec.http2.DefaultHttp2ConnectionDecoder$FrameReadListener.onSettingsRead(Lio/netty/channel/ChannelHandlerContext;Lio/netty/handler/codec/http2/Http2Settings;)V DefaultHttp2ConnectionDecoder.java:515
    ...
```
2024-01-12 07:29:48 -08:00
Sergii Tkachenko c346b41e22
RELEASING.md: Include author email in shortlog (#10794)
Makes it easier to track down / credit the author.
2024-01-11 11:37:19 -08:00
John Cormie 4352099c7f
binder: BinderTransportTest uses a realistic Executor. (#10803) 2024-01-11 10:49:03 -08:00
Eric Anderson 100d5a55fd xds: Add EC key support
io.grpc.util.CertificateUtils does much of the same thing as xds's
CertificateUtils, but also supports EC keys. The xds code pre-dates the
grpc-util class, so it isn't surprising it wasn't using it.

There's a good number of usages of the xds CertificateUtils, so I just
got rid of the duplicate implementation, but didn't yet bother changing
callers io.grpc.util.
2024-01-10 15:17:36 -08:00
Eric Anderson cb03bd2346 java_grpc_library.bzl: Support Auto Exec Groups
Tested with --incompatible_auto_exec_groups=true with Bazel 7
2024-01-10 13:46:20 -08:00
Terry Wilson 6605649c28
okhttp: Ignore known conscrypt socket close issue (#10811)
This stops an exception from being thrown when a known Conscrypt synchronization issue happens.
2024-01-10 11:01:42 -08:00
Terry Wilson 516f411e02
android-interop-testing: Fix tester activity layout (#10807)
Add missing inputType and lint ignore rule.
2024-01-09 13:37:06 -08:00
Sergii Tkachenko d180e6cfa2
xds: (minor) address Java Code Clarity recommendations in CSDS (#10804)
Redoes https://github.com/grpc/grpc-java/pull/8028
Ref cl/365582959
2024-01-08 12:30:46 -08:00
yifeizhuang 6efa9ee37d
fix tsan data race in attributes (#10805) 2024-01-08 10:54:06 -08:00
Larry Safran 4e163361d4
util:create a test for MultiChildLoadBalancer and Endpoint (#10771)
* Add a test for MultiChildLB doing some basic checking and using multiple addresses for an eag

* Add tests for Endpoint
2024-01-05 17:09:35 -08:00
Larry Safran 4b2e5eddd2
api:Provide a default implementation for new method added to ManagedTranport.Listener to support ClientTransportFilters (#10795)
* Provide a default implementation for new method added to ManagedTransport.Listener to support ClientTransportFilters
* Relax test constraint to reduce flakiness due to timing.
* Add test for listener.filterTransport.
2024-01-04 14:19:13 -08:00
yifeizhuang f01c110f77
fix flaky xds test due to verification race (#10798) 2024-01-04 11:31:53 -08:00
John Cormie 5e07310d06
binder: oneway txns cannot arrive out of order (#10754)
See https://developer.android.com/reference/android/os/IBinder#FLAG_ONEWAY
2024-01-03 22:31:51 -08:00
joybestourous 91d15ce4e6
Add ClientTransportFilter (#10646)
* Add ClientTransportFilter
2024-01-03 10:45:22 -08:00
Sergii Tkachenko 7692a9f5db
Start 1.62.0 development cycle (#10792) 2024-01-03 10:08:36 -08:00
Mateus Azis 5b082ca640
Do not cache failed futures for async security policies indefinitely. (#10743)
Currently, if caching is enabled (as is often the case) and AsyncSecurityPolicy returns a failed future, then this future is cached forever, without giving the SecurityPolicy implementation a chance to be retried. Going forward, new invocations will trigger new security checks if the last one could not be completed successfuly.
2024-01-03 15:17:30 +01:00
Sergii Tkachenko 062f7a2072
README.md: Correct gradle protobuf reference from 3.22.3 to 3.24.0 (#10772)
1. The bump to `3.23.4` was incorrectly done to the master README in
   https://github.com/grpc/grpc-java/pull/10359.
2. This was reverted in https://github.com/grpc/grpc-java/pull/10430.
3. Then protobuf was upgraded again in 1.58.0, from `3.23.4` to
   `3.24.0` (f8baa9ca1)
4. 1.58.0 release updated it to `3.24.0` for maven, but kept at
  `3.22.3` for gradle (75af7abf4).
2024-01-02 11:40:37 -08:00
yifeizhuang 597101c089
xds: fix flow control message not delivered when previous message type is unknown (#10785) 2023-12-31 12:54:07 -08:00
Vladimir Gordiychuk 0f21574bb1
core: reduce CompositeReadableBuffer allocation (#3279)
* core: reduce CompositeReadableBuffer allocation

Add ability for CompositeReadableBuffer read specified length bytes
to another CompositeReadableBuffer instead of create temp
CompositeReadableBuffer.

fixes #3278
---------

Co-authored-by: Larry Safran <107004254+larry-safran@users.noreply.github.com>
2023-12-28 14:12:52 -08:00
yifeizhuang 846e008399
xds: Revert xds flow control change. (#10784)
* Revert "xds: fix flow control test failure (#10773)"

This reverts commit f67ec2ecd9.

* Revert "xDS: implement ADS stream flow control mechanism (#10674)"

This reverts commit 0a704a52ee.
2023-12-28 10:59:53 -08:00
yifeizhuang f67ec2ecd9
xds: fix flow control test failure (#10773) 2023-12-19 19:02:52 -08:00
Larry Safran 7be2b6c08d
Add increment as identified in #10768 (#10769) 2023-12-19 10:11:11 -08:00
James Roper 67b67f8382
Fix outbound message size checking (#10739)
This fixes two bugs in outbound message size checking:

* When thet checke failed, the thrown StatusRuntimeException with a status code
  of RESOURCE_EXHAUSTED was been caught and rewrapped in another
  StatusRuntimeException but this time with status code UNKNOWN.
* This applies the max outbound message size check to messages prior to, and
  after compression, since compression of a message that is smaller than the
  maximum send size can result in a larger message that exceeds the maximum
  send size.
2023-12-18 11:02:51 -08:00
yifeizhuang 0a704a52ee
xDS: implement ADS stream flow control mechanism (#10674) 2023-12-16 11:17:02 -08:00
Sergii Tkachenko 1680ada2fd
buildscripts: Use the Kokoro shared install lib from the new repo (#10757)
Source: 4f7ead2c7b/tools/internal_ci/linux/grpc_xds_k8s_install_test_driver.sh
New repo: https://github.com/grpc/psm-interop
New path: `.kokoro/psm_interop_kokoro_lib.sh`
2023-12-15 15:27:58 -08:00
Eric Anderson d6830d7f99
Change many api deps to implementation deps
These look pretty fair now, mostly only exposing grpc-api and
annotations as api dependencies.
2023-12-15 15:14:29 -08:00
Terry Wilson 8c4f4e08d9
Move Noop{Client,Server}Call from testing to api (#10753)
To help reduce cross dependencies, we move these test classes to the test
fixtures of grpc-api.
2023-12-14 23:00:30 -08:00
Eric Anderson a5f3483653 Upgrade distroless base images
gcr.io/distroless/java:8 is no longer being updated. Java 8 isn't a
distroless option any more. Java 11 and 17 are options, but only Java 17
with Debian 12. The main alternative is to stick with Java 8 and use
something like docker.io/library/eclipse-temurin:8-jre . But there
doesn't seem to be much need to use an old JDK for these containers.

jib needed updating to support the oci manifest format used in the
updated image.
2023-12-14 16:58:31 -08:00
Eric Anderson 225a7d30c9 core: Remove test dependency on grpclb
It was just unnecessary, and is isn't great having lower-level tests
depend on higher-level packages.
2023-12-14 09:26:58 -08:00
Eric Anderson 682d84c427 api: Remove unused grpc-core jmh dependency 2023-12-14 08:35:13 -08:00
Eric Anderson cf19263595 api: Remove test dependency on grpclb
It was just unnecessary, and is isn't great having lower-level tests
depend on higher-level packages.
2023-12-14 08:07:34 -08:00
Eric Anderson 201893f5e7 core: Improve language for leaked channel error
Originally you had to confirm that awaitTermination() returned true, but
that was annoying and useless, especially after calling shutdownNow().
The behavior was changed in ce2ae1fb because the awaitTermination()
detection logic could prevent the channel from getting garbage
collected.

Fixes #10732
2023-12-12 16:25:40 -08:00
Larry Safran e562a0558b
Remove Unused experimental API ManagedChannelBuilder.enableFullStreamDecompression. (#10744) 2023-12-12 14:56:22 -08:00
Ulf Adams 692696e2ed NettyServerBuilder: remove dead code
The KeepAliveManager clamps the keepalive and keepalive time values such that the result is larger than the minimum values specified here. Therefore, a second check here is unnecessary.
2023-12-12 14:02:00 -08:00
Shohei Kamimori 60c3133f4a README.md: Update the build badge
Travis is no longer used, the badge should be replaced by GitHub
Actions.
2023-12-12 13:01:40 -08:00
Eric Anderson c985797d90
Upgrade dependencies
All the changes outside libs.versions.toml and examples were
because of ErrorProne. It didn't actually find anything to fix; signal
vs noise has gotten pretty bad with the newer checks.

Status was changed for ErrorProne's SuperCallToObjectMethod. With the
old code it didn't notice the trivial implementation. The fail-for-test
code wasn't used, so it was easiest to just remove it.

Some of the libs had their versions inlined; now that we have
:checkForUpdates it isn't much of a risk for versions to diverge when
there's only a few artifacts sharing a version. If we need 4+ artifacts
to have the same version, then it makes sense to still use a shared
version.

Dependencies not upgraded: google-auth-libray, mockito, netty, cronet
2023-12-12 12:40:20 -08:00
Eric Anderson 68b14aaa49 RELEASING.md: Remove $ before commands
Removing the $ prompt makes it easier to copy+paste. At no point are we
running as root, so there's no # vs $ distinction, not that many people
would even notice the difference.

There is a risk here that not all commands end up getting run. When
pasting multiple commands at once, gradle or another tool might read in
stdin and discard them. But it's probably not worth continuing the
copy-each-command-separately-and-avoiding-the-$.
2023-12-12 08:57:20 -08:00
yifeizhuang 7567894e67
dual stack: generic health checking (#10623)
This change has health checking consumer (new pick first) to install a listener through and health checking producer (outlier detection and client health checking) producing health checks. Health notification chain is built reusing the previous connectivity state chain.
Pickfirst installs the health listener, and is capable of detecting when no health checking producer is installed in the system. In that case, it sets health status to be READY so that health system is no-op.
2023-12-11 17:49:56 -08:00
Eli Lipsitz 3e3ba56838 services: make BinlogHelper compatible with lite runtime
This commit makes a small change to BinlogHelper to make it compatible with the Protobuf Java Lite runtime.

In the Lite runtime, the `addXBuilder` for repeated fields is not available. Instead, the `addX` method must be used with a manually-constructed Builder.
2023-12-07 11:43:54 -08:00
Eric Anderson 55a9c012c3 Drop support for Bazel 5
Protobuf 25.0 drops support for Bazel 5. Bazel 7 is coming out very
soon, at which point we'd drop Bazel 5 anyway.
2023-12-07 10:06:42 -08:00
yifeizhuang 1a0c97a7a4
util: attributs is petiole policy (#10729) 2023-12-06 13:14:26 -08:00
Eric Anderson 8ac43dd816 util: Disable publishing of fixtures
We do the same in grpc-api and grpc-core
2023-12-06 10:07:21 -08:00
Mateus Azis a053889869
Handle slow security policies without blocking gRPC threads. (#10633)
* Handle slow security policies without blocking gRPC threads.

- Introduce PendingAuthListener to handle a ListenableFuture<Status>, progressing the gRPC through each stage in sequence once the future completes and is OK.
- Move unit tests away from `checkAuthorizationForService` and into `checkAuthorizationForServiceAsync` since that should be the only method called in production now.
- Some tests in `ServerSecurityPolicyTest` had their expectations updated; they previously called synchornous APIs that transformed failed `ListenableFuture<Status>` into one or another status. Now, we call the sync API, so those transformations do not happen anymore, thus the test needs to deal with failed futures directly.
- I couldn't figure out if this PR needs extra tests. AFAICT `BinderSecurityTest` should already cover the new codepaths, but please let me know otherwise.
2023-12-06 11:13:28 +01:00
Eric Anderson 4477269e2f Update README etc to reference 1.60.0 2023-12-05 13:40:06 -08:00
Eric Anderson d62334ea85
RELEASING.md: Include commit hash in shortlog (#10716)
This removes the benefit of including the PR number in the title without
also requiring using github APIs to query the PR number. It still
provides the same details about the change, and indirectly links to the
PR if the user wants to see the review.
2023-11-29 16:11:59 -08:00
Eric Anderson 56c5a0fe76 Update README etc to reference 1.59.1 2023-11-28 10:00:49 -08:00
Eric Anderson 7eb24d6ff0 Make custom tasks compatible with configuration cache
Gradle is forcing a move away from using 'project' during task excution
and because of some interactions there, this is easiest by making them
real classes. That makes them start looking quite strange in the build
file, so they are now moved to buildSrc/. We could have continued using
Groovy, but it is weird in some ways that are more apparent when making
classes and not just scripting. Instead, they were converted to Java.

They are compatible with delayed configuration resolution as well.
2023-11-27 14:28:44 -08:00
Eric Anderson dca89b25bf
util: Pass an AtomicInteger to RR's ReadyPicker
We already do this for WRR. Notably, we are no longer trying to avoid
the modulus each pick. It was of questionable value, and removing it is
necessary to continue sharing the same integer when the list size
changes.

The change means we can implement a stronger isEquivalentTo() by
comparing the AtomicInteger references. It is strong enough that the
operation aligns with normal equals(). Using equals() instead of
isEquivalentTo() also made more obvious an equals() optimization that
uses the hashCode() before the more expensive HashSet creation; equals()
should now be very fast except when they are (very likely) equal.
2023-11-27 14:27:42 -08:00
Eric Anderson 43e06372ec kokoro: Build android-interop-testing and binder separately
This avoids an OOM. We could probably configure things to run them
together, but that generally takes trial-and-error.
2023-11-27 10:15:42 -08:00
Eric Anderson a70dddd3dc kokoro: Use Firebase's arm virtual Android devices
They are a lot faster. Instead of 1-3 minutes of test execution, I now
see 2-22 seconds. There still may be 3 minutes of overhead for the
gcloud command to complete, but the reduction is noticable in the total
execution time. And it seems the tests are actually being run, as there
is some flakiness. The flakiness appears to be at a lower rate.

The script was slightly reorganized to make it easier to copy commands
to run locally.
2023-11-27 08:22:52 -08:00
Eric Anderson e65b4eb5a2 all: Add grpc-inprocess
This should have been added when inprocess was moved out of core. This
includes inprocess in the Javadoc and code coverage reporting.
2023-11-25 08:01:18 -08:00
Eric Anderson 0567ab5773 android-interop: Add testing for API levels 28-30
Note that this uses Pixel2 and Pixel3. Also swap 26-27 from Nexus6P to
Pixel2. We tend to prefer the latest (virtual) device for each API
level.

The current models and their supported API levels are available via:
```
gcloud firebase test android models list --filter=form=virtual
```

Pixel2.arm supports 31-32, but is beta, so I didn't swap to it. It also
supports the preview 33.
2023-11-22 14:49:19 -08:00
Eric Anderson 57dae6e20c inprocess: Add missing anonymous address as supported 2023-11-22 13:55:10 -08:00
Eric Anderson 860b5cb1f0 api: Deprecate LoadBalancer.EMPTY_PICKER
FixedResultPicker is our preferred approach.
2023-11-21 12:57:06 -08:00
Eric Anderson 3b92333890 core: Detect NameResolverProviders passed as Factories
This may help some to move closer to Providers. It especially helps
cases where `NameResolverFactory`s aren't returning `InetSocketAddress`,
as it allows them to override `getProducedSocketAddressTypes()`, which
will now fail starting in 15fc70be.
2023-11-21 10:56:55 -08:00
Eric Anderson c6d448e43f Remove getSubjectDN(), which is deprecated in Java 17 2023-11-20 10:06:19 -08:00
Eric Anderson 0987dc401c
netty: Add option to limit RST_STREAM rate
The behavior purposefully mirrors that of Netty's
AbstractHttp2ConnectionHandlerBuilder.decoderEnforceMaxRstFramesPerWindow().
That API is not available to our code as we extend the
Http2ConnectionHandler, but we want our API to be able to delegate to
Netty's in the future if that ever becomes possible.
2023-11-17 15:10:52 -08:00
Terry Wilson da4618ace1
util: Remove shutdown subchannels from OD tracking (#10683)
An OutlierDetectionLoadBalancer child load balancer might decided to
shut down any subchannel it is tracking. We need to make sure that those
subchannels are removed from the outlier detection tracker map to avoid
a memory leak.
2023-11-17 15:04:45 -08:00
John Cormie e89389a50a
api: Clarify that NameResolver can only be started once (#10681) 2023-11-17 07:44:24 -08:00
John Cormie bdb0c72d45
binder: Beef up hasPermissions security policy Javadoc (#10650)
Try to manage the fact that runtime permissions could be granted externally by the user after a hasPermissions() SecurityPolicy check has already been made on a transport.
2023-11-15 10:05:31 -08:00
Eric Anderson 32d85d8309 Start 1.61.0 development cycle 2023-11-15 07:41:12 -08:00
Benjamin Fedorka 2b65e660c0
netty: disable huffman coding in headers (#10563)
Huffman in the datacenter doesn't add much value in the common cases.  It could be useful to turn on huffman based on the connection latency (say, >10ms means "assume cross-datacenter") but the Netty API doesn't lend it to that. The savings here aren't huge and it is expensive; the table provides the biggest savings.
2023-11-14 11:09:38 -08:00
Patrick Koenig 90e76a1b4a
Implement Http2Headers.isEmpty (#10663) 2023-11-14 10:39:16 -08:00
Eric Anderson 0299788807 util: Make grpc-core an implementation dependency
This prevents grpc-core from being exposed on the classpath when
compiling code using grpc-util.
2023-11-13 16:52:42 -08:00
Eric Anderson 6257c59566
benchmarks: Remove usage of deprecated StreamObservers 2023-11-13 16:29:38 -08:00
yifeizhuang ae62785e0b
xds: fix ring hash childLB acceptResolvedAddress not in syncContext (#10664) 2023-11-13 14:58:30 -08:00
Vindhya Ningegowda d5544bbb02
opentelemetry : Implement metrics (#10593)
Adds a new module grpc-opentelemetry that integrates OpenTelemetry and focuses on metrics.

OpenTelemetry APIs are used for instrumenting metrics collection. Users are expected to provide SDK with implementations.

If no SDK is passed, by default gRPC uses OpenTelemetry.noop().
2023-11-13 10:58:16 -08:00
Eric Anderson 84baad12fc inprocess: Remove InProcessNameResolver
It was introduced in 15fc70be but unused. It could be "used" from
inprocess: targets, but the in-process transport wasn't registered, so
would fail.

We do want an in-process name resolver, but we need to agree no the URI
format cross-language before we introduce it.
2023-11-10 15:48:30 -08:00
Eric Anderson f2fc717749
testing: Add FakeNameResolverProvider.getProducedSocketAddressTypes (#10655)
This fixes BinderChannelSmokeTest, broken by 15fc70be.
2023-11-10 09:21:52 -08:00
Larry Safran dfdd50bc79
xds:Make Ring Hash LB a petiole policy (#10610)
* Update picker logic per A61 that it no longer pays attention to the first 2 elements, but rather takes the first ring element not in TF and uses that.
---------
Pulled in by rebase:
Eric Anderson  (android: Remove unneeded proguard rule 44723b6)
Terry Wilson (stub: Deprecate StreamObservers b5434e8)
2023-11-09 13:46:52 -08:00
Terry Wilson 0346b40e4e
stub: Deprecate StreamObservers (#10654)
This class is of questionable utility and generally not used.
2023-11-08 15:00:32 -08:00
Eric Anderson 3ca3b9975e
android: Remove unneeded proguard rule
The methods other than forTarget() were no longer used after 493af030.
forTarget() was no longer used after cda0e9d9.
2023-11-08 14:33:48 -08:00
Jeff Davidson 45ffb06f00 Bump compileSdkVersion and finalize setAllowActivityStarts API.
Per https://developer.android.com/about/versions/14#beta-3, Android U has reached the platform stability milestone which means that all external APIs are finalized.

We can thus bump the compileSdkVersion to 34 (U) and begin using APIs added there. We leave targetSdkVersion unchanged for now to avoid the broader evaluation of whether deeper changes may be necessary as part of the upgrade; this simply allows compile-time access to newer APIs without changing runtime behavior.

See b/274061424
2023-11-07 08:01:44 -08:00
Eric Anderson 7ba30f679a Bump Netty to 4.1.100.Final 2023-11-06 13:05:22 -08:00
Sergii Tkachenko 8b4b14ac40
core: add description to Status.UNKNOWN in ServerImpl's #internalClose (#10643)
This is currently the only place where we return Status.UNKNOWN with no description, which makes is harder to debug and differentiate from statuses originated from non-grpc sources.

This PR enriches ServerImpl's #internalClose `Status.UNKNOWN` with description `Application error processing RPC`.
2023-11-06 12:31:30 -08:00
sanjaypujare 15fc70be2a
core, netty, okhttp: implement new logic for nameResolverFactory API in channelBuilder (#10590)
* core, netty, okhttp: implement new logic for nameResolverFactory API in channelBuilder
fix ManagedChannelImpl to use NameResolverRegistry instead of NameResolverFactory
fix the ManagedChannelImplBuilder and remove nameResolverFactory

* Integrate target parsing and NameResolverProvider searching

Actually creating the name resolver is now delayed to the end of
ManagedChannelImpl.getNameResolver; we don't want to call into the name
resolver to determine if we should use the name resolver.

Added getDefaultScheme() to NameResolverRegistry to avoid needing
NameResolver.Factory.
---------

Co-authored-by: Eric Anderson <ejona@google.com>
2023-11-03 09:57:59 -07:00
Terry Wilson 9888a54abd
lb: acceptResolvedAddresses() to return Status (#10636)
Instead of a boolean, we now return a Status object. Status.OK
represents accepted addresses and other non-acceptance. This allows the
LB to provide more information about why a set of addresses were not
acceptable.

The status will later be sent to the name resolver as well to allow it
to also better react to to bad addresses.
2023-11-03 09:02:46 -07:00
erm-g 4fbefe9f0f
alts: Add propagation of original exception for AltsHandshakerStub (#10644)
This PR addresses a bug which is a part of #9058. It propagates the
original exception caught at AltsHandshakerStub.Reader.onError().
2023-11-03 07:50:52 -07:00
Sergii Tkachenko a294b27d52
core: Deprecate ForwardingChannelBuilder (#10587)
Deprecate `ForwardingChannelBuilder` in favor of `ForwardingChannelBuilder2`.
2023-11-02 10:58:20 -07:00
Eric Anderson 073ca92e24
alts: Re-enable deprecation warnings (#10640)
google/protobuf#4046 was fixed a long time ago. Recently noticed when
working on ForwardingChannelBuilder(2).
2023-11-02 10:09:09 -07:00
Sergii Tkachenko 302f756449
interop-testing: Improve ChannelAndServerBuilderTest readability (#10641)
Add javadoc and code readability refactoring
2023-11-02 10:06:40 -07:00
Terry Wilson 84ddcb04e0
interop-testing: Fix total calls log statement (#10639)
We don't want local specific formatting of the number, so let's just
concatenate.
2023-10-31 14:20:22 -07:00
Terry Wilson d3729faea6
interop-testing: Fix disabling of stream tracers (#10638)
The client stream tracers need to be disabled before setUp() is called.
2023-10-31 14:17:51 -07:00
Mateus Azis b6947de95a
Introduce the AsyncSecurityPolicy class. (#10622)
This is the async variant of SecurityPolicy, allowing callers to implement security checks based on slow calls that aren't meant to block the gRPC thread.

BinderTransportSecurity.checkAuthorization **STILL** blocks while attempting to resolve the ListenableFuture<Status> it gets from the policy object. That will still be adressed in a follow-up.

Relate issue: #10566
2023-10-26 19:14:39 +02:00
Terry Wilson cd810c5284
protobuf: Stabilize ProtoUtils.metadataMarshaller() (#10628)
This method has been around since 2018 and is now considered stable.
2023-10-25 15:38:35 -07:00
Terry Wilson 7bd2e5b59c
protobuf-lite: ProtoLiteUtils experimental comment (#10627)
Add a comment clarifying that the ProtoLiteUtils class will remain
experimental.
2023-10-25 15:37:49 -07:00
Terry Wilson 18a5f8a90b
interop-testing: Stress test log for total calls (#10626)
Allows stress tests to make assertions based on the total amount of
calls made by the stress test client.
2023-10-25 14:19:32 -07:00
Yannick Epstein 86835ae817
xds: Log ORCA UNIMPLEMENTED error to subchannel logger (#10625)
Logging to the static instance would result in application logs filling
up if the Orca service is not available.
We'd like to have the logging on the subchannelLogger, so we make it
visible on demand.

Also succeed Orca logging test if log message present. Using
contains over containsExactly seems more reasonable.
2023-10-25 10:19:37 -07:00
Terry Wilson 6cf6380812
releasing: add git command for pushing gh-pages (#10621) 2023-10-20 15:16:56 -07:00
Terry Wilson 2bec8cdf1d
Update README etc to reference 1.59.0 (#10620) 2023-10-20 14:29:26 -07:00
Mateus Azis 8966680015
binder: Allow async/slow implementations of authorization checks (#10596)
Allow a security policy to returns a `ListenableFuture<Status>` that
callers can implement to perform slower auth checks (like network
calls, disk I/O etc.) without necessarily blocking the gRPC calling
thread.

Partially addresses: https://github.com/grpc/grpc-java/issues/10566
2023-10-20 13:53:12 -07:00
Terry Wilson ccf9101828
interop-testing: allow disabling of stream tracers (#10609)
This adds the ability to disable the installation of stream tracers in
each test call in AbstractInteropTest. The tracers are stored in a list
and used to make assertions by normal tests, but a long running stress
test will accumulate too many entries in this list and the heap gets
wuickly filled up.
2023-10-17 08:37:15 -07:00
Larry Safran 0d39bf5018
lb:Implement LeastRequestLB as a petiole policy and restore RR and WRR (#10584)
* Change LeastRequest, Round Robin and WeightedRoundRobin into petiole policies
2023-10-16 16:40:20 -07:00
Terry Wilson fc03f2be9d Remove extra parenthesis 2023-10-09 17:17:50 -07:00
Terry Wilson 501246374c Line up usage and add assertions 2023-10-09 17:17:50 -07:00
Terry Wilson 21c287f7c3 interop-testing: Custom credentials in stress test
Adds support for specifying either google default or compute engine
"custom" credentials on the command line. This works like it does in
TestServiceClient.

Another feature from TestServiceClient is also included - the channel
builder is created differently when the server port is 0. This avoids
some ipv6 address parsing shenanigans.
2023-10-09 17:17:50 -07:00
Terry Wilson e488b67d99 gradle: Downgrade mockito to 4.4.0
Starting from version 4.5.0 Mockito uses the Java stream APIs, which are
not available on Android API levels < 24. This has been causing the
Android integration tests for API levels 21, 22 and 23 to fail.
2023-10-09 13:29:12 -07:00
amirhadadi 8c0545564f
Avoid flushing headers when the server returns a single response (#9314)
* core,netty: avoid flushing the headers on the server side when the server has a single response.
2023-10-09 09:43:10 -07:00
Anthony J. Pratti aec9a56eaf
cleanup: protobuf_java_lite typo in IO_GRPC_GRPC_JAVA_OVERRIDE_TARGETS (#10592) 2023-10-06 13:26:34 -07:00
Sergii Tkachenko ab8210ae0c
Stabilize forwarding builders (#10586)
- `ForwardingServerBuilder`
- `ForwardingChannelBuilder` - will be deprecated immidiatelly after
   stabilization
- `ForwardingChannelBuilder2` - should be used instead of
  `ForwardingChannelBuilder`
2023-10-06 11:18:29 -07:00
Terry Wilson 8a247ad16a interop-testing: Logging of stress test metrics
Introduces a flag to enable the logging of collected metrics. In some
cases it can be more practical to analyze the metrics from a log file
after the fact, instead of connecting to the metrics server to collect
the metrics as the client is running.
2023-10-05 16:19:31 -07:00
Terry Wilson bf9ccc68f5 Start 1.60.0 development cycle 2023-10-04 10:29:43 -07:00
Sergii Tkachenko 0e03654add core: Remove temporary AbstractManagedChannelImplBuilder
This breaks the ABI of the classes listed below.

Users that recompiled  their code using grpc-java [`v1.36.0`]
(https://github.com/grpc/grpc-java/releases/tag/v1.36.0) (released on
Feb 23, 2021) and later, ARE NOT AFFECTED.

Users that compiled their source using grpc-java earlier than
[`v1.36.0`]
(https://github.com/grpc/grpc-java/releases/tag/v1.36.0) need to
recompile when upgrading to grpc-java `v1.59.0`. Otherwise the code
will fail on runtime with `NoSuchMethodError`. For example, code:

```java
NettyChannelBuilder.forTarget("localhost:100").maxRetryAttempts(2);
```

Will fail with

> `java.lang.NoSuchMethodError: 'io.grpc.internal.AbstractManagedChannelImplBuilder
  io.grpc.netty.NettyChannelBuilder.maxRetryAttempts(int)'`

**Affected classes**

Class `AbstractManagedChannelImplBuilder` is deleted, and no longer in
the class hierarchy of the channel builders:
- `io.grpc.netty.NettyChannelBuilder`
- `io.grpc.okhttp.OkhttpChannelBuilder`
- `grpc.cronet.CronetChannelBuilder`
2023-10-03 10:35:16 -07:00
Sergii Tkachenko 050ae18e2a core: Remove temporary AbstractServerImplBuilder
This breaks the ABI of the classes listed below.

Users that recompiled  their code using grpc-java [`v1.36.0`]
(https://github.com/grpc/grpc-java/releases/tag/v1.36.0) (released on
Feb 23, 2021) and later, ARE NOT AFFECTED.

Users that compiled their source using grpc-java earlier than
[`v1.36.0`]
(https://github.com/grpc/grpc-java/releases/tag/v1.36.0) need to
recompile when upgrading to grpc-java `v1.59.0`. Otherwise the code
will fail on runtime with `NoSuchMethodError`. For example, code:

```java
NettyServerBuilder.forPort(80).directExecutor();
```

Will fail with

> `java.lang.NoSuchMethodError: 'io.grpc.internal.AbstractServerImplBuilder
  io.grpc.netty.NettyServerBuilder.directExecutor()'`

**Affected classes**

Class `AbstractServerImplBuilder` is deleted, and no longer in the
class hierarchy of the server builders:
- `io.grpc.netty.NettyServerBuilder`
- `io.grpc.inprocess.InProcessServerBuilder`
2023-10-03 10:35:16 -07:00
Eric Anderson 2cbc290755 okhttp: Make grpc-util an implementation dependency
This prevents grpc-util from being exposed on the classpath when
compiling code using grpc-okhttp. grpc-core is still needed because of
AbstractManagedChannelImplBuilder.
2023-09-29 15:10:02 -07:00
Eric Anderson 1d03bb80a9 Bump rules_jvm_external to 5.3
I'm not choosing any version in particular (just the latest). The main
point is to get off a "random" commit that had a fix for Netty.
2023-09-28 09:33:09 -07:00
Larry Safran bc784c0ef9
Revert "Change Round Robin and WeightedRoundRobin into petiole policies (#10528)" (#10575)
This reverts commit e1334eae7b.
2023-09-26 17:31:58 -07:00
Eric Anderson cf4cf03d79
api: Replace ErrorPicker with FixedResultPicker
FixedResultPicker can be used in more situations. Note that
WrrLocalityLoadBalancerTest's test was changed non-trivially. The
noChildLb test was particularly nasty as it assumed
LoadBalancer.ErrorPicker had same toString() as
GracefulSwitchLoadBalancer's ErrorPicker.
2023-09-26 15:28:29 -07:00
Eric Anderson a004096b3c Revert "stub: enable throwing rejected execution exception on ThreadlessExecutor shutdown (#10555)"
This reverts commit 5f480de2ee. We're
seeing it thrown in (b/301552213):

```
java.util.concurrent.RejectedExecutionException
	at io.grpc.stub.ClientCalls$ThreadlessExecutor.execute(ClientCalls.java:761)
	at io.grpc.internal.RetriableStream$Sublistener.closed(RetriableStream.java:954)
	at io.grpc.internal.ForwardingClientStreamListener.closed(ForwardingClientStreamListener.java:34)
	at io.grpc.internal.InternalSubchannel$CallTracingTransport$1$1.closed(InternalSubchannel.java:691)
	at io.grpc.internal.DelayedStream$DelayedStreamListener$4.run(DelayedStream.java:510)
	at io.grpc.internal.DelayedStream$DelayedStreamListener.delayOrExecute(DelayedStream.java:462)
	at io.grpc.internal.DelayedStream$DelayedStreamListener.closed(DelayedStream.java:507)
	at io.grpc.internal.AbstractClientStream$TransportState.closeListener(AbstractClientStream.java:458)
	at io.grpc.internal.AbstractClientStream$TransportState.-$$Nest$mcloseListener(AbstractClientStream.java)
	at io.grpc.internal.AbstractClientStream$TransportState$1.run(AbstractClientStream.java:441)
	at io.grpc.internal.AbstractClientStream$TransportState.deframerClosed(AbstractClientStream.java:278)
	at io.grpc.okhttp.OkHttpClientStream$TransportState.deframerClosed(OkHttpClientStream.java:297)
	at io.grpc.internal.MessageDeframer.close(MessageDeframer.java:234)
	at io.grpc.internal.MessageDeframer.closeWhenComplete(MessageDeframer.java:192)
	at io.grpc.internal.AbstractStream$TransportState.closeDeframer(AbstractStream.java:201)
	at io.grpc.internal.AbstractClientStream$TransportState.transportReportStatus(AbstractClientStream.java:444)
	at io.grpc.okhttp.OkHttpClientTransport.startGoAway(OkHttpClientTransport.java:899)
	at io.grpc.okhttp.OkHttpClientTransport.-$$Nest$mstartGoAway(OkHttpClientTransport.java)
	at io.grpc.okhttp.OkHttpClientTransport$ClientFrameHandler.run(OkHttpClientTransport.java:1123)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:644)
	at java.lang.Thread.run(Thread.java:1012)
```
2023-09-25 13:50:06 -07:00
Anirudh Ramachandra fec7c2ea4a
Add fix for xdstp replacement for encoded authorities (#10571)
In ac35ab6 the logic in xDS Name resolver was changed to support encoded
authorities. This seems to cause an issue for xdstp replacements which
would percent encode the authority for the replacement causing double
encoding.

For example:

URI = xds:///path/to/service
Authority = path%2Fto%2Fservice
xdstp resource = xdstp:///envoy.config.listener.v3.Listener/path%252Fto%252Fservice

Here the authority is encoded due to slashes and during replacement we
percent encode it again causing %2F to change to %252F. To avoid this
issue, use the encoded authority only for the getServiceAuthority() API
and for all other use cases retain the unencoded authority.
2023-09-22 08:25:08 -07:00
Eric Anderson 88b3484a60 Bump Netty to 4.1.97.Final 2023-09-21 17:15:31 -07:00
Larry Safran 0c415e8784
Eliminate use of getOrDefault (#10565)
* Eliminate use of getOrDefault
2023-09-19 13:42:34 -07:00
sanjaypujare 7d9b76e330
examples: add an example for OAuth (#10560) 2023-09-18 09:56:16 -07:00
Larry Safran 6f09466edb
netty: Eliminate buffer release when there is an error as caller still owns the buffer. (#10537)
* netty: Eliminate buffer release when there is an error as caller still owns the buffer.
---------

Co-authored-by: Sergii Tkachenko <hi@sergii.org>
2023-09-15 15:18:03 -07:00
Larry Safran e1334eae7b
Change Round Robin and WeightedRoundRobin into petiole policies (#10528)
* Change Round Robin and WeightedRoundRobin into petiole policies
2023-09-15 10:27:36 -07:00
Terry Wilson 69986b542e COMPILING.md: Fix small typo 2023-09-14 12:03:20 -07:00
Eric Anderson 3eb5d20f6c servlet: Avoid lincheck for normal testing
It is slow, and just tries a bunch of possibilities. Leave it around for
developers to run locally, but it isn't precise enough to run on every
build. This change reduces the build of servlet in isolation by
1 minute. I suspect the gains are larger in a full grpc build because it
is very CPU-intensive; it uses 600% CPU on my 8-thread CPU when running
by itself.
2023-09-13 10:49:37 -07:00
John Cormie 134b0490d5
Enable indirect addressing using <intent-filter>s. (#10550)
AndroidComponentAddress now accepts an Intent with merely a package
restriction, not a full ComponentName. This lets clients avoid hard
coding Service class names that they don't control.

Fixes #9062
2023-09-12 17:27:35 -07:00
yifeizhuang 5f480de2ee
stub: enable throwing rejected execution exception on ThreadlessExecutor shutdown (#10555) 2023-09-12 13:41:15 -07:00
sanjaypujare 923ac60416
api: don't generate Java7 bytecode with Java 20+ (#10552)
Java 20+ don't support --release 7, so we just will use the default (8).
2023-09-11 13:41:50 -07:00
Eric Anderson b839b38b83 api: Add grpc-okhttp to suggestions if no server is available
Since 3b61799 OkHttp can support Grpc.newServerBuilderForPort().
2023-09-11 13:40:26 -07:00
yifeizhuang 6335e0be3e
core: DEADLINE_EXCEEDED gives hints for slow resolver (#10545) 2023-09-08 15:09:18 -07:00
yifeizhuang 75af7abf45
Update README etc to reference 1.58.0 (#10547) 2023-09-08 10:35:14 -07:00
Larry Safran 878e301a5c
netty: Respect io.netty.allocator.type="unpooled" when getting Netty Allocator (#10543)
Fixes #10292
2023-09-07 14:58:46 -07:00
Eric Anderson d4a163461a netty: Touch ByteBuf when message framing has been decoded
When a memory leak occurs, it is really helpful to have access records
to understand where the buffer was being held when it leaked. retain()
when we create the NettyReadableBuffer already creates an access record
the ByteBuf, so here we track when the ByteBuf is passed to another
thread.

See #8330
2023-09-07 13:15:22 -07:00
Eric Anderson 131a0047c4 netty: Use UNAVAILABLE for connections closed while writing
Fixes #10474 and b/273930962
2023-09-06 12:41:03 -07:00
Stephane Landelle cb2b68e39d core: only try to resolve InternalCensusStatsAccessor once 2023-09-06 11:12:04 -07:00
Stephane Landelle 22863dda38 netty: Use JUL instead of String.format 2023-09-06 11:12:04 -07:00
Eric Anderson 461dc85ba6 api: Make offload executor's purpose more clear
Blocking can be confused with the blocking stub, which is unrelated. I'm
purposefully not saying "it is used only for X," as that isn't what we
need from the API. But it is still helpful to users to describe the
sorts of things that use it.

Fixes #10508
2023-09-06 07:44:35 -07:00
kotlaja 9ab35b05de
java_grpc_library.bzl: Disable Automatic Exec Groups inside grpc libraries (#10514) 2023-09-05 17:21:10 -07:00
Terry Wilson 36e0af66fe
core: de-expermentalize pick first config parsing (#10531) 2023-08-30 15:40:34 -07:00
Terry Wilson b63e1579ed
testing: Stabilize TestMethodDescriptors (#10530) 2023-08-30 12:54:20 -07:00
Eric Anderson d15daed5e4 interop-testing: Modernize stress test channel creation
OverrideAuthority() is the modern alternative to rewriting the
InetAddress, and can also work if we change the channel creation to use
target strings instead. We can use test CAs now without resorting to the
Netty-specific APIs. After this change, only 4 classes in
interop-testing depend on Netty.
2023-08-25 16:55:46 -07:00
Larry Safran 92174be3df
Log warning message when server side gets exception writing message to stream and allow multiple closes (#10513)
* Use internalClose instead of close when sendMessage has a RuntimeException.
* Change argument to internalClose to a Throwable instead of a Status.
* Rename internalClose to handleInternalError
2023-08-24 16:40:23 -07:00
yifeizhuang 9424f8b4c7
Start 1.59.0 development cycle (#10519) 2023-08-24 11:25:28 -07:00
Terry Wilson 5559d54f5d
examples: Android helloworld to pass Google lint (#10518)
These changes allow the Android helloworld example to pass the lint
checks of the Google internal build system.
2023-08-24 10:37:53 -07:00
Larry Safran 3fad52129f
Fix aarch_64 macs not being able to build the compiler module. (#10516) 2023-08-23 14:58:11 -07:00
Terry Wilson 2b4f649b0a
android: Min SDK level to 21 (#10505)
Google Play has dropped support for SDK levels 19 and 20 and so can we.
2023-08-22 10:47:31 -07:00
Eric Anderson 1fc3649556 interop-testing: Correctly expose API types to dependents
Interop-testing is both binaries and a library. It hadn't been updated
to use java-library and to expose API-surface dependencies to
dependents.

This fixes the error:
```
> Task :grpc-gae-interop-testing-jdk8:javadoc FAILED
javadoc: error - An internal exception has occurred.
        (com.sun.tools.javac.code.Symbol$CompletionFailure: class file for io.grpc.internal.testing.StreamRecorder not found)
Please file a bug against the javadoc tool via the Java bug reporting page
(http://bugreport.java.com) after checking the Bug Database (http://bugs.java.com)
for duplicates. Include error messages and the following diagnostic in your report. Thank you.
com.sun.tools.javac.code.Symbol$CompletionFailure: class file for io.grpc.internal.testing.StreamRecorder not found
1 error
```
2023-08-21 07:38:17 -07:00
Larry Safran 55c5040cb5
Remove ThreadlessExecutor from BlockingServerStream (#10496)
* Remove ThreadlessExecutor from BlockingServerStream

fixes #10490
2023-08-18 10:16:43 -07:00
yifeizhuang eb18cba062
stablize ServerBuilder.handshakeTimeout (#10499) 2023-08-18 10:13:34 -07:00
Eric Anderson ceadf6df6d Upgrade to Gradle 8.3
Examples are updated to use the new version as well, which wasn't done
last time in f3f4ed4ef. That noticed some things that were missed
before.
2023-08-18 09:59:57 -07:00
Eric Anderson 67f4eabb42 xds: In tests, verify WRR static stride does not iterate too many times 2023-08-18 09:59:33 -07:00
Terry Wilson d987fb10aa
api: ManagedChannelBuilder note about ipv6 scope id JDK bug. (#10503)
Adds a note on how to avoid a JDK bug by converting an ipv6 scope ID to
its numeric form.
2023-08-17 18:05:15 -07:00
Tony An 97f4f8687c
xds: WRR scheduler clips weights (#10480) 2023-08-17 17:11:55 -07:00
Terry Wilson 26be0c7665
buildscripts: add missing $GRADLE_FLAGS to enable AndroidX (#10504) 2023-08-17 16:32:23 -07:00
Terry Wilson beaeeefdd2
examples: Android examples to use AGP 7.4.0 (#10497)
- Upgrades AGP version to 7.4.0
- Upgrades appcomat to use AndroidX
- Updates the `android.sh` build script to set the `android.useAndroidX` flag
2023-08-17 11:24:42 -07:00
Eric Anderson b13a656f46
servlet: Support configuration avoidance in build
Instead of adding explicit dependsOn to compileJava and sourcesJar,
adding the sync task to the sourceSet automatically propagates the
dependency to all consumers of the code.
2023-08-17 10:19:20 -07:00
sanjaypujare 0fd4e3b122
api: stabilize ServerCall.getAuthority() by removing experimental annotation (#10498) 2023-08-16 18:40:18 -07:00
Sergii Tkachenko 2e95631b10
testing: Stabilize GrpcCleanupRule, GrpcServerRule (#10494)
Closes #2488.
2023-08-16 18:33:58 -07:00
Eric Anderson 3e44bbfe4a Exclude Internal classes from javadoc 2023-08-16 15:38:30 -07:00
yifeizhuang 5f34c600c4
okhttp: okhttp client and server transport should use padded length for flow control (#10422) 2023-08-16 15:12:19 -07:00
Tony An 93118f4075
API stabilization: getRequestMarshaller, getResponseMarshaller (#10495) 2023-08-16 15:04:49 -07:00
Terry Wilson be16afd213
Update README etc to reference 1.57.2 (#10491) 2023-08-16 13:39:38 -07:00
Eric Anderson e6c77a368a xds: Add missing ExperimentalApi to OrcaServiceImpl 2023-08-16 11:24:59 -07:00
Larry Safran f90656293f
Mark MultiChildLoadBalancer as Internal. (#10481)
* Mark MultiChildLoadBalancer as Internal.  Cannot move to the internal package because of its use of classes in the util package.

* Exclude MultiChildLoadBalancer from javadoc generation.

* Fix javadoc creation.
2023-08-15 17:33:23 -07:00
Eric Anderson b5d7f1394d xds: Fix import scripts deleting the wrong files, use of trap, and full git clone
The scripts used `git rev-parse --show-toplevel` so it appeared they
could be used from any directory. But references to "GIT_BASE_DIR"
weren't absolute, so it did matter the starting directory. And it
mattered in a big way for xds/import.sh as if you ran it from the
grpc-java directory it would delete the xds directory in grpc-java, not
third_party.

The trap that deleted the GIT_BASE_DIR was very broken. In addition to
potentially deleting the wrong directory, it was unnecessary because
that directory was in tmpdir. But you can only have one trap per signal,
so this unnecessary trap disabled the trap that deleted tmpdir.

The script needed a full clone because it needed to check out a specific
commit. To work with --depth 1 you have to use some convoluted syntax.
But just downloading a tar.gz is easy and seems should work fine on Mac.

protoc-gen-validate/import.sh didn't have the trap problem, but seemed
to have drifted from the other scritps. All the scripts were synced to
match.
2023-08-15 16:54:32 -07:00
Mohan Li 5850de2f5f
pick_first: de-experiment pick first (#10475) 2023-08-15 15:48:24 -07:00
Eric Anderson 9585bc948a build.gradle: Modernize japicmp confiuration
Even though we don't really use japicmp, the configuration was resolving
artifacts even when the task was not executed. After some clean up, the
configuration looks more ordinary.
2023-08-14 17:01:38 -07:00
Eric Anderson 849186ac35
examples: Add pre-serialized-message example (#10112)
This came out of the question #9707, and could be useful to others.
2023-08-14 17:00:29 -07:00
Tony An fba7835de1
new pick first policy, architectural change (#10354) 2023-08-14 15:23:40 -07:00
Eric Anderson 778c209751 java_grpc_library.bzl: Allow toolchain to use annotation processors
While not easy to use because java_grpc_library() uses a fixed
toolchain, it is possible for downstream users to apply a patch to the
repo to add their own annotation processors. This feature was added
inside Google so exporting it reduces the diff between internal and
external and causes no harm.

cl/280287611
2023-08-14 12:51:18 -07:00
Eric Anderson 47a84c48c7 RELEASING.md: Prefix grpc/grpc commit with [interop]
They require this style.
2023-08-14 10:55:49 -07:00
Eric Anderson f8baa9ca1d Upgrade protobuf-java and protoc to 3.24.0 2023-08-14 09:20:39 -07:00
Mohan Li cebb4659a1
test: allow set request/response size in interop soak test (#10465) 2023-08-10 10:30:41 -07:00
Eric Anderson 3b61799f73 okhttp: Add OkHttpServerProvider
This allows okhttp to service the Grpc.newServerBuilderForPort() API.
Note that, unlike Netty, it will throw if you try to use
ServerBuilder.forPort().

This fixes android-interop-testing which was broken by c9864a119.
2023-08-09 13:58:34 -07:00
Larry Safran a0d8f2eb31
Create a shared LB base class for LBs with multiple children (#10448)
* Create a shared LB base class for LBs with multiple children and change ClusgterManagerLoadBalancer to use it.
2023-08-08 14:36:27 -07:00
Terry Wilson 4453ce7eb6
util: Outlier detection tracer delegation (#10459)
OutlierDetectionLoadBalancer did not delegate calls to an existing
ClientStreamTracer from the tracer it installed. This change has the OD
tracer delegate all calls to the underlying one.
2023-08-08 14:35:44 -07:00
Eric Anderson c9864a1198 android-interop-testing: Remove usage of Netty for grpc server
We have the OkHttp server these days, so we don't need to use Netty. Use
the generic API instead of hard-coding OkHttp.

We've seen some recent interop failures. We aren't entirely sure what is
going on, but we have seen some Netty usages in logcat. Since we don't
even want Netty on Android, just get rid of it and even if it doesn't
help with the failures things are better dependency-wise.
2023-08-08 14:30:32 -07:00
Tony An 40bff673c0
xds: replace random with atomic sequence in WRR (#10458) 2023-08-07 16:19:50 -07:00
Eric Anderson 4049f89e13
README.md: Revert reference to protobuf 3.23.4 (#10430)
The README describes the released version of gRPC. But the most recent
release doesn't use protobuf 3.23.4. Telling people to use protoc 3.23.4
is asking for breakages because they will be running with protobuf-java
3.22.3, which is a downgrade.

The bump to 3.23.4 was incorrectly done in #10359.
2023-08-03 10:53:38 -07:00
Eric Anderson 1638ce39f8 .github: Use checkout@v3 for Bazel
The other jobs were swapped to v3 in 38311e8730. Bazel was added later
with the older version.

This fixes the warning:
```
The following actions uses node12 which is deprecated and will be forced to run on node16: actions/checkout@v2. For more info: https://github.blog/changelog/2023-06-13-github-actions-all-actions-will-run-on-node16-instead-of-node12-by-default/
```
2023-08-03 07:28:22 -07:00
Eric Anderson 1e5480847a Update README etc to reference 1.57.1 2023-08-02 14:56:26 -07:00
Eric Anderson f3f4ed4ef3 Upgrade to Gradle 8.2.1 and upgrade plugins
Most changes are migrating from conventions to the equivalent
extensions. JMH, AppEngine, and Jib plugins trigger future compatibility
warnings with `--warning-mode all`.

The movement of configurations was to allow sourceSets to create the
configurations and then we just configure them. When configurations were
before sourceSets, we'd implicitly create the configuration.

The examples were _not_ updated to the newer Gradle, although the
non-Android examples work with the newer Gradle. The Android examples
use an older Android Gradle Plugin which will need to be upgraded first.
https://github.com/grpc/grpc-java/issues/10445
2023-08-02 13:29:44 -07:00
Zach Reyes 6d48271fa4
buildscripts: Add bootstrap generator to cron job that runs nightly (#10440) 2023-08-02 13:04:56 -07:00
Eric Anderson b67a29af3b all: Copy mustRunAfter from each project's JacocoTestReport
While JacocoReportBase.getExecutionData() is properly annotated with
`@InputFiles` and is a FileCollection, which can propagate dependencies,
the JacocoPlugin's configuration of the task [goes through a
File][barefile], which doesn't propagate task dependency information.
This is overcome in the plugin by mustRunAfter. This may have been on
purpose to allow jacocoTestReport to report on the subset of tests
already run, but is atypical these days.

Because of that, we need to copy the mustRunAfter from the other
JacocoTestReports. The dependsOn weren't doing anything because there
were no dependsOn; that configuration is quite old so it's hard to say
when they stopped functioning.

This fixes warnings like:
```
  - Gradle detected a problem with the following location: 'grpc-java/core/build/jacoco/test.exec'. Reason: Task ':grpc-all:jacocoTestReport' uses this output of task ':grpc-core:test' without declaring an explicit or implicit dependency. This can lead to incorrect results being produced, depending on what order the tasks are executed. Please refer to https://docs.gradle.org/7.6/userguide/validation_problems.html#implicit_dependency for more details about this problem.
  - Gradle detected a problem with the following location: 'grpc-java/testing/build/resources/main'. Reason: Task ':grpc-all:jacocoTestReport' uses this output of task ':grpc-testing:processResources' without declaring an explicit or implicit dependency. This can lead to incorrect results being produced, depending on what order the tasks are executed. Please refer to https://docs.gradle.org/7.6/userguide/validation_problems.html#implicit_dependency for more details about this problem.
```

I was able to trigger the warnings by:
```
./gradlew clean
./gradlew :grpc-core:test
./gradlew :grpc-all:jacocoTestReport
./gradlew :grpc-core:test :grpc-all:jacocoTestReport
```

[barefile]: bc4029063c/subprojects/jacoco/src/main/java/org/gradle/testing/jacoco/tasks/JacocoReportBase.java (L162-L168)
2023-08-02 10:41:28 -07:00
sanjaypujare a589eacc8f
stub: remove 2 deprecated methods from MetadataUtils (#10443) 2023-08-01 11:00:23 -07:00
Eric Anderson 1dee7efca4 Avoid accidental Java 9+ dependency with --release
In d654707 we swapped compiling the uploaded artifacts to Java 11. This
caused ABI issues with ByteBuffer, like clear() returning ByteBuffer
instead of Buffer.

There are source-level approaches to avoid the accidental ABI dependency
on Java 11, but we have no tool able to detect such breakages.
We use Animalsniffer for similar cases, but it fails to detect these[1].
Since we have no tool, source-level approaches can't gain the necessary
confidence that all incompatibility fixes have been resolved.

Java has had javac-level ways to address this, but they used to require
setting bootclasspath. Since Java 9, though, they made it easier and we
can use --release, which does exactly what we need.

Fixes #10432

1. https://github.com/mojohaus/animal-sniffer/issues/77
2023-07-31 17:51:49 -07:00
Halvard Skogsrud 4dc786b5be
Fix locality logging (#10423)
The bootstrapping code currently does not log zone and subZone from locality correctly, and only logs region. This commit fixes the logging message format.
2023-07-31 17:44:16 -07:00
Eric Anderson 8121e8118e api: Link to gRFCs A8/A9 for keepalive and related settings
This is to give users a place to look to learn more.
2023-07-31 16:46:41 -07:00
Tony An d9a464e725
Context.Storage deprecated method attach() removed, doAttach() made abstract (#10379) 2023-07-31 16:38:01 -07:00
Tony An 3c19325587
removed assert for flakey static stride scheduler with multiple threads (#10437)
on master branch
2023-07-31 14:03:00 -07:00
Larry Safran 944de93f79
Minor cleanup in releasing instructions (#10426) 2023-07-30 20:06:48 -07:00
Larry Safran 621fbad78c
Reduce test flakiness (#10429) 2023-07-28 14:55:37 -07:00
Larry Safran 31d5b40672
Update README etc to reference 1.57.0 (#10427) 2023-07-28 14:44:13 -07:00
Kun Zhang c5c37ac51c
binder/test: Stop running Robolectric tests on APIs < 19 (#10385)
This is a port of internal cl/547560711, but with a change to call
isDeviceOwner that requires sdk 18 unconditioally
2023-07-26 10:44:56 -07:00
sanjaypujare 41552bfd9a
all: generate automatic module name in the manifest (#10413) 2023-07-25 09:00:11 -07:00
Larry Safran 08a44b9224
Handle header with errors and endStream = true (#10384) (#10412)
* Eliminate NPE by skipping further processing when stream is defined, but doesn't have a property for streamKey (header processing identified an error)

Fixes #10364

* Add unit test for missing content type
2023-07-24 14:33:07 -07:00
Eric Anderson a77e1a240a Downgrade Netty to 4.1.93-Final
Our benchmarks saw a serious performance decrease with the upgrade from
Netty 4.1.88 to 4.1.94. The problem was tracked down to a single PR in
4.1.94, so we avoid 4.1.94 for now.

Fixes #10401
2023-07-21 17:41:41 -07:00
yifeizhuang e179212672
core: fix retriablestream deadlock (#10386) 2023-07-21 13:48:37 -07:00
Larry Safran afa4d6dac8
Have rls's LRU Cache rely on cleanup process to remove expired entries (#10400)
* Add test for multiple targets with cache expiration.
2023-07-21 12:12:19 -07:00
Sergii Tkachenko 419767f968
Upgrade dependencies post v1.57.x branch cut (#10359)
### Dependency updates

#### Update successfully to the latest
- [x] `androidx.core:core 1.10.0 -> 1.10.1`
- [x] `com.google.api.grpc:proto-google-common-protos 2.17.0 -> 2.22.0`
- [x] `com.google.cloud:google-cloud-logging 3.14.5 -> 3.15.5`
- [x] `com.google.truth:truth 1.0.1 -> 1.1.5`
- [x] `com.puppycrawl.tools:checkstyle 8.28 -> 10.12.1`
- [x] `org.robolectric:robolectric 4.9.2 -> 4.10.3`
- [x] Auto-value
   - [x] `com.google.auto.value:auto-value 1.10.1 -> 1.10.2`
   - [x] `com.google.auto.value:auto-value-annotations 1.10.1 -> 1.10.2`
- [x] Protobuf
   - [x] `com.google.protobuf:protobuf-java 3.22.3 -> 3.23.4`
   - [x] `com.google.protobuf:protobuf-java-util 3.22.3 -> 3.23.4`
   - [x] `com.google.protobuf:protobuf-javalite 3.22.3 -> 3.23.4`
   - [x] `com.google.protobuf:protoc 3.22.3 -> 3.23.4`
- [x] Errorprone
   - [x] `com.google.errorprone:error_prone_annotations 2.18.0 -> 2.20.0`
   - [x] `com.google.errorprone:error_prone_core 2.18.0 -> 2.20.0`
   - ~`libs.checkstylejava8 = com.puppycrawl.tools:checkstyle 9.3 -> 10.12.1`~ -- pinned to last version supporting java8, update not needed

#### Updated to non-latest
- [x] `com.squareup.okio:okio 1.17.5 ->` ~`3.4.0`~ `2.10.0` -- updating to 3.x failed due to them [introducing gradle multiplatform artifacts](https://github.com/square/okio/blob/master/CHANGELOG.md#version-320). Error in [the comment below](https://github.com/grpc/grpc-java/pull/10359#issuecomment-1632853307.).
- [x] `org.checkerframework:checker-qual 3.33.0 ->` ~`3.36.0`~ -- removed, no longer needed
- [x] Mockito - updated to `4.11.0`. Versions 5.x break some tests. Errors in [the comment below](https://github.com/grpc/grpc-java/pull/10359#issuecomment-1632834435).
   - `org.mockito:mockito-android 3.12.4 ->` ~`5.4.0`~ `4.11.0`
   - `org.mockito:mockito-core 3.12.4 ->` ~`5.4.0`~ `4.11.0`

#### Not updated
- Cronet -- upgrade failed, created a blocker ticket https://github.com/grpc/grpc-java/issues/10396
   - ~`org.chromium.net:cronet-api 108.5359.79 -> 113.5672.61`~
   - ~`org.chromium.net:cronet-embedded 108.5359.79 -> 113.5672.61`~
- Google auth -- upgrade blocked by https://github.com/grpc/grpc-java/pull/9118
   - ~`com.google.auth:google-auth-library-credentials 1.4.0 -> 1.19.0`~
   - ~`com.google.auth:google-auth-library-oauth2-http 1.4.0 -> 1.19.0`~
- Guava -- not upgraded: 32.1.0 [broke gradle modules](https://github.com/google/guava/releases/tag/v32.1.0)
   - ~`libs.guava = com.google.guava:guava 32.0.1-android -> 32.1.1-jre`~
   - ~`libs.guava.jre = com.google.guava:guava 32.0.1-jre -> 32.1.1-jre`~
   - ~`libs.guava.testlib = com.google.guava:guava-testlib 32.0.1-android -> 32.1.1-jre`~


### checkForUpdates results
```
> Task :checkForUpdates
androidx.core:core 1.10.0 -> 1.10.1
com.google.auto.value:auto-value 1.10.1 -> 1.10.2
com.google.auto.value:auto-value-annotations 1.10.1 -> 1.10.2
org.checkerframework:checker-qual 3.33.0 -> 3.36.0
com.puppycrawl.tools:checkstyle 8.28 -> 10.12.1
org.chromium.net:cronet-api 108.5359.79 -> 113.5672.61
org.chromium.net:cronet-embedded 108.5359.79 -> 113.5672.61
com.google.errorprone:error_prone_annotations 2.18.0 -> 2.20.0
com.google.errorprone:error_prone_core 2.18.0 -> 2.20.0
com.google.errorprone:error_prone_core 2.10.0 -> 2.20.0
com.google.api.grpc:proto-google-common-protos 2.17.0 -> 2.22.0
com.google.auth:google-auth-library-credentials 1.4.0 -> 1.19.0
com.google.auth:google-auth-library-oauth2-http 1.4.0 -> 1.19.0
com.google.cloud:google-cloud-logging 3.14.5 -> 3.15.5
com.google.guava:guava 32.0.1-android -> 32.1.1-jre
com.google.guava:guava 32.0.1-jre -> 32.1.1-jre
com.google.guava:guava-testlib 32.0.1-android -> 32.1.1-jre
org.mockito:mockito-android 3.12.4 -> 5.4.0
org.mockito:mockito-core 3.12.4 -> 5.4.0
com.squareup.okio:okio 1.17.5 -> 3.4.0
com.google.protobuf:protobuf-java 3.22.3 -> 3.23.4
com.google.protobuf:protobuf-java-util 3.22.3 -> 3.23.4
com.google.protobuf:protobuf-javalite 3.22.3 -> 3.23.4
com.google.protobuf:protoc 3.22.3 -> 3.23.4
org.robolectric:robolectric 4.9.2 -> 4.10.3
com.google.truth:truth 1.0.1 -> 1.1.5
```
2023-07-21 10:15:05 -07:00
Larry Safran 9f78b2bd3c
Revert "Change the default for staleAge to be maxAge - 1 minute rather than maxage (unless maxAge is < 2 minutes) for the RLS configuration from proto. (#10397)" (#10399)
This reverts commit 56d1c42c80.
2023-07-20 15:32:35 -07:00
Larry Safran 864d30caed
Handle header with errors and endStream = true (#10384)
* Eliminate NPE by skipping further processing when stream is defined, but doesn't have a property for streamKey (header processing identified an error)

Fixes #10364

* Add unit test for missing content type
2023-07-20 15:31:46 -07:00
Larry Safran 56d1c42c80
Change the default for staleAge to be maxAge - 1 minute rather than maxage (unless maxAge is < 2 minutes) for the RLS configuration from proto. (#10397) 2023-07-20 10:43:08 -07:00
sanjaypujare dea7fa09ff
core, services, util: export util from core and move gson dep to services for the checkUpperBoundDeps error (#10390) 2023-07-20 10:20:10 -07:00
Eric Anderson 3f60746a98
servlet: Remove unused dependency on grpc-util in tests
Also convert to testFixtures, like we did elsewhere.

grpc-testing had previously been listed, but because of the missing
comma, it was not an actual dependency.
2023-07-20 07:57:11 -07:00
Eric Anderson b526a68622 Restrict checkUpperBoundDeps to library dependencies
Guava 32.1.0 added Gradle Module Metadata to their artifact (they still
use Maven for their build). Because of that, we're now seeing less
normal dependencies that were confusing checkUpperBoundDeps.  Obviously
'null' is not the version we were looking for.

We aren't upgrading to Guava 32.1.x yet as there's still other problems.

```
Execution failed for task ':grpc-census:checkUpperBoundDeps'.
> Maven version skew: com.google.guava:guava-parent (32.1.1-jre != null) Bad version dependency path: [project ':grpc-census', com.google.guava:guava:32.1.1-android] Run './gradlew :grpc-census:dependencies --configuration runtimeClasspath' to diagnose
```
2023-07-19 17:17:05 -07:00
Sergii Tkachenko e3016cf7f0
Stabilize setExtensionRegistry() of ProtoLiteUtils and ProtoUtils (#10392)
Closes #1787
2023-07-19 15:38:42 -07:00
Sergii Tkachenko 313c343729
Stabilize setMessageCompression() (#10393)
Closes #1703
2023-07-19 15:38:32 -07:00
Eric Anderson fefbd12c7e Remove unnecessary thisUsesUnstableApi from CallCredentials impls
This method has been unnecessary/deprecated since dd2dc21d.
2023-07-18 13:38:24 -07:00
Eric Anderson e8f36fa522 all: Remove grpc-context from grpc-all
grpc-context is empty, so isn't needed. Including it also causes the
warning:
```
> Task :grpc-all:javadoc
Resolution of the configuration :grpc-context:compileClasspath was attempted from a context different than the project context. Have a look at the documentation to understand why this is a problem and how it can be resolved. This behaviour has been deprecated and is scheduled to be removed in Gradle 8.0. See https://docs.gradle.org/7.6/userguide/viewing_debugging_dependencies.html#sub:resolving-unsafe-configuration-resolution-errors for more details.
```
2023-07-18 11:20:18 -07:00
sanjaypujare 0f5f07f876
core, inprocess, util: move inprocess and util code into their own new artifacts grpc-inprocess and grpc-util (#10362)
* core, inprocess, util: move inprocess and util code into their own new artifacts grpc-inprocess and grpc-util
2023-07-17 11:45:31 -07:00
Anirudh Ramachandra ac35ab67f2
xds: Encode the service authority in XdsNameResolver (#10207)
Encode the service authority before passing it into gRPC util in the xDS name resolver to handle xDS requests which might contain multiple slashes. Example: xds:///path/to/service:port.

As currently the underlying Java URI library does not break the encoded authority into host/port correctly simplify the check to just look for '@' as we are only interested in checking for user info to validate the authority for HTTP.

This change also leads to few changes in unit tests that relied on this check for invalid authorities which now will be considered valid.

Just like #9376, depending on Guava packages such as URLEscapers or PercentEscapers leads to internal failures(Ex: Unresolvable reference to com.google.common.escape.Escaper from io.grpc.internal.GrpcUtil). To avoid these issues create an in house version that is heavily inspired by grpc-go/grpc.
2023-07-14 12:54:18 -07:00
Larry Safran 0aaa2e0434
Bump version (#10378)
* Start 1.58.0 development cycle
2023-07-13 13:06:21 -07:00
Tony An 37351c690c
fixed StaticStrideScheduler looping too many times (#10370) 2023-07-13 10:24:07 -07:00
Terry Wilson 78cf1c39cf
core: Apply RetryingNameResolver in ManagedChannelImpl (#10371)
Wrapping the DnsNameResolver in DnsNameResolverProvider can cause
problems to external name resolvers that delegate to a DnsResolver
already wrapped in RetryingNameResolver. ManagedChannelImpl would
end up wrapping these name resolvers again, causing an exception
later from a RetryingNameResolver safeguard that checks for double
wrapping.
2023-07-12 10:14:50 -07:00
Daniel Liu 4fa2814d65
services, xds, orca: LRS named metrics support (#10282)
Implements gRFC A64: xDS LRS Custom Metrics Support
2023-07-11 13:29:31 -07:00
Larry Safran 8dbd47ceb5
Sort the policies in a rule by policy name when parsing from proto. (#10334)
* Sort the policies in a rule by policy name when parsing from proto.  This fixes the server sending a GOAWAY when an LDS update with no changes other than ordering is received.

* Remove use of deprecated method setSourceIp

* Fix style issues

* Update RbacFilterTest.java
2023-07-10 11:07:54 -07:00
Masakuni Oishi 68e29922cf
CheckedForwardingClientCall should pass trailers from the caught exception (#10356)
`StatusException` thrown from `checkedStart()` may have `trailers`. Therefore, `CheckedForwardingClientCall` should pass the `trailers` to `responseListener.onClose()`.
2023-07-10 10:00:10 -07:00
Eric Anderson 1af6b24a7c Add commit convenience
Co-authored-by: Sergii Tkachenko <hi@sergii.org>
2023-07-07 16:01:21 -07:00
Eric Anderson 13ca4d5f77 RELEASING.md: Reorder contents to make it a bit more streamlined
I moved items that could be done immediately after the release up into
the main release flow. I also stripped some outdated or unnecessary text
to make it quicker to follow.
2023-07-07 16:01:21 -07:00
Eric Anderson 75c9daf4a1 build.gradle: Avoid assignment to japicmp configuration
Instead of assignment, it now seems to be a FileCollection that you
modify. This has probably been broken since f458f22.

```
> Could not create task ':grpc-auth:japicmp'.
   > Cannot set the value of read-only property 'oldClasspath' for task ':grpc-auth:japicmp' of type me.champeau.gradle.japicmp.JapicmpTask.
```

The change works with or without the files(), but the conversion is just
not needed anymore as it is handled by FileCollection.
2023-07-07 14:34:20 -07:00
Stephane Landelle 1e30cb6601
core,grpclb: Resolve isAndroid only once on class loading (#10345)
Motivation:

When multiple NameResolvers are created, the Classloader is scanned every time trying to figure out if the Platform is Android. This expensive work could be done only once.

Modification:

Cache isAndroid resolution in a constant.

Result:

Less expensive multiple NameResolvers instantiation.
2023-07-06 13:42:43 -07:00
Tony An 0b53dd7304
implemented and tested static stride scheduler for weighted round robin load balancing policy (#10272) 2023-07-06 10:03:08 -07:00
Eric Anderson 361616ae7c Upgrade Netty to 4.1.94-Final 2023-07-06 08:46:45 -07:00
sanjaypujare 2be568d70b
core: stabilize MutableHandlerRegistry by removing ExperimentalApi annotation (#10348) 2023-07-05 16:07:37 -07:00
Larry Safran ed4cc896fc
require EDS service name in CDS resources with xdstp name (#10329)
* require EDS service name in CDS resources with xdstp name
2023-06-30 13:51:46 -07:00
sanjaypujare 1a9c2a0dac
api, context: fix bazel build: export api from context and remove context dep from api (#10326) 2023-06-29 13:51:13 -07:00
Terry Wilson 8192ff6103
core: ManagedChannelImpl to always use RetryingNameResolver (#10328)
ManagedCahnnelImpl did not make sure to use a RetryingNameResolver if
authority was not overriden. This was not a problem for DNS name
resolution as the DNS name resolver factory explicitly returns a
RetryingNameResolver. For polling name resolvers that do not do this in
their factories (like the grpclb name resolver) this meant not having retry
at all.
2023-06-29 13:47:23 -07:00
Eric Anderson 443a0502ba Remove old Protobuf Gradle Plugin caching workaround
This has been fixed in the Protobuf Gradle Plugin since probably 0.8.13.
2023-06-29 12:50:01 -07:00
Eric Anderson 5a0fccfae0
Rebuild Android generated code for java.lang.String (#10327)
3808e707 fixed references of String to be java.lang.String, but failed
to update the Android build.
2023-06-29 12:47:44 -07:00
Terry Wilson 3b40b22348
api: Stabilize two io.grpc.Status methods (#10322)
This stabilizes:
 - Status.asRuntimeException(Metadata)
 - Status.trailersFromThrowable(Throwable)
2023-06-29 11:58:15 -07:00
Philip K. Warren 3808e707f9
compiler: Use fully qualified String in codegen (#10321)
Currently, the gRPC compiler isn't properly using the fully qualified
string name `java.lang.String` instead of `String`. Update the generator
to use the `$String$` alias to avoid compile issues with protobuf
messages called String.

Fixes #10316.
2023-06-29 10:50:13 -07:00
Eric Anderson f902e16d3d compiler: Don't mention C++ Protobuf version in build message
There's been minor version skew between Java and C++ many times because
certain releases are one-language-only. And now we have more severe
skew, where we can't readily upgrade to newer C++ Protobuf versions
because of build complexity. Let's just remove the version, and have the
canonical C++ Protobuf version live in COMPILING.md.

See #10317
2023-06-29 06:15:22 -07:00
wwtbuaa01 5799febde0
Add UserHandle and BinderChannelCredentials to BinderChannelBuilder to support cross-user communication through OnDeviceServer. (#10197)
Add UserHandle and BinderChannelCredentials to BinderChannelBuilder to support cross-user ondevice server.
2023-06-29 13:01:13 +02:00
sanjaypujare 4d2c3aac0e
context, all: move Context classes to grpc-api (#10313)
* context, all: move Context classes to grpc-api
clean up grpc-context since it has no source code: only add dep on grpc-api
add exclusion for all transitive deps of grpc-api - only guava
exclude grpc-context as a dependency from grpc-alts because all context code is in grpc-api now
api: 1.7 as target Java version for Context source-set of grpc-api

* core, census: fix the issues with android project pulling in old grpc-context version


* api,context: make changes to bazel build files to account for context code moving from context to api
2023-06-28 18:28:30 -07:00
Eric Anderson d654707838
buildscripts: Build Android with main build in linux_artifacts
Note that this changes the JDK used to compile releases to Java 11. That
should only impact the appearance of the Javadoc.

This adds the Android SDK to the build container, removing the
dependency on the Android SDK being available on the CI host. This
allows running on newer Kokoro images. 'Android' and 'Android interop'
CIs still depend on the Android SDK being available on the host, but
since they aren't used as part of the release process, they can more
easily migrate off Kokoro as part of future work.

This also causes Android components to now be built with -Werror, as we
use -PfailOnWarnings=true in unix.sh but were missing it from the
Android build invocations.

Gradle will auto-download the necessary version of build-tools. We don't
want to download it ourselves because the version we specify might not
even be used. Looking at logs, we were previously downloading a version
that was unused.

We now fork javac to avoid OOM. The build fails 2/3 times before the
forking, and 0/3 after.
2023-06-28 16:24:21 -07:00
Eric Anderson b2327238c5 xds: Include third_party sources is sources jar 2023-06-27 09:48:54 -07:00
Terry Wilson f3399e3d0e
android-interop-testing: Use java.util.concurrent (#10312)
Instead of the deprecated Android AsyncTask, let's use the standard
Java concurrency library with a Callable and an ExecutorService.
2023-06-26 13:32:05 -07:00
Eric Anderson ac8908ec7f xds: Plumb thirdparty classes through sourceSet instead of jar
Plumbing through sourceSet lets cross-project dependencies work the same
way as artifacts published to Maven. This fixes an issue for
interop-testing where build/install would include all the raw files from
thirdparty in addition to the grpc-xds.jar. For example:
build/install/grpc-interop-testing/lib/com/github/xds/data/orca/v3/OrcaLoadReport$1.class

b/288577812
2023-06-23 13:27:29 -07:00
Eric Anderson f46793e82d Remove unneeded dependency excludes
Since 44847bf4e, when we upgraded our JUnit version, the JUnit
exclusions have probably not been necessary. e0ac97c4f upgraded
Robolectric to a version that had the auto.service problem fixed.
2023-06-23 11:18:10 -07:00
Eric Anderson 0e6c01837c buildscripts: Fix prepare_qemu to not assume system already has emulation
Apparently our Kokoro image has this done already, and my laptop as
well. But the newer Kokoro image and other computers like my desktop
don't have it already.
2023-06-23 10:24:25 -07:00
Xuan Wang 1c9ce5d76b
[PSM interop] Don't fail url_map target if sub-target already failed (#10295) 2023-06-22 15:42:21 -07:00
Tony An 2effae6249
okhttp: tsan socket data race bug fix (#10279)
replaced use of bareSocket with a synchronized socket, added additional lock to synchronize initialization with shutdown() to fix a Java bug
2023-06-22 10:46:34 -07:00
Larry Safran f1de820c19
Change delay for hedging retry after a non-fatal error to be 0 to match the gRFC A6. (#10293)
Fixes #10145
2023-06-21 14:53:02 -07:00
Terry Wilson 31321562ee
xds: Use Rule order instead of RuleChain (#10289)
This is now the preferred way to specify rule execution order.
2023-06-16 13:39:47 -07:00
Terry Wilson 48192db68e
netty: Nix InternalNettyServerBuilder unused methods (#10287) 2023-06-15 15:03:05 -07:00
Eric Anderson d28e5f0fc5 buildscripts: Fail sonatype-upload for non-200 HTTP status code 2023-06-15 13:35:00 -07:00
Larry Safran 99392004a0
Handle Aggregate cluster loops and dups (#10274)
* Suppress duplicate children and NACK if detect loops (child is an ancestors of the current CDS aggregate).  

* Handle diamond shaped aggregations (same cluster appears under 2 distinct parents that doesn't create a loop).
2023-06-15 10:24:23 -07:00
Eric Anderson d4e26cc689 okhttp: Use a real socket during server transport testing
The PipeSocket was convenient and avoided real I/O, but the
shutdown/close while connecting/handshaking tests were triggering a
Socket bug in Java (https://bugs.openjdk.org/browse/JDK-8278326). Using
a real socket doesn't trigger the bug because the test stops sharing
state with the code under test.

Fixes #10228

```
Details
==================
WARNING: ThreadSanitizer: data race (pid=4528)
  Write of size 1 at 0x0000cfb9d5f4 by thread T36 (mutexes: write M0):
    #0 java.net.Socket.setCreated()V Socket.java:687
    #1 java.net.AbstractPlainSocketImpl.create(Z)V AbstractPlainSocketImpl.java:149
    #2 java.net.Socket.createImpl(Z)V Socket.java:477
    #3 java.net.Socket.getImpl()Ljava/net/SocketImpl; Socket.java:540
    #4 java.net.Socket.setTcpNoDelay(Z)V Socket.java:998
    #5 io.grpc.okhttp.OkHttpServerTransport.startIo(Lio/grpc/internal/SerializingExecutor;)V OkHttpServerTransport.java:164
    #6 io.grpc.okhttp.OkHttpServerTransport.lambda$start$0(Lio/grpc/internal/SerializingExecutor;)V OkHttpServerTransport.java:159
    #7 io.grpc.okhttp.OkHttpServerTransport$$Lambda$56.run()V ??
    #8 io.grpc.internal.SerializingExecutor.run()V SerializingExecutor.java:133
    #9 java.util.concurrent.ThreadPoolExecutor.runWorker(Ljava/util/concurrent/ThreadPoolExecutor$Worker;)V ThreadPoolExecutor.java:1130
    #10 java.util.concurrent.ThreadPoolExecutor$Worker.run()V ThreadPoolExecutor.java:630
    #11 java.lang.Thread.run()V Thread.java:830
    #12 (Generated Stub) <null>

  Previous read of size 1 at 0x0000cfb9d5f4 by thread T35 (mutexes: write M1, write M2):
    #0 java.net.Socket.close()V Socket.java:1512
    #1 io.grpc.okhttp.OkHttpServerTransportTest$PipeSocket.close()V OkHttpServerTransportTest.java:1384
    #2 io.grpc.okhttp.OkHttpServerTransportTest.clientCloseDuringHandshake()V OkHttpServerTransportTest.java:290
```
2023-06-15 09:59:05 -07:00
Sergii Tkachenko 4d3a29b2af
Update README etc to reference 1.56.0 (#10283)
com.google.protobuf:protoc updated from 3.21.7 to 3.22.3.
2023-06-14 16:18:55 -07:00
Benjamin Peterson 9148095df4 netty: simplify SendGrpcFrameCommand
DefaultByteBufHolder has many perfectly good implementations. It should be enought to implement the replace method.
2023-06-14 08:45:31 -07:00
Mark S. Lewis ae59afb5bf
Update guava dependency to address CVE-2023-2976 (#10249)
Explicit dependencies to keep versions in step with newer Guava
2023-06-12 12:43:35 -07:00
Eric Anderson 5754518914 Upgrade netty-tcnative to 2.0.61.Final
This updates the version of boringssl and removes the dependency on APR.
netty-tcnative 2.0.56.Final uses APR 1.7.0, so is in scope for
CVE-2021-35940, CVE-2022-28331, and CVE-2022-24963. netty-tcnative is
not actually vulnerable. The binary does not include apr_socket_sendv(),
apr_encode_*(), apr_pencode_*(), apr_decode_*(), apr_pdecode_*(). The
binary does include apr_time_exp_*() but it is unused code.
Unfortunately --gc-sections wasn't used during compilation.
apr_time_now() is used, but that just calls gettimeofday() and is not
vulnerable.

There's no panic here, but this updates netty-tcnative just a few weeks
before we would have ordinarily done so. Bumping the version makes life
easier for everyone.
2023-06-12 11:01:06 -07:00
Eric Anderson 0f2c43a8fd Download Maven from Maven Central
Maven deleted older binaries from their CDN, so the download was
failing. Maven Central seems it'll be more stable.
2023-06-09 10:32:12 -07:00
Daniel Liu 1daf0ff720
services, xds, orca: use application_utilization and fallback to cpu_utilization if unset in WRR (#10256)
Implements updates to [A51][] and [A58][].

Imported cncf/xds using import.sh script.

A51: https://github.com/grpc/proposal/pull/374
A58: https://github.com/grpc/proposal/pull/373
2023-06-08 16:03:50 -07:00
Eric Anderson 33a402d924 Avoid NettyServerBuilder when unnecessary
These code locations just needed a generic gRPC server, without any
transport-specific configuration. Use vanilla ManagedServerBuilder
instead of hard-coding to Netty, as we would suggest to our users.
2023-06-05 17:11:16 -07:00
Larry Safran 217103cd5e
Flip default for RLS on XDS being enabled to true. (#10248) 2023-06-05 15:49:30 -07:00
sanjaypujare 6949b8790a
api: stabilize ManagedChannelBuilder.useTransportSecurity (#10244)
* api: stabilize ManagedChannelBuilder.useTransportSecurity and add a note in Java doc
2023-06-02 15:08:25 -07:00
sanjaypujare 639fd8edf2
xds: remove env var for security enable/disable (#10243) 2023-06-02 09:24:51 -07:00
Xuan Wang 02ac6f4393
buildscripts, psm interop: Don't fail target if sub-target already failed
We configured TestGrid to file bug separately for each 
failed sub-target, if we still fail the main target, 
TestGrid will fail duplicate bugs.

The same change in core: 
https://github.com/grpc/grpc/pull/33222.
2023-05-31 17:37:46 -07:00
Sergii Tkachenko 17b2df78ec
Start 1.57.0 development cycle (#10229) 2023-05-30 18:02:40 -07:00
kotlaja e6d9b41895
bazel: Add java toolchain type to all rules which are using java_common (#10225) 2023-05-30 11:48:43 -07:00
Stanley Cheung 4277867a7d
gcp observability: Update Docker images to eclipse-temurin (#10218)
Perform software update so that we install patches for latest
vulnerabilities. Similar to the fix in #10191
2023-05-30 08:03:36 -07:00
Larry Safran df85a45742
Add a java specific description of manual flow control to the example. (#10223)
* Add a java specific description of manual flow control to the example.
2023-05-26 18:36:40 -07:00
Daniel Liu 5a27e3ead2
services, xds, orca: support EPS in client-side WRR (#10177) 2023-05-26 12:52:42 -07:00
Michael Vorburger ⛑️ 6aa72b786d
docs: Document use with Bazel, like Maven & Gradle (fixes #10215) (#10217)
* docs: Document use with Bazel, like Maven & Gradle (fixes #10215)
2023-05-26 12:42:50 -07:00
apolcyn b77f0a022f
interop-testing: introduce --additional_metadata flag to let client optionally send extra metadata (#10201)
The flag was documented in https://github.com/grpc/grpc/pull/33180 .
This flag will be useful for some RLS integration tests where we need
to have the client set certain headers for routing purposes.
2023-05-26 06:45:50 -07:00
Eric Anderson f75c7c72f2 repositories.bzl: In doc, use | to combine dicts
The previous syntax for just adding your own keys doesn't seem to work,
but was similar to the approach of using `dict(d, foo=bar)`. You can't
have '.' and ':' in a key that way though. The doc was written before
Bazel 1.0 and in newer Bazel versions you can just use | to concatenate.

Fixes #10203
2023-05-25 15:26:43 -07:00
Eric Anderson 7217baa777 Remove old Java 7/8 TLS testing workarounds
Ciphers have been "fast enough" for testing since early Java 8 updates;
we haven't needed to override ciphers since we dropped Java 7 support.
Java 8u252 had ALPN, so Conscrypt or Jetty ALPN hasn't been necessary
for basic testing for a while. We still want specialized testing for
Conscrypt, but only tests testing Conscrypt need to care.
2023-05-25 14:04:01 -07:00
Eric Anderson cb42405217 testing: Move some internal classes to testFixtures
These two classes are precisely the purpose of test fixtures. Move them
close to the classes they make easier to use in tests.
2023-05-25 14:03:42 -07:00
sanjaypujare 3b2cba09c1
api: remove experimentalApi setting from proxyDetector and related classes (#10216) 2023-05-25 13:46:24 -07:00
sanjaypujare e875d1b01c
xds: remove remaining occurences of SDS in the security code (#10219) 2023-05-25 10:28:37 -07:00
Terry Wilson e172ea7efc
api: Experimental CallCredentials.thisUsesUnstableApi() (#10211)
The thisUsesUnstableApi() method was earlier deprecated and the
@ExperimentalApi annotation removed. Adding @ExperimentalApi back
to make it clear that this method can (and will) later be removed.
2023-05-23 08:32:33 -07:00
Terry Wilson dd2dc21de2
api: Stabilize io.grpc.CallCredentials (#10208) 2023-05-22 09:59:53 -07:00
Liam Miller-Cushon 478f30e645 testing-proto: Define supported SourceVersion in annotation test
This fixes the warning during the test run:
```
warning: No SupportedSourceVersion annotation found on io.grpc.testing.protobuf.SimpleServiceTest$AnnotationProcessor, returning RELEASE_6.
warning: Supported source version 'RELEASE_6' from annotation processor 'io.grpc.testing.protobuf.SimpleServiceTest$AnnotationProcessor' less than -source '1.8'
```
2023-05-18 11:01:39 -07:00
Kun Zhang 6fd93486cc
test: stop mocking Executor. (#10199)
It is forbidden internally. Error message:

Mocking types which have complex contracts or are easy to construct by
other means is forbidden:

'executor' is mocking 'interface java.util.concurrent.Executor'. Use a
real executor. Mocks of Executor don't execute submitted tasks at all,
which leads to suppressed errors, deadlocks, and brittle tests..
2023-05-17 16:40:32 -07:00
Terry Wilson 5d40396aa2
A note to include backports in release notes (#10198) 2023-05-17 11:36:01 -07:00
Terry Wilson 810d8cab09
xds: pick_first LB configuration (#10181)
Configure pick_first load balancing if the xDS PickFirst LB config
message is used in the Cluster load balancing config.
2023-05-17 10:19:29 -07:00
Eric Anderson e0ac97c4fd
Upgrade dependencies (#10178)
Required bumping android compile/targetSdkVersion to 33
2023-05-17 08:32:49 -07:00
Eric Anderson e38d928f75 examples: Fix hostname binary name in README
The command has been wrong since it was introduced. The hostname-server
comes from the applicationName, which hasn't changed.
2023-05-16 15:44:09 -07:00
Sergii Tkachenko 16b84924a1
xds interop: Update Docker images to `eclipse-temurin:11-jre` (#10172)
- Update to xDS Test Client and xDS test server Docker images to `eclipse-temurin:11-jre`. 
- Perform software update so that we install patches for latest vulnerabilities.
2023-05-16 15:20:55 -07:00
Eric Anderson 29b8483fd6
Use test fixtures instead of sourceSets.test.output
This avoids the (often missing) evaluationDependsOn and fixes using
results from other projects without propagating those through
Configuration. It also reduces the number of useless classes pulled in
by down-stream tests, reducing the probability of rebuilds.

The expectation of fixtures is they help testing down-stream code that
use the classes in main. That applies to all the classes here except for
FakeClock and StaticTestingClassLoader. It would also apply to many
internal classes in grpc-testing, but let's consider cleaning that up
future work.
2023-05-16 12:10:13 -07:00
Eric Anderson cd7b81c6d2 gradle: Assocate an artifact to every version
This allows the checkForUpdates task to look for newer versions.
2023-05-15 14:01:41 -07:00
Eric Anderson 2cc24a9bda gradle: Remove version pinning from POMs
The pinning is unreliable in Maven and ignored by Gradle. I'm not at all
convinced that we are pinning/not pinning in appropriate projects. The
pinning also serves less of a purpose since we started encouraging the
BOM and grpc-netty-shaded. Netty's HTTP/2 API has also become somewhat
stable compared to its earlier history. If we notice an up-tick in
version skew, we can reinstate it.

The pinning is annoying in the build.gradle code and causes Maven/Gradle
to download the version list once a day, which can be troublesome to
users unaware of how to tell the tools to work offline.

It also opens our users to platform issues like seen in #10043
and #10086 where Maven Central's version list was incorrectly generated.
Or like #9664 where Gradle Plugin's repository caches packages from
JCenter but the version list is not as cachable so exposed us to JCenter
instability.

This fixes #8357, by way of "we think we won't worry any more." See
90db93b9 when it was originally introduced. And issues
like #8337, #3634.
2023-05-15 13:08:40 -07:00
Terry Wilson 793fde840a
xds: Import latest Envoy protos (#10167) 2023-05-11 09:44:43 -07:00
Eric Anderson c16972c54a build.gradle: Add checkForUpdates task 2023-05-10 12:44:35 -07:00
Eric Anderson 3f0e90d54e build.gradle: Use proto task output instead of hard-coding path
This removes the need to specify dependsOn explicitly, because the task
input carries the dependency.
2023-05-10 12:44:10 -07:00
Daniel Liu 6e486cba48
import cncf/xds using import.sh script (#10160) 2023-05-10 12:42:26 -07:00
Eric Anderson 02a4cb5c69 Fix throwing LBProvider.parseLoadBalancingConfig() impls
LoadBalancers in general should never throw, but
parseLoadBalancingConfig() in particular has a return value to
communicate the error. Throwing can be a bit unpredictable, but at its
most trivial form causes a channel panic. There's no reason to throw
explicitly and calls to JsonUtil have to be protected by a try-catch
because it can throw.
2023-05-10 12:42:05 -07:00
yifeizhuang 6f804331f7
xds: remove _experimental in wrr policy name (#10162) 2023-05-10 11:02:13 -07:00
Eric Anderson 74b515ecf7 Migrate many usages of TestUtils.loadCert() to the public TlsTesting
TlsTesting.loadCert() is a public API and so should be preferred over
our internal utility. It avoids creating a temp file that has to be
deleted by a shutdown hook. Usages that needed a file were not migrated.
2023-05-09 17:01:31 -07:00
Eric Anderson f229aed538 core: Hide RR's ReadyPicker and EmptyPicker
ReadyPicker hasn't been necessary since 111ff60e, when we stopped
calling super.pickSubchannel(). EmptyPicker was only used in tests, and
we can just compare the class name instead of doing an instanceof check.

Unfortunately, calling getClass() caused Java to start casting the
return value of pickerCaptor.getValue() based on its generics. Captors
don't verify the type they capture, so using any type other than
SubchannelPicker for the pickerCaptor is misleading and hides a cast.
2023-05-09 13:25:19 -07:00
Terry Wilson 86f7bca5f9
api: Fix boundary check in Status.fromCodeValue() (#10155) 2023-05-09 09:02:56 -07:00
Eric Anderson b4f4142e8d RELEASING.md: Include version number in release branch name
This makes it easier to manage multiple patch releases in-flight
simultaneously and improves the default PR description.
2023-05-09 08:12:27 -07:00
Eric Anderson 847ea7cfc9 Upgrade Mockito to 3.12.4
MockitoAnnotations.initMocks() is deprecated.
2023-05-08 16:39:42 -07:00
Eric Anderson 8dbc88f3a3
gradle: Improve compatibility with Gradle 8 2023-05-08 10:46:10 -07:00
Eric Anderson f458f229c6
gradle: Update plugins 2023-05-08 10:45:13 -07:00
Eric Anderson 29c2de0d42 okhttp: Fix signed-byte comparison 2023-05-08 10:43:49 -07:00
Eric Anderson 424ddcee8d compiler: configureEach instead of each+configure
each+configure serves no purpose, because the task has already been
realized with the each. This was just a faulty conversion in 0ff9f37b9e,
although it was because I thought the each was specialized API from the
protobuf plugin, not the normal container each.
2023-05-08 10:37:57 -07:00
Eric Anderson 180b3e9092 xds: Avoid default locale and reset()
Found via linter
2023-05-05 15:23:18 -07:00
Eric Anderson 22366891de
binder: Use Channel-based blockingUnaryCall()
The Channel-based overload can change the CallOptions to use
ThreadlessExecutor, so avoids using extra threads.
2023-05-05 15:22:54 -07:00
Terry Wilson 0005029328
android,binder,cronet: .aar file when publishing (#10138) 2023-05-05 15:21:26 -07:00
Eric Anderson 94dec7c020 xds: Avoid WRR config synchronization 2023-05-05 14:43:26 -07:00
yifeizhuang 5a121ebb83
binder: fix test error prone (#10132) 2023-05-05 10:55:58 -07:00
Eric Anderson e560c6206c gcp-observability: Avoid non-shadow configurations of xds, alts, netty
We have two versions of multiple projects, the non-shadow and the
shadow. When using project() references, things are mostly fine,
although we may test with a different version than our users would use.
However, when a dependency from Maven Central depends on a grpc
artifact, it pulls in the non-shadow configuration and messes up
gradle's tracking. We shouldn't be using the non-shadow configuration,
so this issue is sort of a blessing to improve the test reliability.

Gradle 7 will notice that there's a missing dependency, but it is not
deterministic and is very slow to test. Starting in Gradle 8 it is much
more reliably triggered which greatly helped the testing efforts. The
error in Gradle 7 looks like:
```
> Task :grpc-gcp-observability:interop:startScripts
Execution optimizations have been disabled for task ':grpc-gcp-observability:interop:startScripts' to ensure correctness due to the following reasons:
  - Gradle detected a problem with the following location: 'grpc-java/netty/shaded/build/libs/grpc-netty-shaded-1.54.0-SNAPSHOT-original.jar'. Reason: Task ':grpc-gcp-observability:interop:startScripts' uses this output of task ':grpc-netty-shaded:jar' without declaring an explicit or implicit dependency. This can lead to incorrect results being produced, depending on what order the tasks are executed. Please refer to https://docs.gradle.org/7.6/userguide/validation_problems.html#implicit_dependency for more details about this problem.
```

Fixes #9992
2023-05-05 09:01:17 -07:00
Eric Anderson 0bef2b2ef3 interop-testing: Stop using Shadow Gradle Plugin
This essentially reverts 3624d59b. In 6609f11f we removed the reference
to OrcaLoadReport, which meant shadow has no longer been necessary.
2023-05-05 09:00:46 -07:00
Terry Wilson 21ff7a010a
api: Stabilize the SynchronixationContext class (#10130) 2023-05-04 11:27:35 -07:00
Terry Wilson b5800edd76
Importing latest xDS protos from envoyproxy/envoy (#10123) 2023-05-03 11:57:52 -07:00
sanjaypujare f24a5a7d0d
xds: handle the handlerRemoved callback to skip updateSslContext processing (#10118)
* xds: handle the handlerRemoved callback to skip updateSslContext processing
     In handlerAdded we submit a callback to updateSslContext but before the
     callback is executed the handler could be removed (e.g. bad connection)
     in which case the callback should skip all of the processing.
     Also added a unit test to check there is no exception.
2023-05-03 07:41:15 -07:00
Eric Anderson 545e982afd googleapis: Enable ignore_resource_deletion in bootstrap 2023-05-02 15:16:33 -07:00
Eric Anderson 95207d2ac2 examples: Add missing start scripts for JSON example 2023-05-02 15:15:54 -07:00
Kaloyan Simitchiyski 572a7af426
protobuf,protobuf-lite: configurable protobuf recursion limit (#10094) 2023-05-02 14:52:22 -07:00
Terry Wilson 3c01bfe77f
core: Optional address shuffle in PickFirstLoadBalancer (#10110)
If provided with the new PickFirstLoadBalancerConfig,
PickFirstLoadBalancer will shuffle the list of addresses it receives
from the name resolver.

PickFirstLoadBalancerProvider will now support the new config
if enabled by an env variable.
2023-04-28 15:50:18 -07:00
yifeizhuang b249a5340e
services: allow cpu utilization greater than 1 (#10107) 2023-04-28 11:59:10 -07:00
yifeizhuang fe53346697
xds: fix flaky xds test (#10109) 2023-04-28 11:17:49 -07:00
Terry Wilson fbc8679f7a
core: Sticky TRANSIENT_FAILURE in PickFirstLoadBalancer (#10106)
When the subchannel is transitioning from TRANSIENT_FAILURE to either
IDLE or CONNECTING we will not update the LB state. Additionally, if
the subchannel becomes idle we request a new connection so that the
subchannel will keep on trying to establish a connection.
2023-04-27 15:43:27 -07:00
chenwei321 c5b825aa7d
xds: fix matchRoute in RoutingUtils and clean up implementations in XdsNameResolver. (#10095) 2023-04-27 13:28:44 -07:00
Larry Safran 9d1e089c27
stub: Add null check for responseObserver (#10083)
* stub:Add null check for responseObserver

Fixes #10064
2023-04-25 13:35:39 -07:00
Larry Safran e89e0ccfee
Refactor so that calculation happens in constructor rather than checking for a null value to lazily initialize it. (#10101)
Fixes b/277276312
2023-04-25 10:26:13 -07:00
yifeizhuang c4c9939887
xds: enable wrr env variable (#10100) 2023-04-25 10:15:24 -07:00
John Cormie 87fe41046a
Handle unexpected exceptions on binder threads (#10092)
All BinderTransport transactions are oneway which means uncaught
Exceptions during processing are merely logged locally and not
propagated to the peer. Instead, we add a top level catch block
that handles the unexpected by shutting down the whole transport. This
makes our peer aware of the problem immediately (instead of relying on a
deadline) and gives clients a fresh transport instance to handle any
retries.
2023-04-25 09:11:06 -07:00
Terry Wilson a384c16e8c
xds,googleapis: Default GRPC_EXPERIMENTAL_XDS_FEDERATION to true (#10093) 2023-04-24 11:01:32 -07:00
Terry Wilson 68b67b616e
xds: Allow child of cluster_impl LB to change (#10091)
Under normal conditions the child LB of `ClusterImplLoadBalancer` does
not fluctuate, based on the field used to configure load balancing in
the xDS `Cluster` proto it is either:

1. `WrrLocalityLoadBalancer` if the newer `load_balancing_policy` field
   is used
2. `WeightedTargetLoadBalancer` if the legacy `lb_policy` field is used

`ClusterImplLoadBalancer` currently assumes that this child does not
change and so does not change the child LB when the name resolver sends an
update. If the control plane does switch to using a different field for
LB config, that update will have an LB config meant for the other child
LB type. This will result in a ClassCastException and a channel panic.

To address this, `ClusterImplLoadBalancer` will now use
`GracefulSwitchLoadBalancer` and makes sure if the child policy changes
the correct LB implementation is switched to.
2023-04-24 11:00:56 -07:00
Eric Anderson 8ca99f661d core: Pass Locality to toLowerCase() in GrpcUtil
We pretty much never want to use the system locality, across all our
code.
2023-04-24 10:53:12 -07:00
apolcyn 708497b6ed
interop-testing: add googleapis and rls as interop client dependencies
The internal build rule for this client already adds these dependencies, and is what related tests for these dependencies have been relying on for a while.

We're starting to use the per-release published interop client docker images for those tests too now, and these use the gradle build rules.
2023-04-24 07:54:32 -07:00
Eric Anderson 27edab007d Start 1.56.0 development cycle 2023-04-21 15:56:00 -07:00
Eric Anderson 8054b20325
authz: Add missing ExperimentalApi annotation
It was missed in b43ddc28
2023-04-20 13:09:53 -07:00
Eric Anderson c35870bce0 interop-testing: Start mgmt server before xds server
The xds server can take a really long time to start if the xds resources
are slow to load. Ideally the management server would be available
during this time so we can inspect the server. The server health still
won't go to SERVING until the xds server starts, which is appropriate.
2023-04-20 11:49:17 -07:00
Larry Safran 9204223c16
alts:Remove character dropped from error message (#10068)
The DECRYPTION_FAILURE_RE matcher had an exclamation point that was dropped from the related error message between Java 11 and 19.

Fixes #10011
2023-04-20 11:05:36 -07:00
Eric Anderson 8aa25476e9
SECURITY.md: Update/modernize docs
There's still plenty more that could be done, but I want to keep this on
the simpler/less-invasive side and it'd just delay these changes for no
real benefit.
2023-04-20 08:20:52 -07:00
Eric Anderson 3c89aa191b android-interop-testing: Avoid JRE Guava from Protobuf 22.3 upgrade
This fixes the interop test on API levels 19-23
2023-04-20 06:40:12 -07:00
yifeizhuang 8b9ae27cdf
xds: remove environmental variables (#10055) 2023-04-19 17:26:26 -07:00
Eric Anderson ebc84c209f api: Stabilize Detachable and HasByteBuffer
Fixes #7387
2023-04-19 14:31:06 -07:00
Larry Safran 7255c8dfa8
retries:Remove early commit for transparent retries with none remaining. (#10066)
* retries:Remove early commit for transparent retries when no retries or no hedging remain.

Fixes #10011
2023-04-19 13:42:59 -07:00
Ashitha Santhosh b43ddc2886
authz: File Watcher Authorization Server Interceptor (#9775) 2023-04-19 10:50:19 -07:00
Sergii Tkachenko c9fcd46e84
buildscripts: increase PSM Security test timeout to 4h (#10065)
The total time PSM Security takes to run was getting close to 3h lately.
Adding an extra hour to allow for a larger margin of error.

ref b/259690410
2023-04-19 10:35:12 -07:00
yifeizhuang 111ff60e1c
xds: fix wrr stuck in rr mode (#10061) 2023-04-18 16:39:51 -07:00
Eric Anderson 35852130d9 buildscripts: Cross-compile in Docker
Previously builds were done with Ubuntu 16.04, and now we are using
18.04. Thus the generated binaries will no longer work for
Ubuntu 16.04 and Debian 9 users, both of which are outside of their
support window and aren't supported by Abseil. RHEL users are
unaffected, as the binaries already didn't work on RHEL 7 and they will
remain working with RHEL 8. FWIW, Ubuntu 18.04 will leave its support
window in June.
2023-04-18 16:16:35 -07:00
Eric Anderson 4fec5bbb83
examples: grpc-level proxy 2023-04-18 15:41:09 -07:00
Carl Mastrangelo 4e3ee4471e
all: use PerfMark.traceTask (#9950)
* all: use PerfMark.traceTask

* make linter happy
2023-04-18 10:46:54 -07:00
Eric Anderson 2e5cc84c51 examples: Reduce boilerplate and sort scripts
The point of the sorting is to reduce the chances of merge conflicts. I
greatly prefer verboseness over cleverness in examples, but the tasks
can only be sorted manually and there's so many of them.

It is counter-productive to do this for the examples that have their own
project folder, as there's so few tasks in that case that they don't
need to be ordered.
2023-04-18 09:54:22 -07:00
Eric Anderson 1551cc7403 Upgrade Protobuf Java to 3.22.3 (aka 22.3)
The version used by protoc-gen-grpc-java will be upgraded separately,
because of large C++ build changes necessary. But that won't impact
users at all. We are upgrading to protoc 22.3; only the grpc plugin is
not upgraded.

Bazel is upgraded for both Java and C++.
2023-04-17 13:16:20 -07:00
Larry Safran bcbdb205b5
Update README etc to reference 1.54.1 (#10058) 2023-04-17 13:13:04 -07:00
Terry Wilson 6e54ceb2d1
rls: Refresh name resolution on rejected addresses (#10032)
If a child load balancer rejects the addresses it if given all we can do
is to trigger a name resolution refresh and hope for a better set of
addresses.
2023-04-14 16:27:17 -07:00
Eric Anderson be2a2fc3b8 Avoid repeating grpc version in Android documentation
This removes some steps from the release process. These two locations
aren't special enough in way that deserves manually changing the version
each release.
2023-04-14 15:06:53 -07:00
yifeizhuang 14ba959545
census: add delayed name resolution tracing annotation (#10044) 2023-04-14 11:44:50 -07:00
Terry Wilson a702397903 Revert "testing: RpcBehaviorLoadBalancingProvider to use acceptResolvedAddresses() (#10030)"
This reverts commit 17e1fcb393.
2023-04-14 10:12:33 -07:00
Terry Wilson f2b976266e Revert "core: ForwardingLoadBalancer to forward acceptResolvedAddresses() (#10050)"
This reverts commit 086edf0f20.
2023-04-14 10:12:33 -07:00
Terry Wilson 086edf0f20
core: ForwardingLoadBalancer to forward acceptResolvedAddresses() (#10050) 2023-04-13 18:23:11 -07:00
Eric Anderson 445efe7423 .github/workflows: Add Bazel CI
This will replace the kokoro-based CI. We need to upgrade the image
Kokoro runs on, but it is easier to add a GitHub Actions CI than to run
a one-off test on a new image with Kokoro.

A clean run takes 10 minutes and a cached run takes 8.5. So it is a
little bit slower than the 5.5 minutes on Kokoro, but still pretty
quick.
2023-04-13 15:12:47 -07:00
Eric Anderson 9af202fbd0 .github/workflows: Fix duplicate key in testing CI
This has been broken and not running tests since d580bd3 (just a few
days ago).
2023-04-13 14:30:31 -07:00
yifeizhuang e12baed5a9
services: rename to (clear)setQpsMetric (#10031) 2023-04-11 15:18:41 -07:00
Terry Wilson 5082b4c02a
xds: Add dummy LRS service for control plane tests (#10038) 2023-04-11 13:56:08 -07:00
yifeizhuang fc4410f159
api, census: add new pendingStreamCreated on clientStreamTracer and new tracer annotation (#10014) 2023-04-11 13:49:33 -07:00
Eric Anderson 8d98e5ff7f core: Fix NPE race during hedging
The problem was one hedge was committed before another had drained
start(). This was not testable because HedgingRunnable checks whether
scheduledHedgingRef is cancelled, which is racy, but there's no way to
deterministically trigger either race.

The same problem couldn't be triggered with retries because only one
attempt will be draining at a time. Retries with cancellation also
couldn't trigger it, for the surprising reason that the noop stream used
in cancel() wasn't considered drained.

This commit marks the noop stream as drained with cancel(), which allows
memory to be garbage collected sooner and exposes the race for tests.
That then showed the stream as hanging, because inFlightSubStreams
wasn't being decremented.

Fixes #9185
2023-04-11 13:10:41 -07:00
Jeff Davidson 1c6a7412bb
Add BIND_ALLOW_ACTIVITY_STARTS to BindServiceFlags. (#10008)
This flag is added in the U SDK, which is still under development. Since it's just a numeric constant, we copy the value until it is stable and mark the API is experimental, with appropriate warnings about depending on it from production code.

A follow-up change will be made after SDK finalization to point to the official constant (or otherwise update to match any SDK changes), at which point we can remove the `@ExternalApi` annotation.

See b/274061424
2023-04-11 22:04:55 +02:00
Eric Anderson d580bd3d1c .github/workflows: Save subproject reports on test failure
There was recently a failure with the Tomcat test in servlet/jakarta:
```
io.grpc.servlet.jakarta.TomcatInteropTest > pingPong FAILED
    java.lang.AssertionError at AbstractInteropTest.java:845
        Caused by: io.grpc.StatusRuntimeException at Status.java:539
...
* What went wrong:
Execution failed for task ':grpc-servlet-jakarta:tomcat10Test'.
> There were failing tests. See the report at: file:///home/runner/work/grpc-java/grpc-java/servlet/jakarta/build/reports/tests/tomcat10Test/index.html
```

But we couldn't get more details because servlet/jakarta didn't match
the artifact glob.
2023-04-11 12:03:00 -07:00
Eric Anderson f6ddd63f09 Increase test timeouts for ARM emulation
LoadWorkerTest.runUnaryBlockingClosedLoop and Http2NettyTest.tlsInfo are
failing every CI run. It appears they are the unfortunate tests run
first, so are slowest to start as classloading proceeds. There's
definitely other tests that probably need adjustment, but fixing these
two gives us some hope of having a green run occasionally.
2023-04-10 21:57:25 -07:00
Terry Wilson 1e028c404d
xds: Wait for sync context before assertions in federation test (#10021) 2023-04-10 14:05:01 -07:00
Terry Wilson 17e1fcb393
testing: RpcBehaviorLoadBalancingProvider to use acceptResolvedAddresses() (#10030) 2023-04-10 12:52:43 -07:00
Daniel Liu 5201e49ce1
services,orca: update backend metrics support to allow for server-wide metrics recording (per-call and OOB) (#9902)
Also added input range validation.
2023-04-10 11:45:04 -07:00
Matthew Stevenson 11a1f9e3e8
alts: Enable user to configure max number of concurrent ALTS handshakes. (#10016) 2023-04-10 10:49:04 -07:00
Vindhya Ningegowda 1e1b57e15b Removes the ExperimentalApi annotation from GcpObservability. 2023-04-06 12:44:23 -07:00
DNVindhya cc6be5f8c6
gcp-o11y: Remove monitored resource detection for logging (#10020)
* removed populating monitored resource to k8s_conatiner by default for logging; Delegating the resource detection to cloud logging library instead (enabled by default)

* remove kubernetes resource detection logic from observability
2023-04-06 11:48:46 -07:00
Terry Wilson 18e274de65
xds: Synchronize access to test control plane collections (#10012)
Fixes #9938
2023-04-04 14:34:11 -07:00
Eric Anderson 4ae7370646 netty: Remove long-dead third_party reference
This was added in 9ef07916 and should have lived until we upgraded to a
newer Netty in 67eefa69.
2023-04-04 12:03:58 -07:00
Terry Wilson 6d75fca23f
xds: Distinct LoadStatManagers (#10009)
Currently the code maintains one LoadStatsManager2 that collects all
stats. The problem with this is that in a federation situation there
will be multiple LrsClients that will be periodically picking up stats
from the manager and sending them to their respective control planes.
This creates a first-come-first-serve situation where the stats get
randomly distributed across the control planes.

This change creates separate LoadStatsManagers dedicated to their own
control planes, thus assuring no stats will get lost.
2023-04-04 11:29:17 -07:00
Terry Wilson ec9b8e0d61
xds: Correctly start LRS clients in federation situations (#10000)
xds: Correctly start LRS clients in federation situations

The old code used a single member variable to indicate if load reporting
had already been started by XdsClientImpl. This boolean was used to
avoid starting a LoadReportClient more than twice. This works fine with
a single control plane server.

The problem occurs in federation situations where there is more than one
control plane and thus more than one LoadReportClient. Once the first
LoadReportClient is started, the member variable boolean is flipped to
true and no other LoadReportClients would be started.

This change removes the boolean member variable and relies on the fact
that starting an already started LoadReportClient is a no-op.
2023-04-03 18:35:48 -07:00
yifeizhuang bbe5a0227d
xds: fix flaky wrr test (#10004) 2023-04-03 09:14:44 -07:00
Larry Safran 10f5e5afd6
examples: Error details example (#9997)
* examples: Detail Error example (google.rpc.Status)
2023-03-31 16:04:27 -07:00
DNVindhya 9ea7506b2b
use glob for example file names which is used in updating release versions (#9998) 2023-03-31 10:24:05 -07:00
Larry Safran 42b4c61d5e
examples: Health example (#9991)
Provides a server with both a greet service and the health service.

   Client has an example of using the health service directly through the unary call
    <a href="https://github.com/grpc/grpc-java/blob/master/services/src/main/proto/grpc/health/v1/health.proto">check</a>
    to get the current health.  It also utilizes the health of the server's greet service
    indirectly through the round robin load balancer, which uses the streaming rpc
    <strong>watch</strong> (you can see how it is done in
    {@link  io.grpc.protobuf.services.HealthCheckingLoadBalancerFactory}).
2023-03-30 13:32:04 -07:00
Terry Wilson 8ceac65e7a
examples: custom load balancer example (#9951)
Example on how to implement a custom LoadBalancer
2023-03-28 11:51:41 -07:00
Larry Safran e0ddce8612
RELEASING.md:Addressed review comments. (#9995) 2023-03-27 18:17:13 -07:00
yifeizhuang 046e02bcdf
okhttp: forceful close after MAX_CONNECTION_AGE_GRACE_TIME (#9968) 2023-03-27 15:31:14 -07:00
Larry Safran e04c6ec9f6
examples:Client and Server sharing example (#9969)
examples:Client and server sharing example
Part of fixit.  Fixes b/259285817
2023-03-27 15:12:32 -07:00
Larry Safran 58e2224df9
Fix order dependent tests regarding message duration b/271122310 (#9930)
* Fix order dependent test by changing the initializations and comparison so that elapsed time isn't as significant in identifying whether it was the context or call option's duration that was used.

fixes b/271122310
2023-03-24 16:40:35 -07:00
Larry Safran 50a76610ee
docs:Improve instructions (#9974) 2023-03-24 16:39:55 -07:00
Terry Wilson 3d37dc4e9e
Update README etc to reference 1.54.0 (#9990) 2023-03-24 15:23:33 -07:00
Eric Anderson db433ae372
.github/workflows: Pass COVERALLS_REPO_TOKEN to coveralls task (#9935)
The coveralls task has been silently failing since we migrated to GitHub
Actions, away form Travis-CI:
```
no COVERALLS_REPO_TOKEN environmental variable found

no available CI service
> Task :grpc-all:coveralls

BUILD SUCCESSFUL in 23s
7 actionable tasks: 1 executed, 6 up-to-date
```

We'd rather not deal with private tokens, but the Coveralls GitHub
Action [only supports lcov][1] which makes it unhelpful for Java.
Looking deeper, yep, we [aren't the only ones impacted][2]:

[1]: https://github.com/marketplace/actions/coveralls-github-action
[2]: https://github.com/coverallsapp/github-action/issues/22
2023-03-24 12:51:14 -07:00
ZHANG Dapeng 85e656c0dc
Fix AsyncServletOutputStreamWriterConcurrencyTest flakiness (#9948)
The commit 792946132c (diff-cc7b2eb82d208e027f432435bcd324a46713c31096352f437417b770752f92abR197) makes it possible that the sleep can naturally wake up while `writeState` gets changes at the same time, causing a data race in the value of `parkingThread` between

792946132c/servlet/src/main/java/io/grpc/servlet/AsyncServletOutputStreamWriter.java (L199)

and 

792946132c/servlet/src/main/java/io/grpc/servlet/AsyncServletOutputStreamWriter.java (L218)

, in extreme scenario such as the CPU is stressed.

Fixes #9917
2023-03-24 11:20:38 -07:00
yifeizhuang 687340bbbe
interop-test: fix orca interop test client npe (#9989) 2023-03-24 10:05:56 -07:00
Dirk Haubenreisser 99cbdd5d69
Add support for cross-compiling for s390x platform (#9455)
* Added s390x platform support
* Adapt to existing platform naming scheme
* Updated s390_64 library whitelist
* Use g++ compiler version 8.x for s390x
* Introduced dedicated Docker container for building s390x artifacts Minor fix

---------

Signed-off-by: Dirk Haubenreisser <haubenr@de.ibm.com>
Co-authored-by: Eric Anderson <ejona@google.com>
2023-03-23 13:21:31 -07:00
Eric Anderson 39c9ebf180
examples: Add cancellation example
It uses the echo service for both unary and bidi RPCs, to show the
various cancellation circumstances and APIs.
2023-03-22 18:11:32 -07:00
Larry Safran 6b7cb9e4a4
examples: fix bazel build (#9986) 2023-03-22 18:02:49 -07:00
DNVindhya af8048b727
examples: add gcp-observability examples (#9967)
* add examples for gcp-observability
2023-03-22 17:02:25 -07:00
Stanley Cheung a6cdf498c9
Remove sleep from Observability Interop Test binary now that its done in close() (#9977)
After #9972, the `sleep()` is done inside Observability `close()`, we can remove this `sleep()` in the Observability Interop test binary.
2023-03-22 16:50:09 -07:00
DNVindhya 3634901849
gcp-o11y: add default custom tag for metrics exporter
This PR adds a default custom tag for metrics, irrespective of custom
tags being present in the observability configuration. 

OpenCensus by default adds a custom tag
[opencenus_task](https://docs.google.com/document/d/1sWC-XD277cM0PXxAhzJKY2X0Uj2W7bVoSv-jvnA0N8Q/edit?resourcekey=0-l-wqh1fctxZXHCUrvZv2BQ#heading=h.xy85j580eik0)
for metrics which gets overriden if custom tags are set.

The unique custom tag is required to ensure the uniqueness of the
Timeseries. The format of the default custom tag is:
`java-{PID}@{HOSTNAME}`, if `{PID}` is not available a random number
will be used.
2023-03-22 16:44:58 -07:00
Larry Safran 18a318c6c8
examples: waitForReady example (#9960)
Add an example using waitForReady

Part of fixit.  Fixes b/259286751
2023-03-22 12:14:00 -07:00
Kun Zhang dba3c04608
netty: implement GrpcHttp2InboundHeaders.iterator()
This will be used to generate more useful debugging information in
cases such as headers size exceeding the limit.
2023-03-22 12:11:26 -07:00
Kun Zhang 97aa279ed5
test/android: fix the import for AndroidJUnit4
Everywhere else is using
androidx.test.ext.junit.runners.AndroidJUnit4, and google internally
only has that variant.
2023-03-22 11:28:16 -07:00
DNVindhya 783de5dfc9
gcp-o11y: add sleep in Observability close()
This commit adds sleep in `close()` for metrics and/or traces to be
flushed before closing observability.

Currently sleep is set to 2 * [Metrics export interval (30 secs)].
2023-03-22 08:40:05 -07:00
Vindhya Ningegowda 9039d4dcff disable recording real-time metrics using in gcp-o11y 2023-03-21 16:17:30 -07:00
DNVindhya 844de39c26
gcp-observability, census: add trace information to logs (#9963)
This commit adds trace information (TraceId, SpanId and TraceSampled)
fields to LogEntry, when both logging and tracing are enabled in
gcp-observability. 

For server-side logs, span information was readily available using
Span.getContext() propagated via `io.grpc.Context`. Similar approach is
not feasible for client-side architecture.

Client SpanContext which has all the information required to be added
to logs is propagated to the logging interceptor via `io.grpc.CallOptions`.
2023-03-20 14:18:16 -07:00
yifeizhuang efce51be0b
examples: add reflection example (#9955) 2023-03-20 08:54:44 -07:00
Terry Wilson dc313f2e4e
examples: deadline example (#9958)
This provides an example on how a client can specify a deadline for an RPC. Also covers how deadlines are propagated to further RPCs a server might make.
2023-03-17 19:39:04 -07:00
yifeizhuang 4bbee69534
examples: add keepalive example (#9956) 2023-03-17 16:27:33 -07:00
Larry Safran 78fff08eb1
examples: Add an example for doing debug (#9957)
Extensive README, a server that exposes channelz and has pauses, and a client that uses multiple channels also exposes channelz service and has a 30 second delay to allow people to run the grpcdebug tool.

Fixit b/259286633
2023-03-17 16:26:06 -07:00
DNVindhya 1b799adc19
gcp-observability: Update logging fields for GA and use custom BatchingSettings (#9959)
This commit updates the following in gcp observability logging schema
* `payload.status_code` will be of type `google.rpc.Code` instead of `uint32`.
*  names in enum `Address.TYPE`

Use custom batching settings for [LoggingOptions](https://javadoc.io/doc/com.google.cloud/google-cloud-logging/latest/com/google/cloud/logging/LoggingOptions.html)

Note: Upgraded `com.google.cloud:google-cloud-logging` from `3.6.1` to `3.14.5`.
2023-03-17 15:53:46 -07:00
yifeizhuang c1ff4a856d
buildscript: iterate all example folder and build (#9961) 2023-03-17 15:09:58 -07:00
Jeff Davidson b8444d563d
binder: Expose client identity via a new abstract 'PeerUid' type (#9952)
The actual remote uid was kept private to prevent misuse.
2023-03-16 17:34:13 -07:00
DNVindhya b09473b0d3
census: Trace annotation for reporting inbound message sizes (#9944)
This commit uses [OpenCensus Annotation][] to report message size
[bytes] for inbound/received messages in traces.

`addMessageEvent` API which is currently used expects both uncompressed
and compressed message (optional) sizes to be reported at the same.
Since decompression for messages happens at a later point in time,
reporting compressed message as is and reporting uncompressed size as
`-1` renders the size as _0 bytes received_ in cloud tracing front end.

As a workaround, we add _two annotations for each received message_:
* For compressed message size
* For uncompressed message size (when it is available)

This commit also removes `addMessageEvents` a flag introduced in
PR #9485 to temporarily suppress message events for gcp-observability.

[OpenCensus Annotation]: https://www.javadoc.io/static/io.opencensus/opencensus-api/0.31.0/io/opencensus/trace/Annotation.html
2023-03-10 16:19:21 -08:00
Ken Katagiri 915c706dec android: Add UDSChannelBuilder
Allows using Android's LocalSocket via a Socket adapter. Such an adapter
isn't generally 100% safe, since some methods may not have any effect,
but we know what methods are called by gRPC's okhttp transport and can
update the adapter or the transport as appropriate.
2023-03-10 15:28:55 -08:00
Stanley Cheung cc03b480b8 Pass interop parameters to each langs run.sh as-is. run.sh should just pass through to the interop client/server binaries 2023-03-10 10:34:11 -08:00
Larry Safran 136665f00e
api,stub:Stabilize part of compression agreed to in the stabilization meeting (#9942)
* api,stub:Stabilize part of compression agreed to in the stabilization meeting.

addresses part of #1704
2023-03-09 12:25:43 -08:00
Terry Wilson 7ecb909776
buildscripts: Use Java 11 with android-interop (#9943) 2023-03-09 09:33:10 -08:00
Stanley Cheung 06ec0b93a5
interop-testing: Do not System.exit(0) from interop client
After #9937 was merged, the Java observability tests start to fail.

This System.exit(0) call in the existing Interop client main() method
prevented execution to continue in the new combined Observability
Interop test binary here. (The new binary is calling the old binary's
main() method.)
2023-03-08 11:53:42 -08:00
Terry Wilson b5b7cacba9
Upgrade Android Gradle plugin to 7.4.0 (#9933)
This is the latest version of the plugin supported by the Gradle version
in use at the moment (7.6).

Note that this also upgrades the R8 optimizer to a version (4.0.48) that
now uses "full mode" optimization by default.

This also splits off Android projects to run under Java 11 (Gradle
plugin requirement) while the other projects continue to run under Java
8.
2023-03-08 11:18:27 -08:00
Terry Wilson 2351e37dd7
binder: Do not fail binder build on javadoc errors (#9941)
We will be running this with Java 11, which has elevated some earlier
warnings to errors that fail the build. We don't want the build to fail
because of this.
2023-03-08 10:02:02 -08:00
Terry Wilson 3332199106
Start 1.55.0 development cycle (#9939) 2023-03-07 18:14:31 -08:00
Eric Anderson 4229191a23 Move gcp-observability interop binary out of interop-testing
gcp-observability has many dependencies so is a bit annoying in some
build systems to get working... just for it not to be used in
non-observability scenarios.

grpc-go and c core are using separate binaries for gcp-observability
interop testing, so do the same in Java, which makes interop-testing a
bit lighter.
2023-03-07 10:57:38 -08:00
Larry Safran 7aa5598dc0
api:stabilize offloadExecutor. (#9931)
* api:Stabalize offloadExecutor.

fixes #6279
2023-03-06 12:49:37 -08:00
Terry Wilson 56e4ce49bd
Rename AbstractXdsClient to ControlPlaneClient (#9934)
AbstractXdsClient is not abstract.
2023-03-06 10:35:32 -08:00
Stanley Cheung b55ecd5c35
GCP Observability Interop Testing Client/Server for Java (#9858) 2023-03-06 08:24:42 -08:00
Benjamin Peterson 4b6853b6dd
errorprone: enable UnnecessaryAnonymousClass (#9927)
The Java 7 compatibility rationale no longer holds.
2023-03-03 15:16:17 -08:00
DNVindhya 66f95b7ade
census: add per call latency metric (#9906)
* updated call latency measure with AGGREGATION_WITH_MILLIS_HISTOGRAM; added test for call latency view
2023-03-03 09:36:14 -08:00
Benjamin Peterson 5be17e8b22 build: allow Java 11+ to use modern error prone 2023-03-02 17:31:50 -08:00
Larry Safran 95a44e0592
Move retrieval of elapsed time in handleRpcStreamClosed to make TSan happy (#9923)
* In `handleRpcStreamClosed()`, move retry handling to before the call to `xdsResponseHandler.handleStreamClosed()` so that TSan doesn't report a race condition that is completely meaningless.

fixes #9920
2023-03-02 15:28:37 -08:00
yifeizhuang c367b267c6
xds, wrr: randomize the initial deadline in the scheduler (#9922) 2023-03-02 15:17:54 -08:00
Eric Anderson 7e41d82b5a .github/workflows: Bump dessant/lock-threads to v4 2023-03-02 10:42:45 -08:00
yifeizhuang c7f556a9a6
xds: exclude generated error prone (#9921) 2023-03-02 09:41:31 -08:00
Benjamin Peterson ae6c506f96
all: fix build with errorprone 2.18 (#9886)
errorprone cannot be updated past 2.10 because later versions do not support Java 8.

Fixes https://github.com/grpc/grpc-java/issues/9916.
2023-03-01 13:45:18 -08:00
Eric Anderson a9a7cd129c api: Forward getMethodDescriptor() in ForwardingServerCall 2023-03-01 09:38:38 -08:00
yifeizhuang 8d12baa447
xds: add weighted round robin LB policy support (#9873) 2023-02-27 10:34:51 -08:00
Eric Anderson cc28dfdb36 compiler: Inform the compiler that GRPC_CODEGEN_FAIL aborts
This is enough for the linter to realize that the missing break cases
do not imply fallthrough.
2023-02-27 10:01:07 -08:00
Eric Anderson c3f02d5957
gcp-observability: Fix transitive gRPC versions
google-cloud-logging brings in xds, services, and netty-shaded versions
1.43.2. grpc-netty-shaded and xds use internal APIs, so their version
needs to align with grpc-api and grpc-core.  OpenCensus stackdriver
components also brings in netty-shaded version 1.27.2, but it was later
in the dependency list so google-cloud-logging's versions won out even
if using Maven.

We don't need an explicit dependency on netty-shaded because xds depends
on it transitively.

This was discovered because our GAE interop test failed in the course of
PR #9858 which added grpc-gcp-observability to interop-testing (and thus
also gae-interop-test):
```
Caused by: java.lang.AbstractMethodError: io.grpc.ManagedChannelProvider.getSupportedSocketAddressTypes()Ljava/util/Collection;
    at io.grpc.ManagedChannelRegistry.newChannelBuilder(ManagedChannelRegistry.java:186)
    at io.grpc.ManagedChannelRegistry.newChannelBuilder(ManagedChannelRegistry.java:155)
    at io.grpc.Grpc.newChannelBuilder(Grpc.java:101)
    at io.grpc.testing.integration.LongLivedChannel.<init>(LongLivedChannel.java:44)
    ... 44 more
```
2023-02-24 13:45:19 -08:00
Stanley Cheung 111033e818
servlet: Don't assume ManagedChannelBuilder will be NettyChannelBuilder (#9914) 2023-02-24 13:44:32 -08:00
Carl Mastrangelo 26c2db9c39
api: forward getSecurityLevel on PartialForwardingServerCall (#9912)
* api: forward getSecurityLevel on PartialForwardingServerCall
2023-02-23 22:36:39 -08:00
Terry Wilson d8c572dde6
compiler: add missing break in switch statement (#9901)
Linters don't like this kind of stuff.
2023-02-17 12:18:04 -08:00
Eric Anderson 305dfee2a8 api: Target schema should be case insensitive
URI schema are case-insensitive. Previously the code would do
case-sensitive matching. We expect NameResolverProviders to return the
typical canonical scheme formatting, which is lower-case. If a
NameResolverProvider returns an unexpected string (upper case, unicode,
etc), then it simply won't ever match. Channel users, however, can use
either casing in target strings.

The code implicitly already handled relative URIs by returning null, as
Map.get(null) returned null.
2023-02-17 07:57:20 -08:00
Terry Wilson b481f34855
xds: deletion only to watchers of same control plane (#9896)
When XdsClient learns that a control plane no longer tracks a resource,
it should only notify watchers associated with that control plane.

This matters in control plane federation cases when more than one
control plane is in use.
2023-02-17 06:34:30 -08:00
yifeizhuang 4ef0200f6b
xds: import envoy proto for WRR (#9898) 2023-02-16 15:23:28 -08:00
Terry Wilson e3bd5baeda
grpclb: no SRV lookup for "metadata.google.internal."
This change is to address b/269159638 about GCP metadata server returning an unexpected REFUSED status instead of NXDOMAIN. This causes a 15s delay with older versions of systemd-resolved.

This issue was observed with systemd 245.4. Version 251 worked without issue.
2023-02-16 12:57:54 -08:00
Larry Safran 3fb9abcb2c
Remove ExperimentalApi from ServerBuilder.intercept. (#9894)
Fixes #3117
2023-02-16 07:19:41 -08:00
DNVindhya 7942b9e7f5
gcp-observability: add new *compressed_bytes_per_rpc views (#9893)
* Add new metric views; Register latency and bytes per metrics views for observability
* update view description to inlcude client/server
* Use pre-defined aggregation from OpenCensus for bytes histogram
* updated view names
2023-02-15 17:17:39 -08:00
Larry Safran 19eab29f8d
compiler: Generate interfaces for services to implement (#9688)
Introduce an AsyncService interface in the generated code and move the methods from <service>ImplBase to default implementation of the interface.
* update pom files to allow java 1.8
* Add a bindService(<service>Async) method
* Change TestServiceImpl to use the interface and include a bind method instead of extending TestServiceImplBase.
2023-02-15 10:33:44 -08:00
Sergey Matyukevich 67d6600f71
core: add logger to OutlierDetectionLoadBalancer (#9880) 2023-02-14 13:27:21 -08:00
yifeizhuang 3d4d46d9ff
Revert "core: add subchannel list LB commons utility function, refactor for WRR (#9875)" (#9892)
This reverts commit 5a2adcc7c6.
2023-02-13 17:28:24 -08:00
Terry Wilson d42678a3bf
core: fix outlier detection default ejection time (#9889) 2023-02-13 14:40:31 -08:00
Terry Wilson c194c71c50
protobuf: update external javadoc link (#9890) 2023-02-13 08:23:12 -08:00
Ivan Bahdanau 5beae3a53b
Updating ServerInterceptors.java to support different marshallers for Request and Response messages. (#9877)
Fixes #9870
2023-02-10 11:43:39 -08:00
yifeizhuang f6a0028fe5
orca: support remove listener in OrcaOobUtil (#9881) 2023-02-08 09:50:32 -08:00
Larry Safran b8d23a3c2c
netty:Upgrade Netty from 4.1.79 to 4.1.87, tcnative from 2.0.54 to 2.0.56 (#9784)
* Upgrade Netty from 4.1.79 to 4.1.87 and tcnative from 2.0.54 to 2.0.56
2023-02-06 17:54:28 -08:00
Larry Safran 5983be1369
rls:Fix throttling in route lookup (b/262779100) (#9874)
* Correct value being passed to throttler which had been backwards.

* Fix flaky test.

* Add a test using AdaptiveThrottler with a CachingRlsLBClient.

* Address test flakiness.
2023-02-06 15:19:16 -08:00
Asaf Flescher 56a08c3506
Build Improvements (#9855)
* Made dependency on build.gradle in protobuf tasks relative so as to make downstream tasks cacheable

* Made transformer cacheable

* Add property name to path to root build.gradle

Co-authored-by: Nelson Osacky <nelson@osacky.com>
2023-02-06 14:57:09 -08:00
Terry Wilson fcb5c54e4b
Move name resolution retry from managed channel to name resolver (take #2) (#9812)
This change has these main aspects to it:

1. Removal of any name resolution responsibility from ManagedChannelImpl
2. Creation of a new RetryScheduler to own generic retry logic
     - Can also be used outside the name resolution context
3. Creation of a new RetryingNameScheduler that can be used to wrap any
   polling name resolver to add retry capability
4. A new facility in NameResolver to allow implementations to notify
   listeners on the success of name resolution attempts
     - RetryingNameScheduler relies on this
2023-02-03 18:23:32 -08:00
yifeizhuang 5a2adcc7c6
core: add subchannel list LB commons utility function, refactor for WRR (#9875) 2023-02-03 17:53:51 -08:00
Eric Anderson 8154fadf7e compiler: Add docs describing requirements for generated code 2023-02-03 12:53:03 -08:00
Larry Safran 54c1f37093
xds:Allow big cluster total weight (#9864)
* xds:  allow sum of cluster weights above MAX_INT up to max of unsigned int.

* Define nextLong(long bound) method in FakeRandom for WeightedRandomPickerTest.
2023-02-03 10:53:50 -08:00
Kun Zhang 04afea0fbd
test: new JDK fixed InetSocketAddress toString so we are updating our test (#9876)
The change was introduced in JDK 14 (f8440c33d2) so JDK 17 for us to care about.

Fixes internal issue: b/261217361
2023-02-02 21:35:24 -08:00
Eric Anderson 51913f6e9e Bump os-maven-plugin to 1.7.1 2023-02-02 18:30:32 -08:00
Eric Anderson 43917f052e Use Apache CDN to download Maven
Maven seems to have improved their download management and instead of
having their webpage choose a host they now have a CDN domain.
apache.cs.utah.edu is slow and is failing to finish the downloading.
2023-02-02 16:42:06 -08:00
yifeizhuang 6119f6ec94
services: add qps in orca api (#9866) 2023-02-02 15:16:27 -08:00
Benjamin Einaudi fb70a66e2c Fixes MethodDescriptor java documentation
According to git history, method 'getBareMethodName' and 'extractBareMethodName' of MethodDescriptor appeared in 1.33.0
2023-02-02 12:46:18 -08:00
yifeizhuang b7164f0791
xds: import cncf/xds (#9862) 2023-01-30 10:42:11 -08:00
yifeizhuang 4876996d84
Start 1.54.0 development cycle (#9857) 2023-01-25 10:56:58 -08:00
Larry Safran 501ca8f7b4
xds: Update logic so that an error being reported when stream is closed gets propagated to subscribers (#9827)
* Stop setting waitForReady in XdsClient's AbstractXdsClient.
* Handle bad URL cleanly.  

Fix test cases to deal with asynchronous flow.
2023-01-24 18:31:50 -08:00
Terry Wilson b0635fa1d4
googleapis: Allow user set c2p bootstrap config (#9856)
Instead of always overriding the bootstrap with a custom c2p config, now
we allow user defined ones to also be used. This only applies when
running in GCP with federation.
2023-01-24 15:57:11 -08:00
chenwei321 b2895198c3
xds: fixed RouteConfiguration not supporting contain and stringMatcher (#9845) 2023-01-23 11:49:56 -05:00
Colin Alworth 706646f8bb
servlet: Implement gRPC server as a Servlet (#8596)
Full end to end implementation of gRPC server as a Servlet including tests and examples

Co-authored-by: Penn (Dapeng) Zhang <zdapeng@google.com>
Co-authored-by: Chengyuan Zhang <chengyuanzhang@google.com>
2023-01-20 13:17:58 -08:00
Eric Anderson 44847bf4e9
Upgrade JUnit to 4.13.2
ExpectedException is deprecated, so I fixed the new warnings. However,
we are still using ExpectedException many places and had previously
supressed the warning. See
https://github.com/grpc/grpc-java/issues/7467 . I did not fix those
existing instances that had suppressed the warning, since it is
unrelated to the upgrade and we have been free to fix them at any time
since we dropped Java 7.
2023-01-20 09:33:11 -08:00
Eric Anderson 5a2c94bca1 core: Free unused MessageProducer in RetriableStream
This prevents leaking message buffers.

Fixes #9563
2023-01-20 07:48:35 -08:00
Eric Anderson 9de989bd64 okhttp: Avoid DNS lookup in test
Our tests assume localhost is in /etc/hosts or uses some other form of
local-only resolution. But that wouldn't apply to "host". What was
happening is this was causing a DNS resolution, which would fail, and
the InetSocketAddress would be "unresolved". Thus, the equivalent and
faster code would be `InetSocketAddress.createUnresolved("host", 1234)`.
But there doesn't seem to be any reason to avoid localhost in this test,
so swap to the more typical solution instead.

This should avoid flakes like:
```
io.grpc.okhttp.OkHttpClientTransportTest > invalidAuthorityPropagates FAILED
    org.junit.runners.model.TestTimedOutException: test timed out after 10 seconds
        at java.base@11.0.17/java.net.Inet6AddressImpl.lookupAllHostAddr(Native Method)
        at java.base@11.0.17/java.net.InetAddress$PlatformNameService.lookupAllHostAddr(InetAddress.java:929)
        at java.base@11.0.17/java.net.InetAddress.getAddressesFromNameService(InetAddress.java:1529)
        at java.base@11.0.17/java.net.InetAddress$NameServiceAddresses.get(InetAddress.java:848)
        at java.base@11.0.17/java.net.InetAddress.getAllByName0(InetAddress.java:1519)
        at java.base@11.0.17/java.net.InetAddress.getAllByName(InetAddress.java:1378)
        at java.base@11.0.17/java.net.InetAddress.getAllByName(InetAddress.java:1306)
        at java.base@11.0.17/java.net.InetAddress.getByName(InetAddress.java:1256)
        at java.base@11.0.17/java.net.InetSocketAddress.<init>(InetSocketAddress.java:220)
        at app//io.grpc.okhttp.OkHttpClientTransportTest.invalidAuthorityPropagates(OkHttpClientTransportTest.java:1687)
```
2023-01-19 10:51:20 -08:00
yifeizhuang f1f40b0b23
Update README etc to reference 1.52.1 (#9849) 2023-01-19 10:26:16 -08:00
Larry Safran 3cbd948bad
Restore "netty:Auto adjust BDP ping frequency" with fix (#9847)
* Revert "Revert "netty:Auto adjust BDP ping frequency (#9650)" (#9821)"

This reverts commit a2bbe84198.

* Eliminate half RTT delay in sending BDP Pings when starting up.
* Eliminate delay for bdp ping when current read would push us over the threshold.
2023-01-18 18:27:56 -08:00
Alexander Polcyn ecc7cf35a2 Address internal linter suggestions 2023-01-18 13:33:19 -08:00
pandaapo 0f4b767660
core: Add grpc-previous-rpc-attempts to the initial response metadata (#9686)
Fixes #9641
2023-01-17 15:33:45 -08:00
Sergii Tkachenko f2533f4fd8
xds interop: Fix buildscripts not continuing on a failed test suite (#9833)
Apparently there's a difference between bash 3 and bash 4.
OSX comes with bash 3 out-of-box, so for whoever wrote this logic
it "worked on my machine".

The `((` construct returns a 0 exit code if the value is non-zero.
Since the value starts at 0 and we do a post-increment,
it will always fail the first time.
Changing it to a pre-increment should fix it.
2023-01-17 13:15:40 -08:00
Eric Anderson 62d924745d core: Remove unused helper field from SubchannelImpl 2023-01-17 13:06:00 -08:00
Sergii Tkachenko 42ba00ba65
Revert "xds interop: Fix buildscripts not continuing on a failed test suite (#9817)" (#9831)
This reverts commit d83a599c97.

Reverted in favor of better syntax suggested here: https://github.com/grpc/grpc-node/pull/2323#pullrequestreview-1248043432. This fix will be sent as another PR for the convenience of backporting.
2023-01-17 11:36:31 -08:00
Larry Safran ed71b0a520
Update README etc to reference 1.52.0 (#9815) 2023-01-13 12:44:21 -08:00
Sergii Tkachenko d83a599c97
xds interop: Fix buildscripts not continuing on a failed test suite (#9817)
Apparently there's a difference between bash 3 and bash 4.
OSX comes with bash 3 out-of-box, so for whoever wrote this logic
it "worked on my machine".
2023-01-13 12:42:45 -08:00
apolcyn 23d34cdd84
testing: create test client for XDS federation integration tests (#9798)
This client can be used as a part of XDS federation integration tests. It can concurrently perform RPCs with different stubs using different underlying XDS servers.

For example, one might perform proxyless service mesh and DirectPath RPCs in the same process with flags like:

```
--server_uris=xds:///${PSM_TARGET},google-c2p:///${DIRECTPATH_TARGET} \
--credentials_types=INSECURE_CREDENTIALS,compute_engine_channel_creds \
--test_case=rpc_soak \
--soak_iterations=10  \
--soak_max_failures=0  \
--soak_per_iteration_max_acceptable_latency_ms=2500 \
--soak_overall_timeout_seconds=300
```
2023-01-13 11:55:08 -08:00
Eric Anderson 89b823c550 core: Synchronize access to retry's throttle
Use a volatile to publish the value even though it is final. TSAN
ignores the final aspect of a field, which is fair since another thread
may not see the parent's pointer become updated and use a stale value.
The lack of synchronization was clearly against lastServiceConfig's
documentation.

Fixes #9267
2023-01-13 11:19:15 -08:00
Larry Safran a2bbe84198
Revert "netty:Auto adjust BDP ping frequency (#9650)" (#9821)
This reverts commit f5e8459748.
2023-01-13 10:36:03 -08:00
yifeizhuang 2b9bd6cdac
core: delay retriable stream master listener close until all sub streams are closed (#9754)
This helps to prevent retryable stream from using calloptions.executor when it shouldn't, e.g. call is already notified closed. It is done by delaying notifying upper layer (through masterListener).
2023-01-12 14:51:13 -08:00
Eric Anderson ce86090322 xds: Include unknown type in channel logger warning
This makes the log statement more useful and easier to determine whether
this was expected behavior.
2023-01-12 11:04:20 -08:00
yifeizhuang 82ca98f338
xds:fix cancel xds watcher accidentally removes the url (#9809)
Fix a bug. When any of the xds subscribers for a resource has the last watcher cancelled, the bug will accidentally remove that resource type from the map, which make xds stream not accepting response update for that resource type entirely(pass through, no ACK/NACK will send).
2023-01-11 15:33:48 -08:00
Eric Anderson eb391fd66c Bump to Gradle 7.6 and update plugins
As normal, Android versions weren't touched as it tends to be special to
upgrade.

The errorprone plugin handles errorproneJavac for us now, since it
hasn't changed in five years. VERSION_CATALOGS is already enabled by
default and graduated out of preview.

Fixes #9802
2023-01-11 08:17:17 -08:00
Eric Anderson ec5bc6b1eb Drop Bazel 4 support
Bazel 6 has been released, and we track the two most recent major
versions.
2023-01-11 08:15:47 -08:00
Stefan Puhlmann 56a4186f0a Testing that Netty clients fail for mismatching TLS common names
Netty is known to not use SSL hostname verfication by default[1], although
this is enabled for gRPC channels. This change validates that
functionality by porting a test with a similar purpuse for OkHttp.

* [1]: https://github.com/netty/netty/issues/8537
2023-01-10 09:11:29 -08:00
yifeizhuang 45554def76
interop test: fix project evaluation order (#9800) 2023-01-09 15:49:07 -08:00
Eric Anderson d761fc6db9 okhttp: Remove unnecessary client certs in TlsTest
This simplifies the tests and makes them more clear. basicTls_succeeds
was added to confirm excluding the client cert functions.
2023-01-09 14:57:25 -08:00
Eric Anderson a40e4343f5 okhttp: Use normal server cert when testing trust checking
Previously, untrustedServer_fails could have been failing for the same
reason as unmatchedServerSubjectAlternativeNames_fails. The
implementation could have been broken and not checking the cert chain
but still checking the hostname. We'd either need to override the
authority to match the badserver cert or use the normal server
certificates. It is best to use the normal server certificates as
mtls_succeeds confirms the configuration is correct and so our test is
failing for the right reason.
2023-01-09 10:28:35 -08:00
Chris Povirk c0de130ac6 Change ArgumentCaptor.forClass(null) to ArgumentCaptor.forClass(Foo.class)
The former will [soon throw NullPointerException][notnull].

[notnull]: fe1cb2de09 (diff-8d274a9bda2d871524d15bbfcd6272bd893a47e6b1a0b460d82a8845615f26daR31)
2023-01-09 07:15:23 -08:00
Eric Anderson cc5378453f
api: Early-detect null bytes from Metadata.Marshaller
See #9706
2023-01-05 17:36:24 -08:00
Eric Anderson d17a2db4bd Upgrade to Checkstyle 8.28
Trying to upgrade Gradle to 7.6 improved the checkstyle plugin such that
it appears to have been running in new occasions. That in turn exposed
us to https://github.com/checkstyle/checkstyle/issues/5088. That bug was
fixed in 8.28, which also fixed lots of other bugs. So now we have
better checking and some existing volations needed fixing. Since the
code style fixes generated a lot of noise, this is a pre-fix to reduce
the size of a Gradle upgrade.

I did not upgrade past 8.28 because at some point some other bugs were
introduced, in particular with the Indentation module. I chose the
oldest version that had the particular bug impacting me fixed. Upgrading
to this old-but-newer version still makes it easier to upgrade to a
newer version in the future.
2023-01-05 17:07:04 -08:00
yifeizhuang d07ecbe037
xds: refactor LoadReportClient with xds v2 dropped (#9788) 2023-01-05 12:49:23 -08:00
Sergii Tkachenko 040e2831e4
xds: fix the EDS dups test so it doesn't assume address order (#9786) 2023-01-04 10:47:07 -08:00
panxuefeng f40231e147
buildscripts: Enhancement for LoongArch64 (#9778) 2023-01-04 09:11:23 -08:00
Sergii Tkachenko f4cda008ee
buildscripts: drop xDS v2 interop test (#9783)
This disables xDS v2 support interop test.
xDS v2 support dropped in https://github.com/grpc/grpc-java/pull/9760.

Internal ref cl/499306755
2023-01-03 15:37:12 -08:00
Eric Anderson f0614e5a76 bazel: Export deps from maven stand-in targets
If an artifact on Maven Central exposes a type from gRPC on its API
surface, then consumers of that artifact need that gRPC API in the
compile classpath. Bazel handles this by making hjars for transitive
dependencies, but if the dependencies are runtime_deps then Bazel won't
generate hjars containing the needed symbols.

We don't export netty-shaded because the classes already don't match
Maven Central. If an artifact on Maven Central is exposing a
netty-shaded class on its API surface, it wouldn't work anyway since the
class simply doesn't exist for the Bazel build.

Fixes #9772
2023-01-03 13:36:27 -08:00
Larry Safran 51ee3eb6ab
xds: Disallow duplicate addresses in the RingHashLB. (#9776)
* xds: Disallow duplicate addresses in the RingHashLB.
Removed test that was previously checking for specific expected behavior with duplicate addresses.
2023-01-03 13:11:46 -08:00
yifeizhuang 3c5c2be712
xds: drop xds v2 support (#9760) 2022-12-28 10:35:44 -08:00
Larry Safran f5e8459748
netty:Auto adjust BDP ping frequency (#9650)
* netty:Auto adjust BDP ping frequency

* Change setDataSizeAndSincePing to set time to current time rather than 1 second (or nanosecond) previous.
2022-12-21 18:00:06 -08:00
Ashitha Santhosh 0194ae9a41
Static authorization server interceptor implementation (#8934)
* Static authorization server interceptor implementation

* Resolving comments

* Remove RbacParser file

* update error logs

* checkstyle fixes

* Add InternalRbacFilter

* formatting

* javadoc

* format test file

* resolving comments

* minor formatting

* Update comment
2022-12-21 15:30:42 -08:00
Larry Safran 530cf905b1
xds:Fix test flakiness by adding a timeout to verify. (#9771)
* xds:Fix test flakiness by adding a timeout to verify.
* Add a note warning about multiple threads in the test.
2022-12-21 14:29:17 -08:00
Larry Safran fe19152108
Eds weight allowed between max signed and max unsigned int (#9765)
* Enforce individual weights and sum of weights not exceeding the max unsigned int value
2022-12-20 13:07:10 -08:00
Eric Anderson 7c73baa450 Revert "Move name resolution retry from managed channel to name resolver. (#9758)"
This reverts commit 43bc578f20. It breaks
API without stair-stepping and needs to be tweaked architecturally.
2022-12-20 08:35:31 -08:00
Eric Anderson f08300e0e3 bazel: Include `@Generated` dep for autovalue
Fixes #9755
2022-12-19 19:51:29 -05:00
Kun Zhang 6adae08597
test: fix internal ErrorProne failure (#9761) 2022-12-19 12:54:24 -08:00
Terry Wilson 43bc578f20
Move name resolution retry from managed channel to name resolver. (#9758)
This change has these main aspects to it:

1. Removal of any name resolution responsibility from ManagedChannelImpl
2. Creation of a new RetryScheduler to own generic retry logic
     - Can also be used outside the name resolution context
3. Creation of a new RetryingNameScheduler that can be used to wrap any
   polling name resolver to add retry capability
4. A new facility in NameResolver to allow implementations to notify
   listeners on the success of name resolution attempts
     - RetryingNameScheduler relies on this
2022-12-16 15:30:57 -08:00
Larry Safran 46ed02ed72
xds:Update logic to match A57 (#9745)
* xds:Change timer creation logic to wait until the adsStream is ready before creating the timer to mark resources absent.

* xds:When the ads stream is closed only send errors to subscribers that haven't yet gotten results to match spec.

* Use a blocking queue to avoid the 2-second sleep.
For some inexplicable reason the following call.verifyRequest fails only for the V2 test and only from command line not IDE unless there is some Thread.sleep, even if it is only 1-millis.
2022-12-15 14:54:35 -08:00
Larry Safran ccb5d945c0
Start 1.53.0 development cycle (#9757) 2022-12-14 18:07:57 -08:00
Greg e325dc9112
Replace ctx.host_configuration.host_path_separator with ctx.configuration.host_path_separator. (#9742)
Replace ctx.host_configuration.host_path_separator with ctx.configuration.host_path_separator.

This is because

1. we're removing ctx.host_configuration
2. host_path_separator's value doesn't depend on the configuration (the API is misleading by embedding it under ctx.configuration). So this is a no-op.

Internal ref cl/494008561.
2022-12-14 12:13:31 -08:00
yifeizhuang 2a0b86f7cd
binder: BinderInternal.setIBinder() is public static (#9743) 2022-12-09 15:21:47 -08:00
yifeizhuang 9b5ca70f85
doc: add fake control plane xds test comments (#9735) 2022-12-07 14:53:06 -08:00
yifeizhuang 786417085c
xds: Nack xds response when weighted cluster total weight sums zero (#9738) 2022-12-07 13:16:21 -08:00
Mohan Li bf0b92a963
Log xDS node ID with verbosity INFO (#9731)
Log xDS node ID so that we can better debug DirectPath issues.

b/260634412
2022-12-06 08:06:00 -08:00
Larry Safran e14cba0bae
Update clarifying comment per code review. (#9730) 2022-12-02 16:04:17 -08:00
Larry Safran 3e5fa7c5df
xds:Fix ConcurrentModificationException in PriorityLoadBalancer (#9728)
Fix ConcurrentModificationException in PriorityLoadBalancer by making copy of children values to iterate rather than directly using children in for loop.
2022-12-02 15:15:48 -08:00
Eric Anderson 79f4411d20 xds: Remove outdated comment about observing total weight
total_weight is deprecated and serves no value.
2022-12-02 15:09:21 -08:00
yifeizhuang c87fc05224
xds: remove retained resources logics for RDS and EDS resources (#9724)
We use state-of-the-world approach. For LDS/CDS, the control plane must return all resources that the client has subscribed to in each request. If some LDS/CDS resources are gone in a new update, their corresponding RDS/EDS resources names will be onAbsent(), unless there is cached data that is in use by other subscribers in other components. 
The motivations to remove this "retained resource" logic between resource types are:
1. Already handled by the subscribers, e.g. a CDS state would shut down its childLBs on new updates. XdsResolver for LdsUpdate would cancel all existing RDS subscriptions. Therefore the onAbsent() notification is effectively no-op.
2. Complexity.
2022-12-02 10:35:26 -08:00
Smilencer 9dac8cf352
examples: add name resolve and load balance (#9700) 2022-12-01 13:17:34 -08:00
cbianchi-7 e36275e951 Additional changes that were added post-submission of PR 9669 for promoting out of experimental status. 2022-12-01 12:39:55 -08:00
Eric Anderson dceb764385 api: Avoid initializing CallOptions.Builder fields that will be overwritten
The JIT probably cleans this up, but it is a bit confusing and needless.
2022-12-01 11:42:50 -08:00
Eric Anderson df974455ae binder: Remove unused imports 2022-12-01 11:41:57 -08:00
Eric Anderson b51cd9fd99
core: Replace AtomicInteger.updateAndGet with compareAndSet
updateAndGet is only available in API level 24+. It is unclear why
AnimalSniffer didn't detect this.

This was noticed when doing the import, but the Android CI has also been
failing because of it.
2022-12-01 11:09:40 -08:00
Terry Wilson 78415f55d3
xds: Include additional EAG attributes on updates (#9723)
ClusterImplLoadBalancer adds the ATTR_CLUSTER_NAME and
ATTR_SSL_CONTEXT_PROVIDER_SUPPLIER attributes to the EAG list when it
creates a new subchannel, but they are lost on subsequent address
updates. This change assures the attributes are also included on address
updates.
2022-12-01 09:37:10 -08:00
Larry Safran c145473756
Improve error message when deadline is exceeded, making it clear which deadline (Context or CallOptions) was exceeded and making the grammar clearer. (#9713) 2022-11-30 13:58:57 -08:00
cbianchi-7 d6aa0ea370
binder: Promote out of experimental status (#9669) 2022-11-30 10:37:32 -08:00
apolcyn a5f458a3a7
xds: Limit ring hash max size to 4K (#9709)
Implements grpc/proposal#338 for Java.
2022-11-29 14:02:48 -08:00
Terry Wilson 5cf54f3178
xds: Support localities in multiple priorities (#9683)
Additional logic to support for the same locality appearing under
multiple priorities.
2022-11-29 13:15:28 -08:00
Eric Anderson 548d3cac38 MAINTAINERS.md: Add Binder maintainers 2022-11-29 13:01:53 -08:00
markb74 241097c6e0
binder: Set default idle timeout to 60 seconds, and enable "strict lifecycle management". (#9486) 2022-11-29 09:57:25 +01:00
markb74 f082151fb5
binder: Ensure the security interceptor is always closest to the actual transport. (#9716) 2022-11-28 17:38:00 -08:00
Eric Anderson 58ba73205a README.md: Update support docs, OkHttp server, binder 2022-11-28 11:06:01 -08:00
Eric Anderson c80b587579
okhttp: Add missing server support for TLS ClientAuth (#9711) 2022-11-22 17:09:03 -08:00
yifeizhuang b593871801
core: fix RejectedExecutionException in Retriable Stream (#9626)
Add big negative integer to pending stream count when cancelled. The count is used to delay closing master listener until streams fully drained.
Increment pending stream count before creating one. The count is also used to indicate callExecutor is safe to be used. New stream will not be created if big negative number was added, i.e. stream cancelled. New stream is created if not cancelled, callExecutor is safe to be used, because cancel will be delayed.
Create new streams (retry, hedging) is moved to the main thread, before callExecutor calls drain.
Minor refactor the masterListener.close() scenario.
2022-11-22 13:04:06 -08:00
Larry Safran 159bb8c55b
test:Report the values that were compared rather than the underlying durat… (#9710)
* Report the values that were compared rather than the underlying durations that generated those values.

* Eliminate BigInteger to eliminate flakiness from possible class loading overhead.
2022-11-21 17:29:36 -08:00
Eric Anderson 806fb84a57 examples: Swap to Channel/ServerCredentials API
This makes it more obvious when plaintext vs TLS is being used and is
the preferred API.

I did not change the Google Auth example, because it is doing things a
weird way and changing it would be more invasive. I also didn't update
the Android examples.
2022-11-21 09:09:21 -08:00
Sergii Tkachenko 775d79b0eb Update README etc to reference 1.51.0 2022-11-17 13:22:25 -08:00
pandaapo 1b94f48dc8
api: Fix CallOptions to be properly `@Immutable` (#9689)
Although CallOptions is annotated by @Immutable, its fields are not
final. So it's not truly immutable, namely not safe for unsynchronized
publication.

This commit adds final to all fields of CallOptions. Using internal
builder class to keep flexibility of constructing CallOptions.

Fixes #9658
2022-11-17 13:11:27 -08:00
Justin Bassett 1241946c15 Always update the TagContext in filterContext()
This is a potential optimization, depending on the OpenCensus
implementation installed. Currently, the code checks TagContext equality
against the empty TagContext as an optimization to avoid updating the
Context, but checking equality may not be cheaper than updating the
Context. In particular, this condition is almost always true, because we
[update the parentCtx with an additional
tag](bacf18db8d/census/src/main/java/io/grpc/census/CensusStatsModule.java (L770-L774)).
It's only true when there is no OpenCensus implementation (i.e. some
kind of no-op implementation that ignores TagContexts) or when the empty
TagContext already has that tag set to the specific value which varies
depending on the RPC method.

For the default OpenCensus implementation, the equality check is
equality between two maps. Other implementations may require additional
work to determine equality.

Basically, we are trading off rarely avoiding updating the Context for
always doing at least a map equality or potentially even more depending
on the OpenCensus implementation in use. Given this, it makes sense to
just always update the Context.
2022-11-17 10:22:43 -08:00
Sergii Tkachenko 80cd7ec457
bazel: Migrate from `cfg = "host"` to `cfg = "exec"` (#9695)
This change migrates from `cfg = "host"` to `cfg = "exec"`.
This is a no-op cleanup: `cfg = "host"` is a deprecated alias
for `cfg = "exec"`.

Tested:

```
bazel build //grpclb:grpclb
bazel build //compiler:java_grpc_library_toolchain
bazel build //compiler:grpc_java_plugin
bazel build '//compiler:*'
```

Internal ref cl/487924699
2022-11-16 13:01:59 -08:00
RapperCL 096898a46e
ManagedChannelImpl.SubchannelImpl args check bug (#9651)
Previously it could trigger NPE without the string saying which argument
was null.
2022-11-10 16:15:13 -08:00
RapperCL b8f142c1e7 reduce redundant judgment 2022-11-10 14:27:43 -08:00
Sergii Tkachenko eb1e5a11c6 Start 1.52.0 development cycle 2022-11-07 11:56:25 -08:00
Eric Anderson a82ea0cb09 Fix jmh -PjmhIncludeSingleClass
I would have assumed a JMH plugin update renamed include to includes,
but I don't see a mention to it in the plugin changelog. Either it was
an undocumented rename, or devs just kept fixing it locally and not
fixing upstream. In either case, it works now.
2022-11-04 13:46:33 -07:00
Terry Wilson 0d44203bdc
xds: Delay priority LB updates from children (#9670)
If a child policy triggers an update to the parent priority policy
it will be ignored if an update is already in process.

This is the second attempt to make this change, the first one caused a
problem with the ring hash LB. A new test that uses actual control plane
and data plane servers is now included to prove the issue no longer
appears.
2022-11-04 09:17:17 -07:00
Terry Wilson ba182c3e02
core: round_robin to use acceptResolvedAddresses()
Switching to new API to allow eventual deprecation of
handleResolvedAddresses()
2022-11-03 12:40:05 -07:00
Terry Wilson c1d0e14799
xds: Fake control plane test setup code to Rules (#9666)
This extracts the startup and shutdown code for the control and data
plane server to reparate JUnit rules, which allows this logic to be
resued in other tests in a simple manner. Also makes the test easier to
read with the boiler plate init code removed.
2022-11-03 10:48:52 -07:00
Terry Wilson 39c264698d
xds: least_request LB to use acceptResolvedAddresses() (#9616)
This is part of a migration to move all LBs away from using
handleResolvedAddresses().
2022-11-02 16:29:32 -07:00
Terry Wilson a65ecef538
xds: ring_hash to use acceptResolvedAddresses() (#9617)
Part of a migration to move all LBs away from handleResolvedAddresses()
2022-11-02 16:28:31 -07:00
apolcyn a97db60fd7
c2p resolver: use federation if enabled via env var (#9660) 2022-10-28 06:02:55 -07:00
yifeizhuang 47ddfa4f20
okhttp: add maxConnectionAge and maxConnectionAgeGrace (#9649) 2022-10-21 12:06:26 -07:00
Eric Anderson 38311e8730 .github/workflows: Bump action major versions
Almost all of these major version bumps are because they upgraded to
Node 16, which requires a new minimum version of the Runner (which
matters for those maintaining their own runners). The main outlier is
lock-threads, which changed the names of its input parameters.
2022-10-21 10:25:10 -07:00
Sanjay Pujare 4cb090145b Update README etc to reference 1.50.2 2022-10-20 17:36:54 -07:00
yifeizhuang 7007d78b71
doc: improve java doc ManagedChannelOrphanWrapper (#9636) 2022-10-20 11:16:53 -07:00
yifeizhuang fa00094328
xds: fix javadoc warning (#9637) 2022-10-20 10:34:58 -07:00
Sergii Tkachenko 6f3c915267
Update README etc to reference 1.50.1 2022-10-19 11:20:08 -07:00
DNVindhya 13c2db1aa3
add period to service filter regular expression in logging config (#9631) 2022-10-19 11:07:41 -07:00
DNVindhya aeb90e3855
gcp-observability: updated config to public preview config (#9622) 2022-10-18 14:23:54 -07:00
DNVindhya 43942623fb
gcp-observability: update observability logging proto (#9608) 2022-10-17 22:47:54 -07:00
Terry Wilson e16f1436a9
xds: wrr_locality LB to use acceptResolvedAddresses() (#9625)
Part of a migration to move load balancers away from
handleResolvedAddresses().
2022-10-13 16:27:03 -07:00
Terry Wilson 3198195908
xds: weighted_target to use acceptResolvedAddresses() (#9624)
Part of a migration from handleResolvedAddresses().
2022-10-13 15:55:23 -07:00
Terry Wilson b873dc2a7b
xds: Priority LB to use acceptResolvedAddresses() (#9623)
Part of a migration to move load balancers away from
handleResolvedAddresses()
2022-10-13 15:51:14 -07:00
Terry Wilson 63f3787f86
xds: cluster_resolver to use acceptResolvedAddresses() (#9615)
Part of a wider migration to migrate load balancers away from
handleResolvedAddresses().
2022-10-13 13:27:51 -07:00
Eric Anderson 6904f88a7d Update README etc to reference 1.50.0 2022-10-13 07:50:08 -07:00
Eric Anderson 38ef8d22d4 services: Exclude io.grpc.protobuf.services.internal from javadoc 2022-10-12 09:42:20 -07:00
Eric Anderson 18602b74e1 COMPILING.md: Fix protobuf version number to 21.7
This is essentially a repeat of b118e00c, but for our compiling
documentation. Protobuf has two versions nowadays: 3.21.7 for Java and
21.7 for protobuf as a whole. For 21.1 they tagged it both as 21.1 and
3.21.1, but they didn't do that for 3.21.7.

Fixes #9582
2022-10-10 16:06:52 -07:00
Terry Wilson 458e06fafa
cds: ClusterImplLoadBalancer to use acceptResolvedAddresses() (#9571)
This is part of the API migration away from handleResolvedAddresses().
2022-10-10 15:55:57 -07:00
Terry Wilson ab78f39f23
xds: ClusterManagerLoadBalancer to use acceptResolvedAddresses() (#9572)
Part of an API migration away from handleResolvedAddresses().
2022-10-10 15:51:10 -07:00
Terry Wilson 8473e270eb
xds: CdsLoadBalancer2 to use acceptResolvedAddresses (#9570)
xds: CdsLoadBalancer2 to use acceptResolvedAddresses

Moving over from handleResolvedAddresses() as part of an API migration.
2022-10-10 15:06:59 -07:00
Terry Wilson 950fb7da61
rls: Migrate RLS LB to acceptResolvedAddresses() (#9612)
Second attempt at this, now with the understanding that RLS actually can
accept empty address lists.

This seems contrary to the behavior this LB advertizes with the canHandleEmptyAddressListFromNameResolution() method. This method is not overridden, so the default response of false is preserved. Empty address lists are supported though, and the parent LB never called the canHandleEmptyAddressListFromNameResolution() method.
2022-10-10 13:38:03 -07:00
Terry Wilson 31d777e212
grpclb: switch to use acceptResolvedAddresses() (#9568)
This is part of a migration to move all LB implementations from
handleResolvedAddresses() to this new method.
2022-10-10 13:31:46 -07:00
Trevor Edwards 73020a9dd7 grpclb: fix mismatched indices in addresses log 2022-10-10 09:56:48 -07:00
yifeizhuang fe8f474055
xds: Fix AbstractXdsClient fromTypeUrl to use subscribedResources instead of hardcoded (#9607) 2022-10-07 13:33:38 -07:00
yifeizhuang 68339250e4
xds: remove ResourceType enum, use XdsResourceType instead (#9587)
Now the xds resources are dynamically managed in resourceStore in xdsClient. The types is a xdsResourceType, singleton.
There is no longer hardcoded static list of known resource types, the subscription list is the source of truth.
AbstractXdsClient that manages AdsStream will only accept the xds resource types that has already has watchers subscribed to, same behaviour as before.
2022-10-06 13:10:55 -07:00
yifeizhuang cff8bd8d87
doc: name resolver start() should not throw (#9589) 2022-10-05 16:22:30 -07:00
Terry Wilson df0a4bdc1b
Update README etc to reference 1.49.2 (#9588) 2022-10-04 15:16:09 -07:00
Terry Wilson dd35ae5206
okhttp: Add client transport proxy socket timeout (#9586)
Not having a timeout when reading the response from a proxy server can
cause a hang if network connectivity is lost at the same time.
2022-10-04 12:43:02 -07:00
sanjaypujare 6b80efcfa8
xds: security code refactoring: delete unused code and rename misc things (#9583) 2022-10-04 12:41:17 -07:00
Eric Anderson b118e00cf9
Use Protobuf 21.7 in our code generator
This aligns the C++ version we're using for gRPC-generated code with the
Java version. This should have no real impact to our users, as there
were no features added to .proto files or the like that would be visible
to users.
2022-10-04 10:22:52 -07:00
Alexander Polcyn b7363bc854 Revert "rls: use acceptResolvedAddresses() (#9569)"
This reverts commit 3b62fbe365.
2022-10-03 16:15:51 -07:00
Alexander Polcyn 114e1dfbf7 google-c2p resolver: add authority entry to bootstrap config 2022-09-30 15:25:50 -07:00
Eric Anderson 85bdca45fa Bump Protobuf to 3.21.7 2022-09-30 14:02:45 -07:00
sanjaypujare ba8cd04191
xds: rename ClientXdsClient to XdsClientImpl (#9573) 2022-09-30 09:32:52 -07:00
Terry Wilson 3b62fbe365
rls: use acceptResolvedAddresses() (#9569)
Switch over from handleResolvedAddresses as part of a LoadBalancer
public API refactoring.
2022-09-29 12:51:31 -07:00
Sergii Tkachenko eaf8b28930
netty: create adaptive cumulator (#9558)
Creates "Adaptive" cumulator: cumulate ByteBuf's by dynamically switching between merge and compose strategies.

This cumulator applies a heuristic to make a decision whether to track a reference to the buffer with bytes received from the network stack in an array ("zero-copy"), or to merge into the last component (the tail) by performing a memory copy.

It is necessary as a protection from a potential attack on the COMPOSITE_CUMULATOR. Consider a pathological case when an attacker sends TCP packages containing a single byte of data, and forcing the cumulator to track each one in a separate buffer. In this case we'll be paying a memory overhead for each buffer, as well as extra compute to read the cumulation.

Implemented heuristic establishes a minimal threshold for the total size of the tail and incoming buffer, below which they are merged. The sum of the tail and the incoming buffer is used to avoid a case where attacker alternates the size of data packets to trick the cumulator into always selecting compose strategy.

Merging strategy attempts to minimize unnecessary memory writes. When possible, it expands the tail capacity and only copies the incoming buffer into available memory. Otherwise, when both tail and the buffer must be copied, the tail is reallocated (or fully replaced) with a new buffer of exponentially increasing capacity (bounded to minComposeSize) to ensure runtime O(n^2) amortized to O(n).

Note: this reintroduces https://github.com/grpc/grpc-java/pull/7532, addressing the subtle issue (ref b/155940949) with `CompositeByteBuf.component()` indexes getting out of sync, which results in the merge operation producing broken buffers.
2022-09-27 19:21:46 -07:00
Eric Anderson 5b62d22802 Start 1.51.0 development cycle 2022-09-26 16:37:56 -07:00
Eric Anderson e998955d1d xds: Avoid NPE from update after removing subscriptions
This fixes a regression in commit e1ad984. I'd create a test, but the
NPE gets thrown away in the context of the current test setup so can't
be created as quickly as we'd like to fix this. I have manually tested
in a custom reproduction to confirm it resolves the NPE.

Seen at b/248326695

```
java.lang.AssertionError: java.lang.NullPointerException
        at io.grpc.xds.ClientXdsClient$1.uncaughtException(ClientXdsClient.java:89)
        at io.grpc.SynchronizationContext.drain(SynchronizationContext.java:97)
        at io.grpc.SynchronizationContext.execute(SynchronizationContext.java:127)
        at io.grpc.xds.ClientXdsClient.cancelXdsResourceWatch(ClientXdsClient.java:327)
        at io.grpc.xds.ClusterResolverLoadBalancer$ClusterResolverLbState$EdsClusterState.shutdown(ClusterResolverLoadBalancer.java:378)
        at io.grpc.xds.ClusterResolverLoadBalancer$ClusterResolverLbState.shutdown(ClusterResolverLoadBalancer.java:206)
        at io.grpc.util.GracefulSwitchLoadBalancer.shutdown(GracefulSwitchLoadBalancer.java:195)
        at io.grpc.xds.ClusterResolverLoadBalancer.shutdown(ClusterResolverLoadBalancer.java:141)
        at io.grpc.xds.CdsLoadBalancer2$CdsLbState.shutdown(CdsLoadBalancer2.java:136)
        at io.grpc.xds.CdsLoadBalancer2.shutdown(CdsLoadBalancer2.java:110)
        at io.grpc.util.GracefulSwitchLoadBalancer.shutdown(GracefulSwitchLoadBalancer.java:195)
        at io.grpc.xds.ClusterManagerLoadBalancer$ChildLbState.shutdown(ClusterManagerLoadBalancer.java:256)
        at io.grpc.xds.ClusterManagerLoadBalancer.shutdown(ClusterManagerLoadBalancer.java:138)
        at io.grpc.internal.AutoConfiguredLoadBalancerFactory$AutoConfiguredLoadBalancer.shutdown(AutoConfiguredLoadBalancerFactory.java:164)
        at io.grpc.internal.ManagedChannelImpl.shutdownNameResolverAndLoadBalancer(ManagedChannelImpl.java:381)
        at io.grpc.internal.ManagedChannelImpl.access$8200(ManagedChannelImpl.java:118)
        at io.grpc.internal.ManagedChannelImpl$DelayedTransportListener.transportTerminated(ManagedChannelImpl.java:2174)
        at io.grpc.internal.DelayedClientTransport$3.run(DelayedClientTransport.java:122)
        at io.grpc.SynchronizationContext.drain(SynchronizationContext.java:95)
        at io.grpc.SynchronizationContext.execute(SynchronizationContext.java:127)
        at io.grpc.internal.ManagedChannelImpl$RealChannel.shutdown(ManagedChannelImpl.java:1057)
        at io.grpc.internal.ManagedChannelImpl.shutdown(ManagedChannelImpl.java:817)
        at io.grpc.internal.ManagedChannelImpl.shutdownNow(ManagedChannelImpl.java:837)
        at io.grpc.internal.ManagedChannelImpl.shutdownNow(ManagedChannelImpl.java:117)
        at io.grpc.internal.ForwardingManagedChannel.shutdownNow(ForwardingManagedChannel.java:52)
        at io.grpc.internal.ManagedChannelOrphanWrapper.shutdownNow(ManagedChannelOrphanWrapper.java:65)
        at io.grpc.testing.integration.GrpclbFallbackTestClient.tearDown(GrpclbFallbackTestClient.java:178)
        at io.grpc.testing.integration.GrpclbFallbackTestClient.main(GrpclbFallbackTestClient.java:67)
Caused by: java.lang.NullPointerException
        at io.grpc.xds.ClientXdsClient.handleResourceResponse(ClientXdsClient.java:179)
        at io.grpc.xds.AbstractXdsClient$AbstractAdsStream.handleRpcResponse(AbstractXdsClient.java:358)
        at io.grpc.xds.AbstractXdsClient$AdsStreamV3$1$1.run(AbstractXdsClient.java:511)
        at io.grpc.SynchronizationContext.drain(SynchronizationContext.java:95)
        ... 26 more
```
2022-09-26 16:37:37 -07:00
sanjaypujare 6f8e44a7f5
xds: security code refactoring/renaming (#9555)
* xds: security code refactoring/renaming
1) move certprovider package under security
2) refactor inner Factory into  CertProviderClientSslContextProviderFactory and CertProviderServerSslContextProviderFactory
3) Make CertProviderClientSslContextProvider and CertProviderServerSslContextProvider non-public
4) use only public (non package private) types like SslContextProvider (instead of CertProviderClientSslContextProvider etc)
2022-09-24 00:05:15 -07:00
sanjaypujare 0cda133c52
observability: replace current OpenCensus registerAllGrpcViews with only selected views for GCP observability (#9561) 2022-09-23 13:24:27 -07:00
Terry Wilson 2289956ec7
core: outlier_detection LB to use acceptResolvedAddresses() (#9557)
Switch OutlierDetectionLoadBalancer to implement
acceptResolvedAddresses() to allow for the eventual deprecation of
handleResolvedAddresses().
2022-09-19 20:20:08 -07:00
apolcyn 8925696b3e
Revert "xds: prevent concurrent priority LB picker updates (#9363)" (#9554)
This reverts commit bcf5cde7dd.
2022-09-19 08:29:41 -07:00
yifeizhuang e1ad984db3
xds: refactor xds client to make it resource agnostic (#9444)
Mainly refactor work to make type specific xds resources generic, e.g.
1. Define abstract class XdsResourceType to be extended by pluggable new resources. It mainly contains abstract method doParse() to parse unpacked proto messges and produce a ResourceUpdate. The common unpacking proto logic is in XdsResourceType default method parse()
2. Move the parsing/processing logics to specific XdsResourceType. Implementing:
XdsListenerResource for LDS
XdsRouteConfigureResource for RDS
XdsClusterResource for CDS
XdsEndpointResource for EDS
3. The XdsResourceTypes are singleton. To process for each XdsClient, context is passed in parameters, defined by XdsResourceType.Args.
4. Watchers will use generic APIs to subscribe to resource watchXdsResource(XdsResourceType, resourceName, watcher). Watcher and ResourceSubscribers becomes java generic class.
2022-09-16 10:08:16 -07:00
yifeizhuang a3c1d7711f
okhttp: add okhttpServerBuilder permitKeepAliveTime() and permitKeepAliveWithoutCalls() for server keepAlive enforcement (#9544) 2022-09-15 16:08:55 -07:00
Terry Wilson 15033caf1c
core: pick_first LB to use acceptResolvedAddresses() (#9548) 2022-09-15 14:21:10 -07:00
Terry Wilson 79c4c355ba
okhttp: Fair treatment when writing out streams (#9545)
When allocating bytes to streams within a flow control window we always
go through the streams in the same order. This can lead to large streams
hogging all the bytes and a smaller one down the list getting starved
out. This change shuffles the stream array to lower the chance of this
happening.

Fixes #9089
2022-09-15 09:35:23 -07:00
Terry Wilson 341fea8996
core: Convert inappropriate call cred errors (#9543)
If a CallCredentials implementation returns an error that is not
appropriate to propagate from the control plane to the data plane, we
convert it to an INTERNAL error. This makes the inappropriate control
plane behavior to be discoverable in the logs.

https://github.com/grpc/proposal/blob/master/A54-restrict-control-plane-status-codes.md
2022-09-13 13:36:40 -07:00
Terry Wilson 944cbf84ed
core: Comment on "inappropriate" service config errors (#9542)
https://github.com/grpc/proposal/blob/master/A54-restrict-control-plane-status-codes.md
2022-09-13 09:57:55 -07:00
Kun Zhang 38b338228a
core: add getCallOptions() to CallCredentials.RequestInfo (#9538)
This is needed internally (b/134067789#comment20).
2022-09-13 08:55:05 -07:00
Terry Wilson 9853a0c463
core: Don't delegate inappropriate ConfigSelector errors (#9536)
In case a control plane returns an "inappropriate" response code, it is converted to INTERNAL to highlight the bug in the control plane.

https://github.com/grpc/proposal/blob/master/A54-restrict-control-plane-status-codes.md
2022-09-12 13:17:16 -07:00
Terry Wilson bcf5cde7dd
xds: prevent concurrent priority LB picker updates (#9363)
If a child policy triggers an update to the parent priority policy
it will be ignored if an update is already in process.
2022-09-12 11:17:51 -07:00
Eric Anderson bacf18db8d
census: Avoid deprecated measure constants
Many of the deprecated constants are just aliases for non-deprecated
constants, so just swap which one we use.
2022-09-12 08:19:21 -07:00
yifeizhuang 42e68149a5
xds: ringhash policy in TRANSIENT_FAILURE should not attempt connecting when already in connecting (#9535) 2022-09-09 17:27:22 -07:00
Terry Wilson 84d0b0474f
core: Replace inappropriate picker result status codes (#9530)
Certain status codes are inappropriate for a control plane to be
returning and indicate a bug in the control plane. These status codes
will be replaced by INTERNAL, to make it clearer to see that the control
plane is misbehaving.
2022-09-09 15:46:28 -07:00
yifeizhuang eac4178eaa
okhttp: add max connection idle at OkHttpServer and fix test (#9533)
* Revert "Revert "okhttp: add max connection idle at OkHttpServer (#9494)" (#9528)"

This reverts commit 95b9d6db29 and fixed flaky test.
2022-09-09 12:53:47 -07:00
sanjaypujare 88a035e2c2
xds: rename package io.grpc.xds.internal.sds to io.grpc.xds.internal.security (#9532) 2022-09-09 09:21:03 -07:00
Eric Anderson 24287b0b14 binder: Fix expected result of security test
The test name includes "fails" but it asserts the result is OK. The test
was added in #9428.

The binder tests are passing on the Android CI, but for some reason the
tests with sdk >= 29 are skipped. Robolectric 4.8 claims API level 32
support and the tests are skipped even when using Java 11 and 17.
2022-09-09 09:18:43 -07:00
sanjaypujare 074e919304
xds: rename Sds to Security or Xds in various classes to eliminate references to SDS (#9529) 2022-09-08 09:35:03 -07:00
yifeizhuang 95b9d6db29
Revert "okhttp: add max connection idle at OkHttpServer (#9494)" (#9528)
This reverts commit 7291ad44c6.
2022-09-08 08:51:16 -07:00
Terry Wilson 53a2d50695
xds: always update priority LB connectivity state (#9527)
Removes the option of skipping the update of the priority LB state when
the failover timer is pending.

This consistency facilitates a future change weher we delay child LB
status updates if the priority LB is performing an update. The upcoming
priority LB policy gRFC also does not require this update to ever be
skipped.
2022-09-08 08:49:07 -07:00
Chris Povirk 6bafca93a7
core: Use real ByteBuffer instead of mock (#9523)
My motivation for making this change is that [`ByteBuffer` is becoming
`sealed`](https://download.java.net/java/early_access/loom/docs/api/java.base/java/nio/ByteBuffer.html)
in new versions of Java. This makes it impossible for Mockito's
_current_ default mockmaker to mock it.

That said, Mockito will likely [switch its default
mockmaker](https://github.com/mockito/mockito/issues/2589) to an
alternative that _is_ able to mock `sealed` classes. However, there are
downside to that, such as [slower
performance](https://github.com/mockito/mockito/issues/2589#issuecomment-1192725206),
so it's probably better to leave our options open by avoiding mocking at
all.

And in this case, it's equally easy to use real objects.

As a bonus, I think that real objects makes the code a little easier to
follow: Before, we created mocks that the code under test never
interacted with in any way. (The code just passed them through to a
delegate.) When I first read the tests, I was confused, since I assumed
that the mock we were creating was the same mock that we then passed to
`verify` at the end of the method. That turned out not to be the case.
2022-09-07 15:50:31 -07:00
Larry Safran 5946eb0d6a
style fix (#9526) 2022-09-07 14:58:42 -07:00
Prateek Karandikar 0fd5751679
Add security policies for checking device owner/profile owner. (#9428) 2022-09-06 20:31:49 -07:00
Terry Wilson bf692c04e6
Add custom_lb to the test suites. (#9502)
Co-authored-by: Sergii Tkachenko <hi@sergii.org>
2022-09-06 15:49:49 -07:00
Terry Wilson 2ee65a9c26
core: Don't forward acceptResolvedAddresses() (#9511)
Forwarding acceptResolvedAddresses() to a delegate in ForwardingLoadBalancer can cause problems if an extending class expects its handleResolvedAddresses implementation to be called even when a client calls handleResolvedAddresses(). This would not happen as ForwardingLoadBalancer would directly send the call to the delegate.
2022-09-06 13:06:48 -07:00
Sergii Tkachenko c8c3d3d6b2
xDS interop: enable pod log collection in the buildscripts (#9495)
- Enables pod log collection in all PSM interop jobs implemented
  in https://github.com/grpc/grpc/pull/30594.
- Associate test suite runs with their own log file, so it's displayed
  on the "Target Log" tab
- Updates security job to not stop after a failed suite, so that
  authz_test run even if security_test failed
- Fix run_test not returning correct exit status, causing false
  positives in some cases. See https://github.com/grpc/grpc/pull/30768
2022-09-06 11:18:27 -07:00
Larry Safran c27f2d5a57
[core,api,auth: Choose executor based on need for thread affinity (#9504)
* core,api,auth: Choose the callOptions executor when applying request metadata to credentials during newStream based upon whether AppEngineCredentials are being used as they require a specific thread to do the processing.

Add an interface to differentiate whether the specific thread is needed.

Fixes b/244209681
2022-09-02 21:55:38 -07:00
yifeizhuang 0a699ad694
netty: upgrade netty from 4.1.77.Final to 4.1.29.Final and tcnative from 2.0.53 to 2.0.54 (#9451) 2022-08-31 16:02:27 -07:00
Terry Wilson 1f33fe6383
core: Assure that context cancellationCause is set (#9501)
core: Assure that context cancellationCause is set

Makes sure that whenever a context is in a cancelled state, we also have
a cancellationCause.
2022-08-31 10:43:22 -07:00
Terry Wilson 4b4cb0bd3b
api,core: Add LoadBalancer.acceptResolvedAddresses() (#9498)
Introduces a new acceptResolvedAddresses() method in LoadBalancer that
is to ultimately replace the existing handleResolvedAddresses(). The new
method allows the LoadBalancer implementation to reject the given
addresses by returning false from the method.

The long deprecated handleResolvedAddressGroups is also removed.
2022-08-31 08:36:50 -07:00
Eric Anderson 8dbff5ba6a core: DelayedClientCall should propagate context
This was already being done for the Listener, but it was missed for the
ClientCall draining itself. That's not too surprising, since very few
things should be looking at the context in that path. We don't care too
much about this client call case, but if the context _does_ end up
mattering it could be painful to debug.

Fixes #9478
2022-08-30 16:42:46 -07:00
sanjaypujare b778947ca6
istio-interop-testing: increase deadline to 5 sec to avoid deadline issue on aarch64 (#9497) 2022-08-30 09:32:52 -07:00
yifeizhuang 7291ad44c6
okhttp: add max connection idle at OkHttpServer (#9494) 2022-08-29 16:25:58 -07:00
Terry Wilson db05295fde
core: Enable outlier detection unit test (#9493)
Implements a fake load balancer with round robin like behavior in order
to test an outlier detection scenario where a subchannel goes from
having multiple associated addresses to one.
2022-08-29 15:23:41 -07:00
sanjaypujare 6131a85196
census,observability: suppress message-events in traces when used by observability (#9485) 2022-08-26 16:39:54 -07:00
yifeizhuang 96b9fc1be4 fix 2022-08-25 12:53:11 -07:00
yifeizhuang 221ee494d9 move max connection idle manager to core 2022-08-25 12:53:11 -07:00
Terry Wilson d3331d953d
core: outlier detection max ejection logic update (#9492)
Stop further ejection if the ejection percentage is lesser than or equal
to the maximum ejection percentage. Previously this was only done when
the current ejection percentage was lesser than the maximum.
2022-08-25 10:48:28 -07:00
Terry Wilson 70bc7470c6
core: outlier detection to min host request volume (#9490)
When doing the failure percentage algorithm, ejections should be skipped
if there are not enough addresses that meet the minimum volume
requirement.
2022-08-24 15:49:01 -07:00
Terry Wilson a74f82ac26
core: Update outlier detection max ejection logic. (#9489)
Instead of strictly enforcing the max ejection percentage setting,
allow one additional ejection past the maximum. This quarantees at least
one ejection and matches Envoy proxy behavior.
2022-08-24 14:44:28 -07:00
Terry Wilson bd33af2dde
Update README etc to reference 1.49.0 (#9487) 2022-08-24 12:11:08 -07:00
Sergii Tkachenko 0cf2d8bc48
context: Skip storageReturnsNullTest for JDK >= 11 (#9484)
JDK-8210522 changes the behaviour of Java reflection to filter out
security-sensitive fields in the java.lang.reflect.Field. This
prohibits Field.class.getDeclaredFields("modifiers") call we rely on
in this test. Until we have a good solution for setting a custom
storage for testing purposes, we'll have to skip this test
for JDK >= 11. Ref https://bugs.openjdk.org/browse/JDK-8210522
2022-08-24 10:17:12 -07:00
Sergii Tkachenko e1ddc3553f
example-android: Add android:exported="true" tag (#9482)
Add android:exported="true" tag to activities/services/receivers that specify an intent filter.

Apps targeting Android 12 and higher are required to specify an explicit value for `android:exported` when the corresponding component has an intent filter defined. Future versions of the manifest merger, as well as the Android platform and the Playstore enforce this.
2022-08-23 14:56:03 -07:00
Eric Anderson 95508e19df binder: Exclude internal classes from javadoc 2022-08-23 11:42:25 -07:00
Terry Wilson d4cd926c96
core: Enable outlier detection by default. (#9479) 2022-08-23 11:32:10 -07:00
Terry Wilson 1dd764a3a1
buildscripts: Add outlier_detection_test interop test. (#9461) 2022-08-22 14:27:20 -07:00
Terry Wilson b16e0e34a4
core: [outlier detection] eject/uneject states to delegate listener. (#9469) 2022-08-22 11:34:50 -07:00
Terry Wilson fbefdf5ea7
core: [outlier detection] Get addresses from subchannel args. (#9468) 2022-08-22 11:12:51 -07:00
Terry Wilson f5670b39c4
core: OutlierDetectionLoadBalancer to pass child LB config. (#9467) 2022-08-22 10:29:57 -07:00
Terry Wilson 9ed5a1bbbf
xds: Fix outlier detection env flag name. (#9462) 2022-08-21 16:13:31 -07:00
DNVindhya 20ab369f3a
gcp-observability: update configuration variable to enable cloud tracing (#9463) 2022-08-19 17:09:17 -07:00
Eric Anderson 2a364838be googleapis: Stabilize google-c2p resolver
Preserve google-c2p-experimental support for the moment to ease testing
migration.
2022-08-19 13:38:27 -07:00
Larry Safran b66250e9e5
Rls spec sync (#9437)
rls: Update implementation to match spec.

* Cleanup cache if exceeds max size when add an entry. Make cache entry size calculations more accurate
* Trigger pending RPC processing if unexpired backoff entries were removed from the cache by triggering helper to call it's parent updateBalancingState with the same state and picker
* Introduce minimum time before eviction (5 seconds)
* Change default accept ratio for AdaptiveThrottler from 1.2 -> 2.0
* Configuration validation
* When checking key names for duplicates also look at headers
* Check extra keys for duplicates

See analysis of implementation versus spec at https://docs.google.com/spreadsheets/d/18w5s1TEebRumWzk1pvWnjiHFGKc6MW-vt8tRLY4eNs0/
2022-08-19 13:31:05 -07:00
Eric Anderson 618a4de705
xds: CHANNEL_ID hash should be random for the channel
The log id is an incrementing value starting from 0. That means the same
binary on two different machines will have the same hashes for each
consecutive Channel. That was not at all the intension of CHANNEL_ID.
From gRFC A42:

> This can be used in similar situations to where Envoy uses
> connection_properties to hash on the source IP address.
2022-08-18 17:27:15 -07:00
Terry Wilson 81abb21e7f
xds: Configure outlier detection. (#9456)
Enables the new OutlierDetectionLoadBalancer when outlier detection is enabled
in the xDS cluster configuration.
2022-08-18 16:06:17 -07:00
Terry Wilson 128688ae4d
Outlier detection load balancer (#9447)
New outlier detection load balancer.

Tracks all RPC results to the addresses it is configured with and periodically attempts
to detect outlier. It wraps a child load balancer from which it hides any addresses that
are deemed outliers.

As specified in gRFC A50: gRPC xDS Outlier Detection Support:
https://github.com/grpc/proposal/blob/master/A50-xds-outlier-detection.md
2022-08-18 08:46:30 -07:00
Larry Safran 778098b911
rls: fix RLS policy to not propagate status from control plane RPC to data plane RPC (#9413)
rls: Avoid library returning the status codes which the status spec document says that the library will never return when talking to RLS server.  Instead, always return UNAVAILABLE on errors.

* Provide context around error message from RLS server
2022-08-15 11:10:10 -07:00
Larry Safran 01d5bd47cb
Cleanup some of the warnings across the code base (#9445)
No logic changes, just cleans up warnings to make spotting real problems easier.

Remove "public" declarations on interfaces
Remove duplicate semicolons (Java lines ending in ";;")
Remove unneeded import
Change non-javadoc comment to not start with "/**"
Remove unneeded explicit type declarations from generics
Fix broken javadoc links
2022-08-15 11:06:31 -07:00
DNVindhya 03430c786a
remove unregistering stackdriver exporters (#9442) 2022-08-12 12:20:43 -07:00
sai-sunder-s 7169b174e6
auth: Copy quota project id when creating Self Signed JWT creds from Service Account Creds (#9438) 2022-08-11 13:20:51 -07:00
sanjaypujare 91aada316a
gcp-observability: implement exclusion of cloud backend RPCs for all 3 signals (#9427)
* gcp-observability: implement exclusion of cloud backend RPCs for all 3 signals
by using a ConditionalClientInterceptor that conditionally delegates
2022-08-10 14:19:27 -07:00
Eric Anderson 61f19d707a
Swap Animalsniffer to Java 8 and Android 19
Also added missing signatures. Swapping to version catalog will make
this process easier in the future.
2022-08-10 12:41:57 -07:00
Eric Anderson 2b50e405b1 core: Remove LB refreshNameResolver check
It's been 17 months since the check was introduced, which is plenty for
the migration. Leaving ignoreRefreshNameResolutionCheck() in-place to
let users delete their call sites. We'll remove the method after a few
releases.

Fixes #9409
2022-08-10 10:26:15 -07:00
Terry Wilson 01aff58178
Start 1.50.0 development cycle (#9433) 2022-08-10 08:17:59 -07:00
DNVindhya 7bdca0c0ef
gcp-observability: remove logging channel/server providers (#9424) 2022-08-09 21:08:01 -07:00
yifeizhuang 050cdb14fe Update README etc to reference 1.48.1 2022-08-02 15:47:29 -07:00
Eric Anderson db320cefc1
repositories.bzl: Use valid target name for services/xds
This fixes builds including dependencies from Maven that use
io.grpc:grpc-services or io.grpc:grpc-xds. It resolves this error:
```
no such target '@io_grpc_grpc_java//services:services': target 'services' not declared in package 'services' defined by services/BUILD.bazel and referenced by '@maven//:io_grpc_grpc_services'
```

Fixes #9419
2022-08-02 10:28:44 -07:00
Sergii Tkachenko e26b6ee1d7
xds: Refactor and document `ClientXdsClient.handleResourceUpdate()` (#9377)
- Reduce nesting level by using `continue`
- Rearrange the order when it's possible to bail out early
- Add comments explaining what case it is, and the logic behind it
2022-07-29 16:55:27 -07:00
Terry Wilson 7665d3850b
Revert "Add LoadBalancer.acceptResolvedAddresses() (#8742)" (#9414)
This reverts commit 70a29fbfe3.
2022-07-28 12:15:26 -07:00
sanjaypujare e3d5861273
istio-interop-testing: add logic to forward non-grpc requests to the Go echo server (#9385) 2022-07-27 14:31:33 +05:30
Terry Wilson 70a29fbfe3
Add LoadBalancer.acceptResolvedAddresses() (#8742)
Introduces a new acceptResolvedAddresses() to the LoadBalancer.

This will now be the preferred way to handle addresses from the NameResolver. The existing handleResolvedAddresses() will eventually be deprecated.

The new method returns a boolean based on the LoadBalancers ability to use the provided addresses. If it does not accept them, false is returned. LoadBalancer implementations using the new method should no longer implement the canHandleEmptyAddressListFromNameResolution(), which will eventually be removed, along with handleResolvedAddresses().

Backward compatibility will be maintained so existing load balancers using handleResolvedAddresses() will continue to work.

Additionally the previously deprecated handleResolvedAddressGroups() method is removed.
2022-07-26 09:23:37 -07:00
sanjaypujare e89d43dde6
gcp-observability: add custom tags to metrics and traces using Stackdriver config-builders (#9407) 2022-07-26 21:27:46 +05:30
yifeizhuang cc9505f6bc
example-orca: fix lost streamTracerFactor (#9411) 2022-07-25 16:28:58 -07:00
yifeizhuang 5f1a1d4f35
service: CalMetricRecorder.recordCallMetric is deprecated, use CalMetricRecorder.recordRequestCostMetric (#9410) 2022-07-25 13:10:29 -07:00
sanjaypujare 1fe3ed9b53
xds: use predefined XdsLbPolicies constants instead of string literals for consistency (#9408) 2022-07-25 22:35:08 +05:30
sanjaypujare 10979b2e2c
gcp-observability: add custom tags for all 3 - metrics, logging, traces and remove old env-vars impl (#9402)
* gcp-observability: add custom tags for all 3 - metrics, logging, traces and remove old env-vars impl
2022-07-23 01:32:18 +05:30
yifeizhuang 027d36eee7
xds: xdsNameResolver match channel overrideAuthority in virtualHost matching (#9405) 2022-07-22 12:41:16 -07:00
yifeizhuang 58cd6e1a7f
example: fix orca example to use new ORCA API (#9403) 2022-07-22 07:40:49 -07:00
Terry Wilson 4850ad219e
xds: ClusterManager LB state/picker update fix (#9404)
* xds: ClusterManager LB state/picker update fix

Correctly set the currentState and curentPicker when the
child LB updates balancing state
2022-07-21 13:54:40 -07:00
Larry Safran dcac7689fa
rls: Change AdaptiveThrottler to use Ticker instead of TimeProvider (#9390)
rls: Change AdaptiveThrottler to use Ticker instead of TimeProvider
* Use a slot being null to mark invalid rather than relying on the slot's endNanos value.

Fixes #9048
2022-07-21 11:41:02 -07:00
Larry Safran 50cdfa9f05
rls: Only use subchannel policy for default target when RLS is not available (#9383)
* core: Only use subchannel policy for default target when RLS is not available
Fixes #9237
2022-07-20 17:20:19 -07:00
yifeizhuang 03abe8a088
Update README etc to reference 1.48.0 (#9401) 2022-07-20 15:36:22 -07:00
Larry Safran 98ce51ab5c
rls: Support multiple returned targets from RLS Server (#9374)
* rls: Support multiple returned targets from RLS Server
Pick the first target that is not in TRANSIENT_FAILURE state.  If none, use the first target.
Also initialize all targets returned from RLS so DataCache will contain a list of child policy wrappers.

Fixes #9236
2022-07-20 11:11:19 -07:00
Eric Anderson 0e45e04041
Avoid accidental locale-sensitive String.format()
%s is fairly safe (requires a Formattable to use Locale), so %d is the
main risk item. Places that really didn't need to use String.format()
were converted to plain string concatenation. Logging locations were
generally converted to using the log infrastructure's delayed
formatting, which is generally locale-sensitive but we're okay with
that. That wasn't done in okhttp, however, because Android frequently
doesn't use MessageFormat so we'd lose the parameters. Everywhere else
was explicitly defined to be Locale.US, to be consistent independent of
the default system locale.
2022-07-19 14:41:34 -07:00
Larry Safran 7568f8cce7
core: Disable retry by default for in-process transport's channel (#9361)
See #8712
2022-07-19 12:35:52 -07:00
Sergii Tkachenko 4aa9b92551
buildscripts: Fix kube contexts in the xds LB tests (#9389)
- The primary should've been `GKE_CLUSTER_PSM_LB`
- The secondary cluster was not activated for LB tests. This resulted
  in the failover test failing, as it relies on workloads running in
  different zones.
2022-07-18 17:40:46 -07:00
Sergii Tkachenko 10449d63bc Revert "buildscripts: Add missing secondary_kube_context to xds LB tests (#9380)"
This reverts commit e3e152a449.
2022-07-18 15:28:35 -07:00
yifeizhuang 756fdf3f2c
service: make the orca MetricReport a top level experimental class (#9382) 2022-07-18 13:23:55 -07:00
Sergii Tkachenko e3e152a449
buildscripts: Add missing secondary_kube_context to xds LB tests (#9380)
Secondary cluster was not activated for LB tests. This resulted in the failover test failing, as it relies on workloads running in different zones.

ref b/238226704
2022-07-15 16:03:48 -07:00
apolcyn 267d15412f
interop client: fix soak test bug where we can crash if peer wasn't set 2022-07-15 15:54:54 -07:00
Eric Anderson 4cb1fbaa9f
core: Workaround retry causing memory leak
Data is getting orphaned sitting in MessageFramer. This hack thus always
flushes data out of the framer so no data can remain sitting there.

See #9340
2022-07-15 15:25:27 -07:00
yifeizhuang 6609f11f48
xds: do not expose orca proto in ORCA api (#9366)
The fix avoids shaded dependency of orca protos
2022-07-15 09:41:50 -07:00
Eric Anderson 55fd6268c6 Revert "Fix for ipv6 link local with scope (#9326)"
This reverts commit c1abc7f8ac. It
produced compilation issues inside Google. I strongly suspect it isn't
this commit or gRPC's fault, but it prevents further testing until it is
resolved.
2022-07-14 11:41:01 -07:00
Benjamin Peterson 50ebb5f864
api: Link to Status#asRuntimeException method in StatusRuntimeException javadocs. (#9373) 2022-07-14 21:04:25 +05:30
DNVindhya ef89bd3ac9
gcp-observability: Populate global interceptors from observability (#9309)
* Populate global interceptors from observability and added stackdriver exporters
2022-07-14 19:38:00 +05:30
Terry Wilson 49f555192d
xds: cluster manager to delay picker updates (#9365)
Do not perform picker updates while handling new addresses even if child
LBs request it. Assure that a single picker update is done.
2022-07-13 15:54:49 -07:00
Eric Anderson eb25807d43 okhttp: Avoid default locale in String.format() 2022-07-13 11:10:22 -07:00
yifeizhuang f9d5ce7e7a
core: server stream should not deliver halfClose() when call is immediately cancelled(#9362)
Fix a bug where the server stream delivers halfClose() to the call during cancellation. It happens when call has a short deadline. Server sees `INTERNAL, desc: Half-closed without a request` due to the bug.
2022-07-11 17:33:57 -07:00
Eric Anderson 9cd17ce3a7 Fix Gradle UP-TO-DATE checking for all tasks
The two checker tasks run quickly so don't gain much from UP-TO-DATE,
but it is convenient to not see them in the noise (checkUpperBoundDeps
in particular). Gradle only performs UP-TO-DATE checks (on the inputs)
if the task has both inputs and outputs defined.

The biggest saving was for distZip/distTar/shadowDistZip/shadowDistTar
which were using the same name for the non-shadow and shadow versions.
Thus the output file would always be out-of-date because it had been
rewritten and was invalid. This is worrisome because we could have
"randomly" been using the shadow Zip/Tar at times and the non-shadow
ones at others, although I think in practice the shadow tasks always run
last and so those are the files we'd see. Changing the classifier avoids
the colliding file names. These tasks took ~7 seconds, so incremental
builds are considerably shorter now.
2022-07-11 11:06:10 -07:00
Eric Anderson 57fe766d10 interop-testing: Hack runtimeOnly deps to be available at runtime
RuntimeOnly dependencies have been missing since 3624d59. This is
because the implementation configuration extendsFrom the shadow
configuration, so any of the things like runtimeOnly are being lost.
This change isn't "correct" but it stops the bleeding with minimal cost.
It is probably incorrect to be using shadow plugin in interop-testing at
all.
2022-07-11 10:31:40 -07:00
Sergii Tkachenko d7a6c1ea31
xds: Allow Gradle to use more memory when building interop - GCE (#9354)
Same as #9347, but for GCE framework too (xds and xds_v3 jobs).

Should fix "Expiring Daemon because JVM heap space is exhausted".

PR #9269 probably pushed the build
over the edge, but there's been evidence via flakes for a good while
that we've been reaching the limit.

b/238334438
2022-07-08 19:28:23 -07:00
Sergii Tkachenko fe1cfc9b96
okhttp: Comment out VisibleForTesting annotation (#9352)
Android linters can't recognize the difference when VisibleForTesting
is used because the method has different visibility, or because
the method only intended for testing.

Because of that linter complains when VisibleForTesting methods are
used in the production code.

Ideally we want to replace or remove this annotation, as its
usage for marking altered visibility for testing purposes is
discouraged since guava v30.0.
2022-07-08 18:00:48 -07:00
Eric Anderson 19ad4467db Service config parse failures should be UNAVAILABLE
INVALID_ARGUMENT is propagated to the data plane if no previous config
is available. INVALID_ARGUMENT is reserved for application use; LBs
should pretty much use UNAVAILABLE exclusively.

While most of the changes are in xds, there do not appear to be likely
xds code paths that would propagate a bad status to the data plane.
Internal policies either don't use parseLoadBalancingPolicyConfig() and
instead have their configuration objects constructed directly or are
constructed transitively through the cluster manager which uses INTERNAL
if there's a child failure. There was a worrisome hole before this
commit for StatusRuntimeExceptions received by the cluster manager, but
the audit didn't find any locations throwing such an exception.
User-selected policies produce a NACK and are protected from the
existing xds client watcher paths. The worst that appears could happen
is the channel could panic (which uses INTERNAL) if a bug let a bad
configuration through.
2022-07-08 15:49:12 -07:00
Sergii Tkachenko ac23d33d72
xds: implement ignore_resource_deletion server feature (#9339)
As defined in the gRFC [A53: Option for Ignoring xDS Resource Deletion](https://github.com/grpc/proposal/blob/master/A53-xds-ignore-resource-deletion.md).

This includes semi-related changes:
* Refactor ClientXdsClientTestBase: extract verify methods for golden resources
* Parameterize ClientXdsClientV2Test and ClientXdsClientV3Test with ignoreResourceDeletion enabled and disabled
* Add FORCE_INFO and FORCE_WARNING levels to XdsLogLevel
2022-07-08 13:09:38 -07:00
Eric Anderson 5f9ef98173 xds: Allow Gradle to use more memory when building interop
Should fix "Expiring Daemon because JVM heap space is exhausted".

https://github.com/grpc/grpc-java/pull/9269 probably pushed the build
over the edge, but there's been evidence via flakes for a good while
that we've been reaching the limit.

b/238334438
2022-07-08 12:59:27 -07:00
Eric Anderson 0ff9f37b9e Use Gradle's task configuration avoidance APIs
This can avoid creating an additional 736 tasks (previously 502 out of
1591 were not created). That's not all that important as the build time
is essentially the same, but this lets us see the poor behavior of the
protobuf plugin in our own project and increase our understanding of how
to avoid task creation when developing the plugin. Of the tasks still
being created, protobuf is the highest contributor with 165 tasks,
followed by maven-publish with 76 and appengine with 53. The remaining
59 are from our own build, but indirectly caused by maven-publish.
2022-07-08 12:16:40 -07:00
Eric Anderson e767905f4a okhttp: Fix AsyncSink.close() NPE
This fixes a regression introduced in e96d0477. The NullPointerException
only happens on client-side when some other error occurred during
handshaking.

I tried to add a test, but SerializingExecutor catches+logs the
exception and the expected behavior in the circumstance is that close()
is a noop. So the NPE was entirely benign other than annoying log
messages.
2022-07-07 07:28:21 -07:00
Eric Anderson 3de7e74c57
xds: Build third-party protos in separate build step
This dramatically shortens build time, even for full builds. A full
assemble of xds on my laptop goes from 1m 46s to 33s at least because
errorprone is disabled for the protos.
2022-07-07 07:26:38 -07:00
Minsoo Cheong 1f1712c67c Update README.md broken link 2022-07-07 07:25:07 -07:00
Jader Alcântara c1abc7f8ac
Fix for ipv6 link local with scope (#9326) 2022-07-07 06:57:04 -07:00
Eric Anderson 3e09ea0068 xds: Fail RPCs with error details when resources are deleted
Previously if LDS/RDS were missing or improperly configured RPCs would
fail with "UNAVAILABLE: NameResolver returned no usable address errors".
That is very confusing and not helpful for debugging.

Ideally we'd also include the node id in this error message, but that's
a bit more involved and this is a huge improvement even without it.

b/237539851
2022-07-06 11:03:42 -07:00
Eric Anderson 2fc7ac441c interop-testing: Add cartesian product HTTP/2 interop test 2022-07-01 12:38:01 -07:00
Eric Anderson 2cb2fe5008 okhttp: Add support for file-based private keys 2022-07-01 12:38:01 -07:00
Eric Anderson bc50adf4b4 okhttp: Limit number of outstanding client-induced control frames 2022-07-01 12:38:01 -07:00
Eric Anderson e96d04774b okhttp: Add server implementation 2022-07-01 12:38:01 -07:00
Eric Anderson 0099b06739 Bump Bazel deps missed in fb314d3
fb314d3 bumped deps in Gradle, but forgot to bump those same deps in
Bazel.
2022-07-01 12:08:33 -07:00
Eric Anderson fb314d3631
Bump versions for assorted dependencies
If I didn't upgrade X there is probably a reason, but worst-case the
reason was "I was lazy." I did the easy stuff, so if upgrading caused
problems of any real sort I skipped it and moved on. The main other
reason is there's some stuff we're more conservative about upgrading,
but you can't distinguish one from the other in this commit.
2022-06-30 15:25:43 -07:00
Sergii Tkachenko 91fcc33243
buildscripts: Fix Xmx JVM flag propagation in GRADLE_OPTS
* buildscripts: Fix Xmx JVM flag propagation in GRADLE_OPTS
* buildscripts: double Java memory allocation pool

To reduce periodic OOMs of the "GitHub Actions Linux Testing / tests (11) (pull_request)" job.
2022-06-30 14:39:03 -07:00
Larry Safran 74137b0978
core: Use SyncContext for InProcessTransport listener callbacks to avoid deadlocks
Fixes deadlocks caused by client and server listeners being called in a synchronized block

Also support unary calls returning null values

Fixes #3084
2022-06-30 13:41:36 -07:00
Eric Anderson c0790283ec
Bump protobuf to 3.21.1 (#9311)
Fixes #9264
2022-06-30 11:18:49 -07:00
sanjaypujare c9a52eb83f
api,core: change ManagedChannel and Server Builders to use GlobalInterceptors (#9312)
* api,core: change ManagedChannel and Server Builders to use GlobalInterceptors
also added a getter in GlobalInterceptors to expose the set flag
2022-06-30 10:11:58 -07:00
sanjaypujare 6271bab20d
istio-interop-testing: create a separate project and add istio echo server code (#9321)
* istio-interop-testing: create a separate project and add istio echo server code
after removing from the grpc-interop-testing project

* add jib support

* use imported echo.proto from istio repo

* use context to propagate values from interceptor so the service's echo method has all values required to compose EchoResponse
2022-06-29 14:52:19 -07:00
yifeizhuang 377e3ce557
Start 1.49.0 development cycle (#9322) 2022-06-29 11:00:27 -07:00
Larry Safran b361ecfc65
core: Always pass offload executor to CallCredentials. never use the executor from CallOptions (#9313) 2022-06-28 13:29:22 -07:00
sanjaypujare 957d4e8b6f
Revert "interop-testing: add echo-server for proxyless gRPC testing in Istio (#9261)" (#9318)
This reverts commit c2d33f15be.
2022-06-27 17:30:47 -07:00
apolcyn 641746622e
interop-testing: add --soak_min_time_ms_between_rpcs flag and log peer addresses (#9282) 2022-06-27 16:31:25 -07:00
Eric Anderson fad38f49f1
Fix Channelz window reporting
Both Netty and OkHttp had local and remote windows flipped. Also, the
comment in OkHttp about "not tracked" wasn't true, so make it more
accurate and provide a _hint_ of what the window may be instead of just
-1.
2022-06-27 12:29:57 -07:00
Adil Ansari a07304471b stub: fix misspelled javadocs 2022-06-27 07:57:44 -07:00
yifeizhuang dc8954d442
xds: eds reuse priority names for the same existing locality (#9287) 2022-06-24 16:15:44 -07:00
sanjaypujare c2d33f15be
interop-testing: add echo-server for proxyless gRPC testing in Istio (#9261) 2022-06-24 15:20:14 -07:00
Terry Wilson 7bd0797496
all: Update netty to 4.1.77.Final and netty_tcnative to 2.0.53.Final (#9027)
all: Update netty to 4.1.77.Final and netty_tcnative to 2.0.53.Final

Also switches to a non-release version of rules_jvm_external to allow Bazel build to work with artifact classifiers.
2022-06-24 10:47:27 -07:00
lllu30 6193d209f0
binder: Add security Policy for verifying signature using sha-256 hash 2022-06-24 10:35:22 -07:00
Terry Wilson 79c607e5ac
xds: weighted target to delay picker updates while updating children (#9306) 2022-06-24 10:29:22 -07:00
amirhadadi 7b80954fd5 core,interop-testing: avoid flushing after writing a message in case the server returns a single response 2022-06-24 07:13:25 -07:00
Wenlong Zhang 334fc32034 Adding loongarch suport for grpc-java 2022-06-24 07:11:47 -07:00
sumitd2 04f9bdc1fd
compiler: Cross-compile for ppc64le platform (#9284)
Fixes #9274
2022-06-23 09:18:19 -07:00
Eric Anderson 69abec5a28
api: Explain security constraints of ATTR_AUTHORITY_OVERRIDE
Half of the text was copied from NameResolver.getServiceAuthority().
However, that method can't perform I/O (which would block) so more text
was appropriate here to mention the implications of having a remote
service provide the authority.

I noticed the text was lacking while discussing #9266.
2022-06-22 13:16:42 -07:00
Eric Anderson 8996702715 SECURITY.md: grpc version table should include future versions 2022-06-22 09:04:32 -07:00
Sergii Tkachenko 306d407493 Update MAINTAINERS.md
Add Larry; move Penn and Srini to emeritus
2022-06-21 17:04:56 -07:00
Eric Anderson 95d2f734be bazel: Support maven_install's strict_visibility=True
This seems like a poorly thought-out feature for maven_install in a
world where the dependency list is being combined from multiple
repositories, as it means all Bazel-aware dependencies must subscribe to
the idea this is good and useful. It also loses effectiveness as
transitive dependencies are likely to be included directly in
maven_install; users of gRPC can use netty, guava, and other
dependencies without explicitly defining them even with
strict_visibility=True. Given maven_install still complains
about "Found duplicate artifact versions", it isn't too surprising it
doesn't make sense in a multi-repo world.

This isn't a bad feature for gRPC as we are pretty low-level and it can
be helpful when making bazel dependency versions match gradle dependency
versions. But it doesn't necessarily seem like something we need to be
too worried about making sure we use. Similarly, don't use it in the
example as it seems low-value for our users.

Fixes #9288
2022-06-21 15:36:13 -07:00
yifeizhuang f0c934e4c1
interop-test: fix import, no cast to ServerStreamCallObserver (#9299) 2022-06-21 12:41:33 -07:00
Sergii Tkachenko 12984db6a7 kokoro: standard TESTING_VERSION in k8s framework build scripts
This Addresses the issue with skips not working due to the
missing/inconsistent `--testing_version` flag, ref b/235688697.

1. Uses the new `TESTING_VERSION` variable populated in the shared
grpc_xds_k8s_install_test_driver.sh - new approach for detecting
versions applicable to all languages.
2. Use `TESTING_VERSION` in all build files in `--testing_version` and
when tagging docker images. This will be backported to all active
test branches. Build Scripts in all other languages will be updated
as well.

Corresponding grpc core change: https://github.com/grpc/grpc/pull/30027
2022-06-21 09:08:24 -07:00
Kurt Alfred Kluever 1ed4b778e0 Tidy up @CheckReturnValue / @CanIgnoreReturnValue annotations
Includes pushing @CanIgnoreReturnValue annotations down from the
class-level to method-level.
2022-06-17 14:57:42 -07:00
yifeizhuang 630d63b7cc
interop-testing: add orca_oob lock to allow only one test client at a time to perform the test case (#9260) 2022-06-17 10:41:30 -07:00
larry-safran 8e7793652b
core: Use offloadExecutor for CallCredentials (#9263)
Change the construction of CallCredentialsApplyingTransportFactory in
ManagedChannelImpl to use the offloadExecutor as indicated in
https://github.com/grpc/grpc-java/issues/6279#issuecomment-1147507365 .
2022-06-14 18:44:02 -07:00
sanjaypujare 75aeccd385
xds: when delegate server throws on start communicate the error to statusListener (#9277) 2022-06-14 17:53:38 -07:00
Eric Anderson c1c69829db build.gradle: Clear Class-Path from shadowJar manifest
The generated Class-Path is simply wrong and it will actually be
attempted to be used at runtime.

Fixes #8606
2022-06-14 17:39:14 -07:00
Eric Anderson d2b05380de core: Clear ConfigSelector in panic mode
If the failure is before the NameResolver has returned the first time,
RPCs would be queued waiting for service config. We don't want to use
the ConfigSelector, as we are trying to circumvent the NameResolver and
LoadBalancer.

Fixes #9257
2022-06-14 17:38:27 -07:00
Eric Anderson b06942d63b Use Gradle's version catalog
This moves our depedencies into a plain file that can be read and
updated by tooling. While the current tooling is not particularly better
than just using gradle-versions-plugin, it should put us on better
footing. gradle-versions-plugin is actually pretty nice, but will be
incompatible with Gradle 8, so we need to wait a bit to see what the
future holds.

Left libraries as an alias for libs to reduce the commit size and make
it easier to revert if we don't end up liking this approach.

We're using Gradle 7.3.3 where it was an incubating fetaure. But in
Gradle 7.4 is became stable.
2022-06-14 14:04:10 -07:00
Eric Anderson 5b825e8b17 Remove classifiers from ext.libraries
Classifier can't be specified in version catalog.
2022-06-14 14:04:10 -07:00
sanjaypujare 428b541114
xds: delete the permanent error logic in processing LDS updates in XdsServerWrapper (#9268) 2022-06-13 12:44:35 -07:00
Terry Wilson c589441bde
xds: Support least_request LB in LoadBalancingPolicy (#9262) 2022-06-10 16:00:39 -07:00
Sergii Tkachenko a4a67b7fc7
testing: minor lint-suggested improvements (#9259)
Use for-each and Lists.reverse() instead of classic for
2022-06-10 15:42:51 -07:00
Sergii Tkachenko 9cebe0aa2b
api: Add missing RunWith annotation to GlobalInterceptorsTest (#9258)
Internal build failed with 

```
grpc/api/src/test/java/io/grpc/GlobalInterceptorsTest.java:28: error: 
[JUnit4RunWithMissing] Test class may not be run because it is missing a @RunWith annotation
public class GlobalInterceptorsTest {
       ^
  Did you mean '@RunWith(JUnit4.class)' or 'public abstract class GlobalInterceptorsTest {'?
```
2022-06-10 10:30:42 -07:00
yifeizhuang 0d6c40227b
interop-testing: skip empty orca updates for unary at the server (#9256) 2022-06-09 16:42:45 -07:00
DNVindhya 395fae59f0
api: Add GlobalInterceptors API (#9235)
* added GlobalInterceptors API
2022-06-09 16:27:25 -07:00
Eric Anderson 65bf2dc61b xds: Fix hash gen in RingHash when generating more than 10 hashes 2022-06-09 15:50:56 -07:00
Eric Anderson 97845fb72e testing: Have GrpcCleanupRule extend ExternalResource
This allows using GrpcCleanupRule with JUnit 5 when combined with
ExternalResourceSupport. We don't really lose anything important when
running with JUnit 4 and this eases migration to JUnit 5.

ExternalResource is now responsible for combining exceptions. after()
cannot throw checked exceptions, so we must now wrap the
InterruptedException. When used with JUnit 5 we are unable to detect the
test failed; we accept that for now but it may be fair to create a new
class for JUnit 5 to be used with `@RegisterExtension` that implements
BeforeEachCallback and AfterTestExecutionCallback to restore the JUnit 4
behavior.

See #5331
2022-06-09 10:25:55 -07:00
yifeizhuang a738bc8f22
alts: support google credential CFE cluster name in XDSTP format (#9246) 2022-06-08 14:26:47 -07:00
Feng Li 56e28bc9fa
Change the gRPC o11y logName when sending logs to GCP. (#9145)
* Change the gRPC o11y logName when sending logs to GCP.
2022-06-08 13:57:45 -07:00
yifeizhuang ecb2210cc1
interop-test: test_orca_oob add retry limit 5 (#9251) 2022-06-07 15:11:47 -07:00
Eric Anderson 746cb15fdd Bump Guava to 31.1
error_prone_core itself was not upgraded, even though the annotations
were to keep the change minimal.
2022-06-06 16:15:43 -07:00
yifeizhuang deea4e737a
xds: fix NullPointerException for unknown xdstp resources (#9245) 2022-06-06 14:36:01 -07:00
Eric Anderson 4d00e0cb02 xds: Remove unused Bouncy Castle dependency 2022-06-06 12:29:43 -07:00
Eric Anderson 01faeee877 api: Document illegal arguments for server connection management APIs
Most are not allowed to be zero. Grace period can be zero to immediately
close the connection when the age is hit. A zero permitKeepAliveTime()
simply doesn't enforce any limits on the client.

The choices here precisely matches the pre-existing Netty behavior, but
also seems to make sense in general.
2022-06-06 11:09:14 -07:00
Eric Anderson a2c0ae3295 api: Document Attributes.Key uses reference equality
The text here should be expanded once `keys()` is removed. But for now
this at least can make it clearer that the current behavior is on
purpose. The text here is the same as that in CallOptions.Key.

See https://github.com/grpc/grpc-java/issues/1764#issuecomment-1144935608
2022-06-06 11:08:51 -07:00
Eric Anderson 9a09021897
core: Add missed internal comment about idle mode workaround
This should have been included in #8746 but wasn't.
2022-06-06 09:34:33 -07:00
yifeizhuang c48b01a46c
interop-test:sync grpc-proto and fix typo (#9233) 2022-06-03 09:31:32 -07:00
yifeizhuang 3624d59b18
interop-test: orca test change gradle dependency to xds non-shaded to allow bazel run (#9230)
Co-authored-by: Eric Anderson <ejona@google.com>
2022-06-03 09:31:00 -07:00
Eric Anderson a206cda1a8 Change Attributes.Key debug strings to reference the API of the key
Users appear to be doing `attributes.toString()` to find keys they are
interested in and then unable to find the name of the Key in our API.
They workaround the problem by scanning through `attributes.keys()`
looking for the key of interest. This is an abuse of the keys() API and
unnecessary user friction. They'd happily use the API if they just knew
where to find it.

I added internal to some strings to make it clear that you shouldn't go
looking to use it. There were many strings I didn't change. I focused on
keys most likely to be seen by users, which meant keys in grpc-api and
keys that are available via transport attributes.

See https://github.com/grpc/grpc-java/issues/1764#issuecomment-1139250061
2022-06-02 16:11:02 -07:00
Sergii Tkachenko 1b620847ad Update README etc to reference 1.47.0, protobuf plugin 0.8.18 2022-06-02 12:02:16 -07:00
Jeremy Volkman 84edc33239
Update to handle rename of java_names.h to names.h in protobuf upstream (#9218) 2022-05-31 15:08:10 -07:00
Vladimir Chizhov 0490ced91c
Bump GSON to 2.9.0 (#9215) 2022-05-31 15:07:22 -07:00
Terry Wilson f8da92e176
xds: Update xDS protos (#9223) 2022-05-27 15:56:31 -07:00
apolcyn 6dbd1d8f58
interop-testing: bump client op timeout from 5 to 15 seconds (#9211)
JVM startup costs that happen when dependencies are loaded for the
first time can consume a lot of time (we've occasionally observed
around ~5 seconds of CPU time); this causes frequent test flakes
with xds (google-c2p) when using the current 5 second deadline.
Increasing to 15 seconds should give enough time.
2022-05-27 14:36:54 -07:00
Terry Wilson 69d4e71309
Enable xDS custom LB config by default. (#9214) 2022-05-26 17:03:14 -07:00
Eric Anderson 0ebf2f76c2 examples/xds: Remove unnecessary includeBuild ..
Previously examples-xds depended on the normal hello-world, as it used
the same classes. But since b6601ba273 it has had its own classes and
not had a dependency on `:examples.
2022-05-26 11:11:56 -07:00
yifeizhuang 45dd17c799
examples: add examples-orca (#9204) 2022-05-26 10:23:43 -07:00
Terry Wilson e2f7e676cf
xds: Make a copy of Metadata for thread safety. (#9212) 2022-05-25 15:57:24 -07:00
Lidi Zheng d6a23e4116 interop-test: Remove duplicated GCE tests 2022-05-25 15:56:29 -07:00
Terry Wilson fc406e8612
xds: Properly assign picker. (#9201)
* xds: Properly assign picker.

Fixes a bug where the picker was not getting used in RpcBehaviorLoadBalancer.
2022-05-25 12:40:12 -07:00
Terry Wilson de3388bd21
xds: Custom LB configs to support UDPA TypeStruct (#9198)
* xds: Custom LB configs to support UDPA TypeStruct

The legacy com.github.udpa.udpa.type.v1.TypedStruct proto should be supported in addition to the current com.github.udpa.udpa.type.v1.TypedStruct one.

Co-authored-by: Sergii Tkachenko <hi@sergii.org>
2022-05-24 13:55:02 -07:00
Terry Wilson 48ea07efce
xds: Use weighted_target LB provider in wrr_locality (#9195)
Fixes a bug where WrrLocalityLoadBalancer would use the endpoint picking policy provider instead of WeightedTargetLoadBalancerProvider.

Also adds a test to fake control plane integration test that caught this bug. The test scaffolding is also updated to have the test server echo all client headers back in the response.

The test load balancer in the test is an almost straight copy of: https://github.com/grpc/grpc-java/blob/master/interop-testing/src/test/java/io/grpc/testing/integration/RpcBehaviorLoadBalancerProviderTest.java
2022-05-24 13:51:12 -07:00
yifeizhuang 01ab821a06
interop-test: add orca test case (#9079)
add interop testing `orca_per_rpc` and `orca_oob`
2022-05-24 13:34:01 -07:00
Terry Wilson 62119b2a2e
interop-testing: Update comment to round_robin. (#9196) 2022-05-24 10:45:07 -07:00
Eric Anderson f9e1c0f37f
xds: Protect xdstp processing with federation env var
There are still some cases for xdstp processing, but they are to percent
encoding replacement strings. Those seem better to leave running since
it looks like it they could be triggered even with federation disabled
in the bootstrap processing.
2022-05-23 08:16:11 -07:00
Terry Wilson 4a5f6adf73
interop-testing: LB that adds the rpc-behavior to calls (#9186) 2022-05-20 12:17:58 -07:00
Eric Anderson 5bb721e217
interop-testing: Support syncing protos from grpc-proto
Two main incompatibilities existed in the copy of protos in grpc-proto:
no SimpleContext and an Empty method argument was replaced with a
message. "Context" is a very old word for "Metadata" back from the days
before the current gRPC protocol. We don't need that message in
particular, and well-known protos actually works in Protobuf Lite these
days, so we can swap to wrappers.proto's StringValue and don't need to
upstream a change to grpc-proto. The argument problem is fixed just by
changing the type in the Java code.

With the incompatibilities fixed, do a sync from grpc-proto and include
interop-testing.
2022-05-18 14:28:20 -07:00
Sergii Tkachenko 9cb3c6e688 Start 1.48.0 development cycle 2022-05-18 13:57:28 -07:00
yifeizhuang c39b3583a1
orca: change metric recorder api to: clear/set/put/remove/setAll (#9180) 2022-05-18 10:54:19 -07:00
Grant Oakley 0c5863f867
binder: Add SecurityPolicies#anyOf(), similar to allOf() (#9147) 2022-05-17 10:40:17 -07:00
John Cormie 3f19dfaf4a
binder: Avoid an ISE from asAndroidAppUri() (#9169) 2022-05-16 17:33:16 -07:00
Ovidiu Tirla a88f19fb4b
Expose SecurityLevel on server-side (#8943) 2022-05-16 17:26:10 -07:00
Eric Anderson c61b4af33d benchmarks: Raise timeout for aarch64
runUnaryBlockingClosedLoop is failing after 10.3s, which means 5.3s was
probably spent loading the LoadWorker. That means things are likely
indeed slow enough that 5s isn't enough time to wait for the server to
start. A successful execution of runUnaryBlockingClosedLoop takes
12.1 seconds, which again points to general slow execution.
2022-05-16 13:20:04 -07:00
Eric Anderson b5e78d548d api: Ignore ClassCastExceptions for hard-coded providers
This was observed in the Bazel/Blaze build where io.grpc.util is a
separate target from the rest of core. During the build of a library
SecretRoundRobinLoadBalancerProvider was not on the classpath, and the
library was later included into a binary using grpc-core from Maven
Central which includes SecretRoundRobinLoadBalancerProvider.

```
java.util.ServiceConfigurationError: Provider io.grpc.util.SecretRoundRobinLoadBalancerProvider$Provider could not be instantiated java.lang.ClassCastException: class io.grpc.util.SecretRoundRobinLoadBalancerProvider$Provider cannot be cast to some.app.aaa.aab
```
2022-05-16 13:19:46 -07:00
Eric Anderson ba57a1d893 api: Add connection management APIs to ServerBuilder
These APIs were added to NettyServerBuilder for gRFC A8 and A9. They are
important enough that they shouldn't require using the perma-unstable
transport API to access. This change also allows using these methods
with grpc-netty-shaded.

Fixes #8991
2022-05-16 13:02:09 -07:00
Michael Lumish 78067cbace
xds: Update rpc-behavior handling in interop server 2022-05-16 10:07:22 -07:00
Eric Anderson ea09d3eebd Add Bazel build support for xds, googleapis to flesh out maven_install
Not updating the example WORKSPACE because it doesn't have any
Bazel-enabled build that depends on xds and so doesn't need the
additional repository dependencies.

Fixes #9162
2022-05-16 10:05:35 -07:00
cfredri4 1d4e82e9ae
xds: Allow unspecified listener traffic direction to work with Istio (#9173)
* Allow unspecified listener traffic direction to work with Istio
2022-05-16 09:35:55 -07:00
Andrei Kandratovich 2c33e39f5d
binder: Respect requested message limits within a single MessageProducer 2022-05-16 09:23:16 -07:00
Terry Wilson 8a84611d9d
xds: Update the env variable to enable custom LB config (#9170) 2022-05-13 15:18:02 -07:00
Sergii Tkachenko 23ab7d0309 xds: ignore routes with unsupported optional cluster specifiers
Support for the is_optional logic in Cluster Specifier Plugins:
if unsupported Cluster Specifier Plugin is optional,
don't NACK, and skip any routes that point to it.
2022-05-13 13:03:04 -07:00
Terry Wilson c6bfce034f
xds: Check for env variable before doing custom LB config (#9165) 2022-05-12 12:57:11 -07:00
Terry Wilson 36d1d5fe45
xsd: wrr_locality to not propagate locality weight attribute (#9158)
WrrLocalityLoadBalancer should remove the locality weights attribute from Resolved addresses after using the information. Not propagating this attribute will make it impossible for another child wrr_locality from working. This is not a supported situation and this change make the failure happen earlier and to be more obvious as to the cause.
2022-05-12 12:51:21 -07:00
yifeizhuang 0fd8a6fcea
xds: add OrcaOobHelperWrapper.setListener(), allow receiving reports per subchannel (#9143)
remove OrcaOobHelperWrapper layer. Use OrcaOobUtil.updateListener() to set OrcaOobReportListener per each subchannel, not per helper. OrcaOobReportListener is per helper+subchannel unique.

Orca stats are created when creating helper.createSubchannels(), overriding subchannel attributes to store orcaState in the orcaHelper created subchannels
2022-05-12 10:50:58 -07:00
Terry Wilson 1ee93758cd
xds: More nuanced LoadBalancerConfigFactory tests (#9161)
Also some refactoring.
2022-05-11 23:01:04 -07:00
yifeizhuang b771403273
xds: separate orca APIs and implementations (#9144)
moved orcaMetrics to service project and renamed to MetricRecorder, added internal accessor. Maybe we can combine metricsRecorder and callMetricRecorder, they looks almost the same things.
OrcaServiceImpl depends on metricRecorder, not visa versa.
2022-05-11 15:54:05 -07:00
Terry Wilson f68be9f87c
xsd: Fix some lint errors. (#9159) 2022-05-11 09:37:24 -07:00
sanjaypujare 8f1dab0470
gpc-observability: add configuration for metrics and tracing, sampler and sampler_rate and reading from file (#9151) 2022-05-11 08:20:12 -07:00
Sergii Tkachenko 743b1ede11
grpclb: Include META-INF/services to //grpclb:grpclb (#9156) 2022-05-10 09:02:33 -07:00
Eric Anderson af56f1fc7d Revert "bom: Remove protoc-gen-grpc-java"
This reverts commit 4a84c6fa96. The BOM
was usable for protoc-gen-grpc-java using dependencyManagement for the
buildscript. See conversation on #9020.
2022-05-09 10:28:32 -07:00
Eric Anderson a8bd0b8c92 netty: Simplify and increase compat of UdsNettyChannelProvider
The transport should be usable with non-`unix:` name resolvers. As long
as the name resolver returns the correct socket address type, things
should work fine.
2022-05-09 08:37:31 -07:00
Terry Wilson c20904d681
xds: Use wrr_locality LB and support load_balancing_policy in Cluster (#9141)
Instead of providing round robin or least request configurations directly, ClientXdsClient now wraps them in a WRR locality config.

ClusterResolverLoadBalancer passes this configuration directly to PriorityLoadBalancer to use as the endpoint LB policy it provides to ClusterImplLoadBalancer. A new ResolvedAddresses attribute is also set that has all the locality weights. This is needed by WrrLocalityLoadBalancer when it configures WeightedTargetLoadBalancer.

Renames the LegacyLoadBalancerConfigFactory to just LoadBalancerConfigFactory and gives it responsibility for both the legacy and the new LB config mechanism.

The new configuration mechanism is explained in gRFC A52: https://github.com/grpc/proposal/pull/298
2022-05-06 14:54:10 -07:00
DNVindhya 15ecc0714e
gcp-observability: add grpc-census as a dependency and update opencensus version (#9140) 2022-05-03 20:52:34 -07:00
Eric Anderson de7db565a3
benchmarks: Propagate errors in LoadWorkerTest startup
Also clean up resources at the end of test.
2022-05-03 16:55:08 -07:00
sanjaypujare 41c027c11b
netty: implement UdsNameResolver and UdsNettyChannelProvider (#9113)
* netty: implement UdsNameResolver and UdsNettyChannelProvider
When the scheme is "unix:" we get the UdsNettyChannelProvider to
create a NettyChannelBuilder with DomainSocketAddress type and
other related params needed for UDS sockets
2022-05-02 16:41:50 -07:00
Eric Anderson cb61a5e284 benchmarks: Increase timeout of LoadWorkerTest
This should fix test failures on aarch64.
```
expected to be less than: 0.0
but was                 : 0.0
	at app//io.grpc.benchmarks.driver.LoadWorkerTest.assertWorkOccurred(LoadWorkerTest.java:198)
	at app//io.grpc.benchmarks.driver.LoadWorkerTest.runUnaryBlockingClosedLoop(LoadWorkerTest.java:90)
```

runUnaryBlockingClosedLoop() has been failing but the other tests
suceeding. The failure is complaining that getCount() == 0, which means
no RPCs completed. The slowest successful test has a mean RPC time of
226 ms (the unit was logged incorrectly) and comparing to x86 tests
runUnaryBlockingClosedLoop() is ~2x as slow because it executes first.
So this is probably _barely_ failing and 4 attempts instead of 3 would
be sufficient. While the test tries to wait for 10 RPCs to complete, it
seems likely it is stopping early even for the successful runs on
aarch64. There are 4 concurrent RPCs, so to get 10 RPCs we need to wait
for 3 batches of RPCs to complete which would be 1346 ms (5 loops)
assuming a 452 ms mean latency. Bumping timeout by 10x to give lots of
headroom.
2022-05-02 13:09:34 -07:00
Eric Anderson 2c3eca57e4 benchmarks: Shut down LoadClient at end of test 2022-05-02 12:14:08 -07:00
Ran e258fc743b
Use `ImmutableMap.Builder.buildOrThrow()` instead of deprecated `build()`. (#9132) 2022-05-02 11:51:42 -07:00
Eric Anderson fe5511cf21 benchmarks: Use Truth in LoadWorkerTest
This will produce better error messages when the comparisons fail. This
is to help debug aarch64 test failures.
2022-05-02 10:15:34 -07:00
marvinliu 80f1cbf6c4
binder: add hasPermissions security policy and test 2022-05-02 10:15:22 -07:00
Eric Anderson 812264ef87
interop-testing: Improve ConcurrencyTest error reporting
When a problem happens, it will now report back quickly instead of
waiting until the timeout expires. The timeout exception will also
report each RPC's state.

This is to help diagnose aarch64 test failures.
2022-05-02 10:10:42 -07:00
Eric Anderson 0431aee1ac xds: Remove unnecessary SuppressWarnings("unchecked") 2022-05-02 09:51:18 -07:00
yifeizhuang f3378c8876
xds: fix java doc warnings in orca (#9091) 2022-05-02 07:52:31 -07:00
Eric Anderson e6ddace2b8 rls: Increase RPC timeout for flaky rls_withCustomRlsChannelServiceConfig
The test appears to be slow because of classloading. The failure cases
were very slow at 14-16 seconds, but looking at other logs it succeeds
after 12 seconds. It is the first test in the class, and the other tests
run much faster. This could be solved with warmup code, but increasing
the RPC deadline is easier.

Two back-to-back failures on aarch64:
https://source.cloud.google.com/results/invocations/c4612a28-d594-42e9-b8ab-12c999690b40/targets
https://source.cloud.google.com/results/invocations/3d5d1dc2-6b47-493d-b15c-e99458067d73/targets

```
expected to be true
	at app//io.grpc.rls.CachingRlsLbClientTest.rls_withCustomRlsChannelServiceConfig(CachingRlsLbClientTest.java:267)
```

And the next run failed on a different line but seems the same cause:
https://source.cloud.google.com/results/invocations/546b83d1-cd26-4b87-8871-a7a06a60dc06/targets

```
expected to be true
	at app//io.grpc.rls.CachingRlsLbClientTest.rls_withCustomRlsChannelServiceConfig(CachingRlsLbClientTest.java:273)
```

Reproduced with:
```diff
diff --git a/rls/src/test/java/io/grpc/rls/CachingRlsLbClientTest.java b/rls/src/test/java/io/grpc/rls/CachingRlsLbClientTest.java
index 9fac852fa..631d632eb 100644
--- a/rls/src/test/java/io/grpc/rls/CachingRlsLbClientTest.java
+++ b/rls/src/test/java/io/grpc/rls/CachingRlsLbClientTest.java
@@ -264,6 +264,11 @@ public class CachingRlsLbClientTest {

     // initial request
     CachedRouteLookupResponse resp = getInSyncContext(routeLookupRequest);
+    try {
+      Thread.sleep(2000);
+    } catch (Exception e) {
+      throw new RuntimeException(e);
+    }
     assertThat(resp.isPending()).isTrue();

     // server response
```
2022-04-29 16:42:00 -07:00
yifeizhuang 9a5467b2ff
xds: move orca to java package io.grpc.xds.orca (#9086)
1. move orca from xds and from service to io.grpc.xds.orca new package
2. keep CallMetricsRecorder and InternalCallMetricsRecorder in service
3. Added APIs for recording utilization/requestCost/cpuUtilization/memoryUtilzation for per-query requests, added internal data structure equivalent to OrcaLoadReport
2022-04-29 14:56:44 -07:00
Terry Wilson e147b5ebfb
cds: Import Envoy load balancing extension protos. (#9133) 2022-04-29 14:42:27 -07:00
yifeizhuang 5686018d40
xds: NACK EDS resources with duplicate localities in the same priority (#9119) 2022-04-29 10:17:47 -07:00
Sergii Tkachenko b3d4607a62
binder, xds: address minor linter fixes (#9130) 2022-04-29 09:42:15 -07:00
Marvin Liu fdd9ab4f96 adding a security policy that allows access if and only if all given security policies allow access. this contributes to b/221149437 and is similar to cl/442582915 2022-04-28 15:48:23 -07:00
Terry Wilson 4c916c4ed1
xds: A new wrr_locality load balancer. (#9103)
This LB is the parent for weighted_target and will configure it based on the child policy it gets in its configuration and locality weights that come in a ResolvedAddresses attribute.

Described in [A52: gRPC xDS Custom Load Balancer Configuration](https://github.com/grpc/proposal/pull/298)
2022-04-28 13:51:46 -07:00
Marvin Liu 40973aedbe usage of ErrorProne CheckReturnValue 2022-04-28 13:02:43 -07:00
Eric Anderson f2348b0157 bom: Automatically exclude unpublished projects
grpc-observability was accidentally included in grpc-bom in 1.45 even
though it was not published to Maven Central. This is intended to reduce
the likelihood of such things reoccurring. We only include a project in
the bom if it is using maven-publish and if the publishing task is
enabled.

onlyIf is very similar to enabled, except it is processed just before
the task is run. We need a more static property here, so swap to
enabled. If a project uses onlyIf in the future, grpc-bom won't be able
to automatically exclude it.
2022-04-28 09:30:32 -07:00
Sergii Tkachenko 88770009fb
Increase memory in Linux aarch64 (emulated) builds (#9111)
Fix the issue with `Linux aarch64 (emulated)` builds failing with 

```
Expiring Daemon because JVM heap space is exhausted
Daemon will be stopped at the end of the build after running out of JVM memory
```

This fixes the build itself, however certain tests still fail.
2022-04-27 16:02:05 -07:00
Eric Anderson 369f87becd Revert "auth: Add support for Retryable interface"
This reverts commit 0963f3151d. This
causes dependency problems when importing into Google, as
google-auth-library-java needs to be upgraded and that requires an
upgrade to google-http-java-client to bring in
https://github.com/googleapis/google-http-java-client/pull/1505 .
Reverting for now and will roll forward once those upgrades are
performed.
2022-04-27 15:38:13 -07:00
Sergii Tkachenko 7dc4fc929c
xds, api: minor cleanup to address linter suggestions (#9116) 2022-04-27 13:02:46 -07:00
Sergii Tkachenko ecf1b37746
xds: remove google.security.meshca.v1 proto (#9115)
Remove unused xds/third_party/istio/src/main/proto/security/proto/providers/google/meshca.proto
and xds/src/generated/main/grpc/com/google/security/meshca/v1/MeshCertificateServiceGrpc.java
generated from it.
2022-04-26 17:39:09 -07:00
Eric Anderson 0963f3151d
auth: Add support for Retryable interface
Retryable was added in google-auth-library 1.5.3 to make clear the
situations that deserve a retry of the RPC. Bump to that version and
swap away from the imprecise IOException heuristic.
go/auth-correct-retry

Fixes #6808
2022-04-26 08:59:08 -07:00
Casey eeeeff0702 fix artifact name in IO_GRPC_GRPC_JAVA_ARTIFACTS 2022-04-25 17:11:56 -07:00
Sergii Tkachenko b1720f10a5
xds: Envoy proto sync to 2022-04-08 (#9101)
Proto updates:

- cncf/xds: Sort xds/import.sh protos alphabetically
- cncf/xds: Sync protos to cncf/xds@d92e9ce (commit 2021-12-16, corresponding to
  envoy cl/440193522). It's a no-op for used protos, but helpful to import the
  latest matcher.proto
- cncf/xds: Import xds/type/matcher/v3/matcher.proto with dependencies
- envoyproxy/protoc-gen-validate: Sync protos to
  envoyproxy/protoc-gen-validate@dfcdc5e (commit 2022-03-10, corresponding to
  envoy cl/440193522) to pick up ignore_empty field required for the following
  envoy sync
- envoyproxy/envoy Sync protos to envoyproxy/envoy@e33f444 (commit 2022-04-07,
  cl/440193522). This is the minimal version needed to pick up
  ClusterSpecifierPlugin.is_optional. a. Generated code:
  AggregatedDiscoveryServiceGrpc was regenerated from the updated proto. This
  is a no-op, just a minor change to the docblocks. b. Deprecated fields had to
  be taken care of manually, see "Manual updates to the code" below.
- envoyproxy/envoy Sync protos to the latest imported version
  envoyproxy/envoy@5d74719 (commit 2022-04-08, cl/443359189). Not needed for
  anything specific, just the last version, and was easy to import.


Manual updates to the code as the result of envoyproxy/envoy@e33f444 sync:

- Deprecated ConfigSource.path replaced with the ConfigSource.path_config_source
  in test fake resources. The ConfigSource.path isn't in active code paths, so
  no prod code changes needed.
- Suppress CertificateValidationContext.match_subject_alt_names deprecations in
  test files. Surprisingly, we don't report deprecations in prod files, despite
  the fact this field is used in prod code a few times.
2022-04-25 16:38:17 -07:00
sanjaypujare 538db03d56
api: add support for SocketAddress types in ManagedChannelProvider (#9076)
* api: add support for SocketAddress types in ManagedChannelProvider
also add support for SocketAddress types in NameResolverProvider
Use scheme in target URI to select a NameRseolverProvider and get
that provider's supported SocketAddress types.
implement selection in ManagedChannelRegistry of appropriate
ManagedChannelProvider based on NameResolver's SocketAddress types
2022-04-22 09:10:55 -07:00
Terry Wilson 8e65700edc
xds: ClientXdsClient to provide JSON LB configurations (v2) (#9095)
This refactoring is done in preparation of a larger change where LB configuration will be provided in the xDS Cluster proto message load_balancing_policy field. This field will allow for the configuration of custom LB policies with arbitrary configuration data.

- Instead of directly creating Java configuration objects, the client delegates to a new factory class to generate JSON configurations
- This factory is considered a "legacy" one as a separate factory will be introduced to build configs based on the new load_balancing_policy field
- The client will use a LoadBalancerProvider to parse the generated config to assure it is valid.
- Overlapping LB config validation that exists both in ClientXdsClient and LB providers will be removed from the client.

This is a second attempt at #8996 that was reverted by #9092.

The initial PR was reverted because the change caused the duplicate CDS update detection in ClientXdsClient to fail. This was because equality checking of PolicySelection instances cannot be relied on. This PR uses the JSON config instead - CdsLoadBalancer2 will handle the conversion from JSON config to PolicySelection.
2022-04-21 14:18:42 -07:00
Sergii Tkachenko a5829107c3
xds: include node ID in RPC failure status messages from the XdsClient (#9099) 2022-04-21 09:52:31 -07:00
yifeizhuang 3a303af02f
xds: priority reset failover timer when connecting if seen ready or idle since TF (#9093)
changes in priority:
Keep track of whether a child has seen TRANSIENT_FAILURE more recently than IDLE or READY, and use this to decide whether to restart the failover timer when a child reports CONNECTING. This ensures that we properly start the failover timer when the ring_hash child policy transitions from IDLE to CONNECTING at startup.
Behaviour change also affects address updates the current priority from CONNECTING to CONNECTING, previously it reports one CONNECTING, right now it does not report and wait there due to failover timer in effect. This helps to try the next priority.
2022-04-20 10:40:03 -07:00
Terry Wilson e2449a7738
Revert "xds: ClientXdsClient to make PolicySelection determination" (#9092)
* Revert "- Change config builder to a static factory class. - Remove validation and default value logic that already exists in providers from the factory. - Using the PolicySelection in CdsUpdate instead of the JSON config."

This reverts commit 54c72b945e.

* Revert "xds: ClientXdsClient to provide LB config in JSON"

This reverts commit 4903b44a82.
2022-04-19 09:24:04 -07:00
yifeizhuang 467ac7a4e8
xds: fix presubmit lints errors for style (#9090) 2022-04-18 17:44:41 -07:00
yifeizhuang 81c4571282
xds: fix ring-hash-picker behaviour (#9085) 2022-04-18 12:16:08 -07:00
yifeizhuang a0da558b12
xds: change ring_hash LB aggregation rule to handles transient_failures (#9084) 2022-04-17 20:45:34 -07:00
Eric Anderson 592a227686 okhttp: Allow keepalive scheduled executor to be overridden
Users should be able to inject all executors. The transport shouldn't be
hard-coded to create the TIMER_SERVICE, especially since a scheduler is
already available to the builder.
2022-04-15 15:28:58 -07:00
Eric Anderson 8862dca624 okhttp: Use ObjectPool for executors internally in Builder
This matches what we do in ManagedChannelImplBuilder and
NettyChannelBuilder. It also fixes a (probably unimportant) bug where
the factory returned from swapChannelCredentials() didn't have its
references to the executors so could not outlive the parent factory.
2022-04-15 15:28:58 -07:00
Terry Wilson 54c72b945e - Change config builder to a static factory class.
- Remove validation and default value logic that already exists in providers from the factory.
- Using the PolicySelection in CdsUpdate instead of the JSON config.
2022-04-13 12:40:43 -07:00
Terry Wilson 4903b44a82 xds: ClientXdsClient to provide LB config in JSON
This refactoring is done in preparation of a larger change where LB
configuration will be provided in the xDS Cluster proto message
load_balancing_policy field. This field will allow for the configuration
of custom LB policies with arbitrary configuration data.

- Instead of directly creating Java configuration objects, the client
  delegates to a new builder to generate JSON configurations
- This factory is considered a "legacy" one as a separate factory will
  be introduced to build configs based on the new load_balancing_policy
  field
- The client will use a LoadBalancerProvider to parse the generated
  config to assure it is valid.
- CdsLoadBalancer2 will parse to config again to produce the LB config
  object passed down to child LBs.
2022-04-13 12:40:43 -07:00
markb74 4e9dab9c70
Support includeStatusWithCause from InternalInProcess. (#9080) 2022-04-12 16:59:08 +02:00
Eric Anderson 4a137d6ef0 Start 1.47.0 development cycle 2022-04-11 10:41:33 -07:00
Eric Anderson 78ccc81fd5 okhttp: Remove dead code in io.grpc.okhttp.internal.Util
A substantial portion of the methods are unused. While these don't
contribute to the size of Android builds because of dead code
elimination in the build process, they still show up in static analysis
and raise questions like "when are we using MD5" or "when are we special
casing exception message text" (answer: "we're not").
2022-04-08 08:24:35 -07:00
Eric Anderson 569b7b0b95 xds: Unconditionally apply backoff on LRS stream recreation
This would limit LRS stream creation to one per second, even if the
old stream was considered good as it received a response. This is the
same change as made to ADS in 957079194a.

b/224833499
2022-04-07 14:44:36 -07:00
Eric Anderson 054cb49b49
okhttp: Remove RPCs-before-ready tests
In the olden days, before LB policies, transports had to accept RPCs as
soon as they were created. This hasn't been true for a very long time,
so remove the tests.

Since a978c9ed we're using real, legit code flows in the tests. This
allowed TSAN to discover that `attributes` is racy when read when
creating a new stream before the transport is ready. We could use a lock
or volatile, but the value of the attributes would still be incorrect
for any RPCs that are created before the transport is ready.

Since there's now only one test that delays the connection, I inline the
support code.
2022-04-07 13:30:25 -07:00
Eric Anderson 5351fb9c25 okhttp: Pass TransportFactory directly to transport constructor
This greatly reduces the number of arguments passed to the constructor
and allows using the builder in tests to change specific arguments
without having to pass all the other arguments. It also makes it easier
to see where tests are doing something special.

While it is weird to expose fields as package-private for digging-into
in the constructor, it's actually very similar to the pattern of passing
the builder instance into the constuctor. In this case, the weirdness is
because the builder isn't a nested class of the transport and there is
an additional level of building going on (Builder and TransportFactory).
We do this pattern already in ManagedChannelImpl which only has the one
level of building.
2022-04-07 09:07:13 -07:00
yifeizhuang 584622c5fa
Revert "stub: enable GRPC_CLIENT_CALL_REJECT_RUNNABLE in ThreadlessExecutor shutdown (#9035)" (#9067)
This reverts commit c53c3ad01b.
2022-04-06 14:01:05 -07:00
Eric Anderson 9208c49572 rls: Use Ticker for durations
Ticker is powered by System.nanoTime() which is CLOCK_MONOTONIC.
TimeProvider is powered by System.currentTimeMillis() which is
CLOCK_REALTIME. For durations, the monotonic clock is appropriate, not
the wall time which can jump around.
2022-04-06 08:45:53 -07:00
Eric Anderson 1426e2a670 rls: Use FakeClock like rest of grpc tests
No need to create a new (mock-based) ScheduledExecutorService
implementation; it is easy enough to teach FakeClock
scheduleAtFixedRate().
2022-04-06 08:45:53 -07:00
John Cormie fba4ae496a
binder: Work around an Android Intent bug (#9061)
Where filterEquals() can be inconsistent with filterHashCode().

Fixes #9045
2022-04-06 07:37:00 -07:00
Eric Anderson 3c2c357efa binder: Use Ticker for durations
Ticker is powered by System.nanoTime() which is CLOCK_MONOTONIC.
TimeProvider is powered by System.currentTimeMillis() which is
CLOCK_REALTIME. For durations, the monotonic clock is appropriate, not
the wall time which can jump around.
2022-04-06 07:16:21 -07:00
DNVindhya 8d69a352a9
adding @Internal annotation for internal classes (#9063) 2022-04-05 15:02:43 -07:00
DNVindhya 6765fe1457
gcp-observability: add null check before trim() for non-GKE instances (#9060) 2022-04-05 14:42:38 -07:00
Terry Wilson 98e4d49bbb Copybara cleanup. 2022-04-05 11:49:20 -07:00
DNVindhya adab27bb0f
gcp-observability: add source project id to labels when cross project logging is enabled (#9056) 2022-04-05 11:29:45 -07:00
yifeizhuang 78308c0c6a
okhttp: Fix okio 2.x API incompatibility (#9054) 2022-04-04 17:37:28 -07:00
Eric Anderson 18753b654f okhttp: Add Javadoc for ExceptionHandlingFrameWriter 2022-04-04 13:37:30 -07:00
Mohan Li 5b321c6096
interop-testing: register RLS 2022-04-04 12:20:31 -07:00
Eric Anderson a978c9edc0 okhttp: Avoid test-specific transport.start()
With the completely different constructor it was hard to track which
fields were different during the test and reduced confidence. Now the
test code flows are much closer to the real-life code flows.
2022-04-04 11:48:14 -07:00
Eric Anderson 004ee10a73
core: Vastly separate types of clock in FakeClock
There was an attempt to use different epochs for the wall clock and the
monotonic clock. However, 123456789 is actually less than a second.
We want the gap between clocks to be at least a day. This issue was
discovered in #8968.

This separation found a bug in an RLS test where it was mixing epochs.
However, it was only a problem in the test. The code under test is
wrongly using wall clock for calculation durations, but that seems to be
a wide-spread problem and will need to be handled separately.
2022-04-04 11:24:55 -07:00
Anirudh Ramachandra 79f2562306
xds: Improve code clarity by removing Unnecessary fully qualified names and using Immutable interface types. (#9025)
1. Unnecessary fully qualified names
Currently in XdsCredentialsRegistry, the child classes are referred by
their fully qualified names i.e.
'io.grpc.xds.internal.GoogleDefaultXdsCredentialsProvider' instead of
importing GoogleDefaultXdsCredentialsProvider and just using
GoogleDefaultXdsCredentialsProvider.class.

2. Use immutable interfaces instead of the generic collection interface
   i.e. ImmutableMap instead of just Map.

These improvements are related to #8924.
2022-04-04 07:19:53 -07:00
Eric Anderson 1ab7a6dd0f
xds: Remove sleeps in FileWatcherCertificateProviderTest (#8968)
This reduces test time by 7 seconds.
2022-04-01 16:35:51 -07:00
yifeizhuang db36905abf
okhttp: fix unreported exception (#9044) 2022-04-01 14:38:37 -07:00
Eric Anderson 432fcf4c98 xds: Reduce XdsServer.start() test time by 24.5s
Just using 100ms is mostly sufficient, but could potentially still flake
on the start()s that should return successfully. Waiting for the
XdsServingStatusListener to be called greatly reduces the amount of
processing needing to be done for start() to react and thus should
greatly avoid flakiness.
2022-04-01 13:34:26 -07:00
sanjaypujare fda3a2d6ff
gcp-observability: trim the string to remove newline for hostname and namespace name from files (#9043) 2022-04-01 10:11:54 -07:00
yifeizhuang c53c3ad01b
stub: enable GRPC_CLIENT_CALL_REJECT_RUNNABLE in ThreadlessExecutor shutdown (#9035) 2022-04-01 08:51:29 -07:00
Eric Anderson 574fbb4327
stub: Shutdown ThreadlessExecutor only if onClose() is called (#9041)
It is only safe to shutdown the executor if onClose() is called. Normal
RPC completions (both success and failure) will see the future complete,
so this only avoids shutting down in stranger cases like an interceptor
throwing an exception.
2022-04-01 08:49:34 -07:00
Kurt Alfred Kluever 71d38f5cae
Suppress CheckReturnValue error in PersistentHashArrayMappedTrieTest (#9038) 2022-03-31 19:50:11 -07:00
Kurt Alfred Kluever f04a49a7bd
Use try/catch idiom instead of @Test(expected = ...) (#9037) 2022-03-31 19:49:12 -07:00
yifeizhuang 7572afb32b
xds: verify and fix presubmit lints errors (#9036) 2022-03-31 12:07:44 -07:00
Eric Anderson 40c929e39f android: Use InternalManagedChannelProvider instead of reflection
This fixes up cda0e9d to be compatible with Proguard without
configuration. Since the methods are now accessed directly there is no
need for manual -keep configuration.
2022-03-31 11:52:57 -07:00
DNVindhya 86e3362298
observability: add configurable value for flush from configuration (#9034) 2022-03-30 18:03:36 -07:00
beatrausch b20ce17817
okhttp: make okhttp dependencies compile only (#8971)
* okhttp: forked required files to make okhttp dep compile only

* okhttp: forked missing file to make okhttp dep compile only

* okhttp: moved url and request files to proxy packge

* okhttp: removed unused methods from forked files; fixed build
2022-03-30 13:43:30 -07:00
sanjaypujare 5113e92415
observability: rename Observability to GcpObservability (#9030)
* observability: rename Observability to GcpObservability
rename artifact to grpc-gcp-observability
enable maven publication of grpc-gcp-observability
2022-03-30 10:12:33 -07:00
Eric Anderson 30b5d6b840 RELEASING.md: Update variable name of grpc.io's config.yaml 2022-03-30 10:02:50 -07:00
Eric Anderson 0c642581e6 Update README etc to reference 1.45.1 2022-03-30 10:01:09 -07:00
DNVindhya 898e03b700
observability: implement filtering for logging and integrate tags to GcpLogSink (#9016) 2022-03-29 21:16:47 -07:00
Eric Anderson 957079194a xds: Unconditionally apply backoff on ADS stream recreation
This would limit ADS stream creation to one per second, even if the
old stream was considered good as it received a response. This shouldn't
really ever trigger, and if it does 1 QPS is probably still too high.
But 1 QPS is _substantially_ better than a closed loop and there's very
few additional signals we could use to avoid resetting the backoff.

b/224833499
2022-03-29 16:36:33 -07:00
yifeizhuang 72ae95792c
xds: add OrcaServiceImpl (#8993) 2022-03-29 08:48:02 -07:00
Carl Mastrangelo 6554061076
all: bump PerfMark to 0.25.0 (#8948) 2022-03-29 07:53:34 -07:00
sanjaypujare 9b1023bafe
observability: change the config parsing to not require logging_config (#9023)
and make Observability implement AutoCloseable
2022-03-28 16:20:26 -07:00
Eric Anderson 4a84c6fa96 bom: Remove protoc-gen-grpc-java
protoc-gen-grpc-java isn't useful in a BOM because the Gradle plugin
doesn't support BOMs (google/protobuf-gradle-plugin#412) and it seems
unlikely the Maven plugin would as well.

Right now the type is pom, which is useless; nobody cares about the pom
itself. We'd need to use a type of exe and repeat it for each platform
(classifier). Given that it is a strange case and we can't actually test
the results and having it in the bom might lead a user to trying to make
it work, let's just remove it for now until it provides value.

Fixes #8936
2022-03-28 14:39:12 -07:00
Kurt Alfred Kluever 31ce764723 Use `try/execute/fail/catch` instead of the strongly discouraged `@Test(expected=...)`
cl/437399696
2022-03-28 14:34:33 -07:00
Anirudh Ramachandra d3f7dc0059
xds: Support custom credentials using XdsCredentialsRegistry (#8924)
Currently the credentials used for xDS communications is hardcoded in the BootstrapperImpl. The bootstrap config chooses one of the possible hardcoded credential.

This commit adds support for a credential plugin which allows users to register custom credentials through XdsCredentialProviders. gRPC will automatically discover the implementations via Java's SPI mechanism

Bootstrapper will use XdsCredentialRegistry to retrieve the list of supported credentials. The current hardcoded list of credentials(google_default, insecure and tls) are registered by default to keep the behavior as is.
2022-03-28 10:20:50 -07:00
Eric Anderson cda0e9d996 android: Use Provider to construct OkHttpChannelBuilder
Doing any reflection on OkHttpChannelBuilder requires that all methods
can have their arguments resolved. We'd like to make okhttp an optional
dependency (to support okhttp 2 and 3/4 simultaneously). But making
okhttp optional means we can no longer construct OkHttpChannelBuilder
reflectively. We swap to the Provider that doesn't have this problem.
See #8971.

Note that ManagedChannelProvider itself only exposes its methods as
protected, so they wouldn't be accessible. However OkHttpChannelProvider
has its methods public. It is an open question of whether
ManagedChannelProvider's methods should become public, but in any case
we can hide a public OkHttpChannelProvider inside a package-private
class so it is only accessable via reflection. So this code assuming
public methods doesn't prevent future implementation hiding.
2022-03-24 14:51:57 -07:00
Terry Wilson 6c00f0052f xds: Return a null RouteAction when cluster has no cluster_specifier or route lookup is not enabled with a cluster_specifier_plugin.
We want to ignore the route in these situations, which is achieved by returning a null. The current behavior of returning an error triggers a NACK to the update.
2022-03-24 09:51:57 -07:00
Eric Anderson 700afafb10 xds: Fix LBs blindly propagating XdsClient errors
This is similar to 2a45524 (for #8950) but for additional similar cases.
2022-03-22 19:44:20 -07:00
ZHANG Dapeng 37904a02c0
rls: remove wrong empty address checke for child lb (#9005)
We shouldn't require addresses to be non-empty for the child lb of rls_lb. That might be a right requirement when the child lb is grpclb, but in our new usecase, the child lb will be cds lb and will only work if empty address is allowed.

Fixing b/223866089#comment24
2022-03-22 15:20:20 -07:00
Eric Anderson 4a0fe99f8a
netty: Support pseudo headers in all GrpcHttp2RequestHeaders methods
The previous code assumed that only gRPC would be using these methods.
But twice now Netty has made a change (generally relating to security)
that used a method for pseudo headers that previously wasn't supported.
Let's stop the whack-a-mole and just implement them all.

This restores compatibility with Netty 4.1.75.Final. Fixes #8981
2022-03-22 07:39:48 -07:00
sanjaypujare 2d7302d4fd
observability: integrate globalTags and configuration into rest of observability (#9000)
* observability: integrate globalTags and configuration into rest of observability
wire observabilityConfig and globalTags into Observability and make
these available to the channel and server interceptors and specifically
to the LogHelper. Also separate globalTags into custom-tags and location-tags as required by the log-helper
2022-03-21 16:05:43 -07:00
ZHANG Dapeng c772eb0f4e
rls: fix wrong grpcKeybuilder field name (#8999)
The `grpcKeybuilders` [field](9fb243ce29/grpc/lookup/v1/rls_config.proto (L176)) should not be `grpcKeyBuilders` in json format.

The mistake in Java was introduced since the [beginning](0fd4975d4c (diff-585b634c79155b4ac9417f7805e1b9d5f6d5c11a940c88e27fdf53c209e619cfR104)).
2022-03-21 14:29:02 -07:00
Lidi Zheng d196e588a2
Add more xds_lb test cases (#8998)
This test suite is only fully enabled for C++ and Python at this
moment. This commit enables the rest of the test suite for grpc-java.

* change_backend_service_test
* failover_test
* remove_neg_test
* round_robin_test
* affinity_test
2022-03-21 12:17:26 -07:00
Eric Anderson d216f26f7a COMPILING.md: Update Android SDK instructions for new downloads 2022-03-21 10:32:50 -07:00
apolcyn 04c2b190c0
Simplify fallback test client and parameterize fallback deadline (#8989) 2022-03-21 10:03:48 -07:00
yifeizhuang 012dbaf5be
xds: accept resources wrapped in a Resource message (#8997) 2022-03-18 17:36:23 -07:00
DNVindhya b4d8fc2c40
observability: implement server interceptor for logging (#8992) 2022-03-18 11:23:50 -07:00
Lidi Zheng d71bef5afe
Redirect xDS tests to use grpc/grpc's master branch (#8982)
We are solving the issue of grpc/grpc delaying the release, causing GCE
tests to fail. Updating the master branch prevents similar cases from
happening.

Tested: [prod:grpc/java/master/branch/xds_v3](http://sponge/010f5353-e65e-4b1a-b6d3-f5a84e31546b)
2022-03-17 09:55:41 -07:00
John Cormie 2bf0a1f271
binder: Dispatch transact() calls on an Executor when FLAG_ONEWAY would not be respected. (#8987)
Fixes #8914
2022-03-16 23:19:06 -07:00
DNVindhya 0628cab226
observability: implement client interceptor for logging (#8956) 2022-03-16 22:09:25 -07:00
Jesse Schalken 1a6840accd
Pass use_default_shell_env = True for protoc (#8984)
If protoc is compiled with MinGW it will depend on libstdc++-6.dll which is found in C:\msys64\mingw64\bin and can only be found by inheriting PATH from the environment.
2022-03-16 13:38:37 -07:00
sanjaypujare 35a065dabc
observability: implement configuration parsing for observability (#8976) 2022-03-16 11:59:16 -07:00
Zhouyihai Ding ad2c0f93f4
Support setting gRPClb initial fallback timeout by service config (#8980) 2022-03-16 09:55:15 -07:00
sanjaypujare 2097d6b615
observability: change alts and google_auth_oauth2 dependencies to implementation from api (#8986) 2022-03-16 09:34:08 -07:00
yifeizhuang 86b74d9ecc
core: delayedClientCall returns drainPendingCalls runnable in setCall (#8978)
`setCall()` returns drainPendingCalls runnable only when there are calls to drain, otherwise return null. Preserved the behaviour of `start()` and `cancel()`, as they are protected by `delayOrExecute()`.
2022-03-15 12:57:24 -07:00
sanjaypujare 87e13daf1a
observability: add support for global tags using env vars and MDS (#8946) 2022-03-14 11:56:03 -07:00
Terry Wilson 3fe2f8e4ff Update README etc to reference 1.45.0 2022-03-10 10:25:32 -08:00
yifeizhuang 299851d149
stub: ClientCalls.ThreadlessExecutor throws rejectedExecutorException disable by default (#8973)
* stub: Have ClientCalls.ThreadlessExecutor reject Runnables after end of RPC

Changes originally proposed as part of #7106.

Fixes #3557

* add environment variable rejectExecutedException

Co-authored-by: Nick Hill <nickhill@us.ibm.com>
2022-03-08 10:43:43 -08:00
Eric Anderson 1d4eb49d1d
RELEASING.md: Before releasing, check TODO labels 2022-03-07 11:36:22 -08:00
apolcyn 42b32c64f5
interop-testing: Add a configurable warmup phase to fallback test client 2022-03-04 12:18:07 -08:00
Eric Anderson d00e7ee375 xds: BootstrapperImpl should not be public
It isn't used outside the package and is showing up in Javadoc. Instead
of excluding it from the Javadoc, just make it package-private.
2022-03-04 07:36:17 -08:00
Terry Wilson b8bcc3523c xds: Fix member variable ordering in FakeControlPlaneXdsIntegrationTest.java 2022-03-03 11:38:02 -08:00
Terry Wilson 2c9534d44f xds: Remove unnecessary "unchecked" warning suppression. 2022-03-03 11:38:02 -08:00
Terry Wilson b670131b55 xds: Fix constant names in FakeControlPlaneXdsIntegrationTest.java 2022-03-03 11:38:02 -08:00
Eric Anderson ecc8cc3405 googleapis: Move GoogleCloudToProdNameResolver from xds
GoogleCloudToProdNameResolver has a hard dependency on alts whereas xds
only has a weak dependency on alts that can be solved by a
ChannelCredentialsRegistry. So split out the code to a separate
artifact.
2022-03-03 11:24:49 -08:00
John Cormie abd1642371
New streams before transportReady() are not guaranteed to work (#8955)
Update javadoc to mention this previously-unwritten rule.

Update earlyServerClose_serverFailure_withClientCancelOnListenerClosed to obey it.

Update BinderTransport to fail sooner if this rule is broken.
2022-03-03 08:03:07 -08:00
Eric Anderson 9de15a4799
xds: Don't end status with '.' in XdsNameResolver (#8958)
2a45524 introduced '.' to the end of some status descriptions. We
typically don't end status descriptiosn in periods, but that's minor. In
this case though if the causal status ends in period then the new status
will end in two periods, which could easily be confusing to users.
2022-03-02 10:13:22 -08:00
yifeizhuang 2a455241a7
xds: fix XdsNameResolver blindly propagates XdsClient errors (#8953) 2022-03-01 17:34:51 -08:00
yifeizhuang 3b9ff362b9
xds: add end-2-end test with java control plane (#8715)
added a java control plane for xds tests end-to-end.
The FakeControlPlaneService manages full sets of xds resources. Use `setXdsConfig()` method to update the latest xds configurations; the method can be called anytime and multiple times dynamically. The fake control plane allows multiple clients connecting, delivers xds responses(for the data resources, or ACK/NACK) for the xds client requests.
The `FakeControlPlaneXdsIntegrationTest` only has one pingPong test case now. Other test case can be added in a similar way.
2022-02-25 13:22:03 -08:00
Penn (Dapeng) Zhang 89e53dc875 xds: Do not failoverpriority when IDLE->CONNECTING 2022-02-24 15:49:51 -08:00
Penn (Dapeng) Zhang c4d21410c6 xds: improve PriorityLoadBalancerTest 2022-02-24 15:49:51 -08:00
Eric Anderson 4d92b48ef8
xds: Squelch ADS reconnection error logs
Workaround for #8886, as we wait on a real fix. The regular load
balancing disconnections are confusing users and will train users to
start ignoring gRPC warnings. At present, it is better to have no log
than excessively log.
2022-02-23 13:55:02 -08:00
Eric Anderson 4cf3a2b801
core: Decrease transparent retry limit to 1000
The test for 10,000 took 10s to run and would time out when using other
tools like TSAN. "10000" was just a "very large number less than
infinity" and 1000 serves the same purpose and should similarly never
trigger. Using 1000 has the test run in 1s and TSAN completes in 17s.

The limit was originally added in dc6eaccc.
2022-02-23 09:15:04 -08:00
Terry Wilson ec3db2b454
Start 1.46.0 development cycle (#8939) 2022-02-23 08:23:41 -08:00
sanjaypujare b77bc6bb35
observability: do not publish our artifact to maven just yet (#8938) 2022-02-22 13:54:48 -08:00
yifeizhuang 6559ef88a1
Revert "stub: Have ClientCalls.ThreadlessExecutor reject Runnables after end of RPC (#8847)" (#8933)
This reverts commit bb3365731f.
2022-02-18 16:59:33 -08:00
sanjaypujare 80a2ca686f
Update README etc to reference 1.44.1 (#8932) 2022-02-18 16:30:42 -08:00
DNVindhya 2ef38150da
observability: implement observability.logging.CloudLoggingHandler() (#8922) 2022-02-18 10:46:21 -08:00
Eric Anderson a8a81e709d
Bump Google Auth, Guava, Auto Value
The Google Auth version is getting quite old. The new version pulls in
newer Guava and Auto Value. Two require Java 8: Google Auth since 1.x,
Guava since 31.x. Google Auth only needs Auto Value 1.8.2, but this
bumps to the latest, so all three are at their latest versions.
2022-02-16 15:47:24 -08:00
Eduard Wirch 3b6a58ee4d
doc: fix outdated external link
Page is not available on ibm.com anymore. Linking to web archive.
2022-02-16 11:36:54 -08:00
Laurent Goujon bfb970ce03
testing: fix GrpcCleanupRule issue when retrying tests (#8918)
Fix an issue in GrpcCleanupRule when tests are retried and the
teardown() method is invoked multiple times, causing Stopwatch instance
to throw an IllegalStateException.

fixes #8917.
2022-02-15 12:52:24 -08:00
Eric Anderson df6db6fe8b
bom: Include binder and exclude authz
Binder has had release artifacts since 0d25d8f7.
2022-02-14 12:17:56 -08:00
Ashitha Santhosh 1b88065f9a
authz: translate gRPC authz policy to Envoy RBAC proto (#8710) 2022-02-14 07:10:18 -08:00
yifeizhuang bb3365731f
stub: Have ClientCalls.ThreadlessExecutor reject Runnables after end of RPC (#8847)
Changes originally proposed as part of #7106.

Fixes #3557

Co-authored-by: Nick Hill <nickhill@us.ibm.com>
2022-02-11 15:08:11 -08:00
yifeizhuang 7eeb411b1f
doc: add comment about callOptions executor behavior (#8913) 2022-02-11 15:07:09 -08:00
ZHANG Dapeng 560a7fb084
okhttp: local-only transparent retry for okhttp
The OKHttp counterpart for #8878.
2022-02-11 13:02:23 -08:00
Penn (Dapeng) Zhang fbb1dbf7a5 xds: update javadoc to reference v3 proto instead of v2 2022-02-10 08:21:21 -08:00
Penn (Dapeng) Zhang f987de7497 xds: migrate EnvoyServerProtoData.Listener data types to AutoValue 2022-02-10 08:21:21 -08:00
ZHANG Dapeng da617e6ecd
rls: fix service name and method name separation
Should consistently use the last '/' in the full method name as the separator between service name and method name in MethodDescriptor.
2022-02-09 15:36:08 -08:00
nafeabd b35506b144
netty: Include both x86 and Arm64 epoll as dependency for grpc-netty-shaded 2022-02-09 13:21:36 -08:00
ZHANG Dapeng dc6eacccbf
core: limit total number of local-only transparent retries
Limit the total number of local-only transparent retries per RPC for the moment to mitigate any potential bug that would trigger infinite loop of transparent retries. If the limit is exceeded, fail the RPC.
2022-02-09 13:20:07 -08:00
Eric Anderson 7a35e3bbde android: fix code style of onBlockedStatusChanged() 2022-02-09 10:28:32 -08:00
ZHANG Dapeng 39c8f4e584
rls: migrate data types to AutoValue
Refactor to use `@AutoValue` for data types. This reduces human mistakes on `equals()`, `hashCode()`, and `toString()` while we are constantly adding and changing member fields of the data type.
2022-02-08 21:40:56 -08:00
DNVindhya 5b6ee1c176
observability: implement GrpcLogRecord proto (#8882)
* observability: implement GrpcLogRecord proto
- add configureProtoCompilation() to build.gradle for compiling protos
2022-02-08 10:20:47 -08:00
ZHANG Dapeng a1c41e3d30
xds/federation: fix percent encoding on server side
Overlooked in #8857 on server side. Since `XdsNameResolver.percentEncodePath()` will be also used for server side, I moved the method to `XdsClient`.
2022-02-07 13:29:09 -08:00
Eric Anderson 7a9ceacafc
benchmarks: Modernize client to use target and credentials
This allows using LoadClient with xDS.

The changes to SocketAddressValidator are a bit hacky, but we really
don't care about cleanliness there. Eventually on client-side, we should
be deleting the unix special case entirely, as we'll have a unix name
resolver.

Fixes #8877
2022-02-07 13:11:04 -08:00
sanjaypujare f0a7132fbe
xds: fix the validation code to accept new-style CertificateProviderPluginInstance wherever used (#8892) 2022-02-07 11:43:17 -08:00
ZHANG Dapeng 431fb0255f
core/netty: infinite local-only transparent retry for netty (#8878)
In core, add a new enum element to `RpcProgress` for the case that the stream is closed even before anything leaves the client. `RetriableStream` will do unlimited transparent retry for this type of `RpcProgress` since they are local-only.

In netty, call `tranportReportStatus()` for pending streams on failure.

Also fixes #8394
2022-02-04 22:12:03 -08:00
yifeizhuang 467985e958
add kokoro config for basic tests xds k8s (#8888) 2022-02-04 11:28:13 -08:00
Sergii Tkachenko c46d2c276a
core: test JsonUtil.getObject with a map containing a null value (#8881)
Verifies the behavior of JsonUtil.getObject when the map contains a null value for a given key.

Note: this may be incorrect behavior. Issue to track the investigation: #8883.
2022-02-04 09:56:26 -08:00
sanjaypujare a661515421
observability: revert previous visibility changes made in the provider APIs (#8889)
change visibility back to protected for certain methods of Providers
2022-02-04 08:38:46 -08:00
litclimbing ca4a1d8ca3
android: fix for app coming to foreground
When an app goes to the background, onBlockedStatusChanged is called with true and then called with false when it comes back to the foreground. The function onAvailable isn't called in this case and the connection wasn't being reset. Closes #8850

I noticed the comment that this is used for API versions 24+ but onBlockedStatusChanged was added in 29. I'm not sure if some kind of guard needs to be added or not.
https://developer.android.com/reference/android/net/ConnectivityManager.NetworkCallback#onBlockedStatusChanged(android.net.Network,%20boolean)
2022-02-03 15:56:43 -08:00
ZHANG Dapeng 7308d92034
rls: support routeLookupChannelServiceConfig in RLS lb config
Implementing the latest change for RLS lb config.

```
The configuration for the LB policy will be of the following form:

{
  "routeLookupConfig": <JSON form of RouteLookupConfig proto>,
  "routeLookupChannelServiceConfig": {...service config JSON...},
  "childPolicy": [
    {"<policy name>": {...child policy config...}}
  ],
  "childPolicyConfigTargetFieldName": "<name of field>"
}
```

>If the routeLookupChannelServiceConfig field is present, we will pass the specified service config to the RLS control plane channel, and we will disable fetching service config via that channel's resolver.
2022-02-01 14:08:15 -08:00
sanjaypujare bd156f98d6
observability: implement and integrate LoggingServerProvider into Observability (#8879) 2022-02-01 10:05:59 -08:00
sanjaypujare 881f747b7e
observability: implement Observability.grpcInit() and LoggingChannelProvider (#8872) 2022-01-31 10:37:54 -08:00
yifeizhuang 5635c6cb44 Update README etc to reference 1.44.0 2022-01-27 20:24:11 -08:00
Zhouyihai Ding 46563b75bf
core: include cause when logging Status in InternalSubchannel (#8846)
It would be good to print Cause when the transport is shutdown and has throwable exception messages.

The current log doesn't have this information for debugging:
`SHUTDOWN with UNAVAILABLE(io exception Channel Pipeline: [HttpProxyHandler$HttpClientCodecWrapper#0, HttpProxyHandler#0, TsiHandshakeHandler#0, WriteBufferingAndExceptionHandler#0, DefaultChannelPipeline$TailContext#0])`
2022-01-27 11:07:14 -08:00
sanjaypujare 5be09ec215
observability: create the grpc-observability artifact (#8870) 2022-01-27 09:58:19 -08:00
ZHANG Dapeng 7c49e5657f
rls: fix RLS lb name
The lb name of RLS lb should be "rls_experimental" instead of "rls-experimental", using underscore like "round_robin".
2022-01-25 12:02:28 -08:00
ZHANG Dapeng c59cc11e7a
Update RELEASING.md to clarify a step in tagging process 2022-01-25 12:01:59 -08:00
John Cormie 128324540f
binder: Fix a ServiceConnection leak (#8861)
Closes #8726
2022-01-24 19:54:21 -08:00
ZHANG Dapeng b29c3ec021
xds/federation: validate and canonify resource name
On reading a new `xdstp`: resource name, do a validation on the URI and canonify the query params.
2022-01-24 16:55:43 -08:00
ZHANG Dapeng 1231ce686e
xds/federation: fix percent encode
Fix percent encoding to comply with [RFC-3986 section 3.3](https://datatracker.ietf.org/doc/html/rfc3986#section-3.3) as specified in [gRFC A47](367ba33a0a/A47-xds-federation.md).
2022-01-24 10:55:19 -08:00
ZHANG Dapeng 6b0009d850
xds/federation: allow ConfigSource to have its self field set
Adopting the change in the [spec](367ba33a0a/A47-xds-federation.md (xds-api-changes)):

>Currently, for the ConfigSource fields in the LDS resource that points to the RDS resource and in the CDS resource that points to the EDS resource, gRPC requires the ConfigSource to have its ads field set. As part of supporting federation, gRPC will now also allow the ConfigSource to have its self field set. Both fields will have the same meaning.
2022-01-21 18:44:45 -08:00
Eric Anderson 41f2ad2540 RELEASING.md: Use git merge-base instead of cherry for backport summary
git cherry is too conservative in determining backports. Showing all
commits between the branch point and the release is more reliable.
2022-01-20 11:06:44 -08:00
ZHANG Dapeng 07567eebe6
xds: XdsNameResolver change to support RouteAction with RLS plugin
Implementation of the xDS Resolver section of the design http://go/grpc-rls-in-xds/view#heading=h.wkxepad0knu
2022-01-19 12:55:22 -08:00
Erik Johansson a35336c15f
xds: implement least_request load balancing policy (#8739)
Implements least_request_experimental as defined by
[A48](https://github.com/grpc/proposal/blob/master/A48-xds-least-request-lb-policy.md)

These tests are mostly just a copy of
RoundRobinLoadBalancerTest.
The main difference is currently in the pickerLeastRequest test case.
All other tests should be the same.
2022-01-19 10:14:24 -08:00
Eric Anderson 2c5a9e2aed
xds: Handle negative random numbers in c2p resolver
This was noticed because Mockito can't mock Random in Java 17, so it was
replaced with actual Random. But when doing that change it exposed that
negative numbers would cause the id to have a double '-'.
2022-01-18 12:38:04 -08:00
ZHANG Dapeng d1e0be6919
all: fix various gradle build warnings 2022-01-18 10:18:16 -08:00
Penn (Dapeng) Zhang cf4cd65707 Revert "all: clean up code related to android api level less than 19"
This reverts commit 3ad4d9bfb7.
2022-01-18 10:14:50 -08:00
Penn (Dapeng) Zhang 3179bc3be0 Revert "use charset from StandardCharsets instead of 'Charset.forName' (#8779)"
This reverts commit a74a3ad834.
2022-01-18 10:14:50 -08:00
ZHANG Dapeng d28f718c84
xds: PriorityLoadBalancer should treat IDLE in the same way as READY (#8837) 2022-01-18 09:58:30 -08:00
Kurt Alfred Kluever d5f22b77b2 netty: Assign the result of a @CheckReturnValue'ed constructor to an unused variable
This fixes a soon-to-be compile error via ErrorProne.

Alternatively, we could use assertThrows() instead of
@Test(expected = ...), but grpc doesn't yet require Java 8.
2022-01-18 09:27:25 -08:00
markb74 d853414ba3
Update javadoc for AndroidComponentAddress. (#8725)
Be more explicit that "packagename" is the application package name.
2022-01-18 09:22:59 -08:00
Eric Anderson 7cf048eb28
Drop Java 7 support
Oracle's Premier Support for Java 7 ended in July 2019. Per gRFC P5,
dropping support for the only release. Android is able to desugar many
Java 8 language features.
2022-01-18 07:17:51 -08:00
John Cormie 25531d6257
binder: Invoke onTransportReady() in a round-robin fashion. (#8835)
Also call onTransportReady() only if isReady() still holds by the time
we get to a given Inbound. This dramatically reduces timeouts and
improves throughput when flow control has kicked in.

This approach is still not completely fair since each ongoing call might
consume a different amount of window on its turn, but because of the way
Outbound#writeMessageData() and BlockPool already work, everyone gets to
send at least 16kb.
2022-01-14 14:06:14 -08:00
Penn (Dapeng) Zhang e279479908 android-interop-testing: update androidTest/AndroidManifest.xml for multidex 2022-01-14 13:38:29 -08:00
Penn (Dapeng) Zhang 14feae81b3 android-interop-testing: migrate AndroidJUnit4 runner 2022-01-14 13:38:29 -08:00
ZHANG Dapeng 9ee0ac208b
testing: remove opencensus dependency from grpc-testing (#8833)
`io.grpc.internal.testing.StatsTestUtils` in `grpc-testing` is only used internally by `grpc-interop-testing` and unit tests. The opencensus dependency does not need to be exposed to `grpc-interop-testing` maven artifact.
2022-01-14 10:13:43 -08:00
Eric Anderson 39cc44e38c
kokoro: Pretty test results
Previously, only Windows had the plumbing to rename test results for
the Kokoro result viewers to pretty-print.

macos.cfg was the only CI that lacked a corresponding .sh, which maked
unix.sh harder to reason about. Created macos.sh so that unix.sh is now
just a helper script and will not be called directly by Kokoro.

We now avoid "gradle clean" to avoid wiping results. Still clean compiler
since we do re-run the build multiple times with varying platforms.
Shouldn't be necessary, but "just in case" since I want this commit to
be low risk. This improves Windows to produce detailed results even
if the CI was successful.
2022-01-12 15:44:01 -08:00
ZHANG Dapeng 7a23fb27fe
rls: fix child lb leak when client channel is shutdown (#8750)
When client channel is shutting down, the RlsLoadBalancer is shutting down. However, the child loadbalancers of RlsLoadBalancer are not shut down. This is causing the issue b/209831670
2022-01-12 14:58:44 -08:00
yifeizhuang 26f0d611db
Start 1.45.0 development cycle (#8825) 2022-01-12 12:08:22 -08:00
Eric Anderson 58a7ace6ac
Bump ErrorProne to 2.10.0
Previous versions of error prone were incompatible with Java 17 javac.

In grpc-api, errorprone is now api dependency because it is on a public
API.  I was happy to see that Gradle failed the build without the dep
change, although the error message wasn't super clear as to the cause.

It seems that previously -PerrorProne=false did nothing. I'm guessing
this is due to a behavior change of Gradle at some point. Swapping to
using the project does build without errorProne, although the build
fails with Javac complaining certain classes are unavailable. It's
unclear why. It doesn't seem to be caused by the error-prone plugin.
I've left it failing as a pre-existing issue.

ClientCalls/ServerCalls had Deprecated removed from some methods because
they were only deprecated in the internal class, not the API. And with
Deprecated, InlineMeSuggester complained.

I'm finding InlineMeSuggester to be overzealous, complaining about
package-private methods. In time we may figure out how to use it better,
or we may request changes to the checker in error-prone.
2022-01-12 12:06:27 -08:00
Sergii Tkachenko 7c4fe69dfd
xds: fix a concurrency issue in CSDS ClientStatus responses (#8795)
* xds: fix a concurrency issue in CSDS ClientStatus responses

Fixes an issue with ClientXdsClient.getSubscribedResourcesMetadata()
executed out of shared synchronization context, and leading to:

- each individual config dump containing outdated data when
  an xDS resource is updated during CsdsService preparing the response
- config dumps for different services being out-of-sync with each
  other when any of the related xDS resources is updated during
  CsdsService preparing the response

The fix replaces getSubscribedResourcesMetadata(ResourceType type)
with atomic getSubscribedResourcesMetadataSnapshot() returning
a snapshot of all resources for each type as they are
at the moment of a CSDS request.
2022-01-11 17:45:24 -08:00
Eric Anderson 69671e152f
interop-testing: Fix script rewrite for Gradle 7.2
e0dca93c broke the interop-testing script for unix because Gradle
changed the scripts for
https://github.com/gradle/gradle/security/advisories/GHSA-6j2p-252f-7mw8

The solution here looks weird, but we are inserting the replacement
string into a single-quoted string, so we stop that string, start a
double-quoted string to allow the variable replacement, and then resume
the previous string.
2022-01-11 09:43:41 -08:00
sanjaypujare 56e9321d8a
android-interop-testing: add the linter error message ignore annotation in the source xml file (#8821) 2022-01-11 09:12:46 -08:00
Eric Anderson 9e8375850b
build.gradle: Add missing dependsOn for generated code sync
When messing with error prone for another commit, Gradle started
producing a clear warning the dependsOn was missing. But the warning
was not reliable. However, even when no warning was printed it is clear
the task was broken.
2022-01-10 14:59:19 -08:00
Eric Anderson e0dca93c6a
Bump to Gradle 7.3.3
Android Gradle plugin bumped to 4.2.0 in examples, for Gradle 7 compat
and to match main build.

Jib 3 changed default base image away from distroless, but we do want
to use distroless.
2022-01-10 10:28:42 -08:00
sanjaypujare d7f951a9d8
all: update netty to 4.1.72.Final and tcnative to 2.0.46.Final (#8780) 2022-01-07 15:34:59 -08:00
Jintao a74a3ad834
use charset from StandardCharsets instead of 'Charset.forName' (#8779)
Co-authored-by: Penn (Dapeng) Zhang <zdapeng@google.com>
2022-01-07 15:03:14 -08:00
Sergii Tkachenko 23a2202efa
xds: Rename ring_hash LB Policy to ring_hash_experimental (#8776)
Ring hash can only be used from within xds currently, because that's
the only way to get a hash assigned to RPCs which is required for it
to function. So it should be using the _experimental suffix like the
other only-used-from-xds policies.
2022-01-07 16:22:30 -05:00
Eric Anderson d44de5069d
Bump to Gradle 6.9 and update plugins
These changes make the build compatible with Gradle 7, except for
Android which requires plugin updates.

I removed animalsniffer from binder because it did nothing (as there
were no signatures) and it was failing after setting toolVersion. It
failed because animalsniffer is only compatible with java plugin. After
this change I put the withId(animalsniffer) loading inside the
withId(java) to avoid a plugin ordering failure. That made it safe again
for binder to load animalsniffer, but it is still best to remove the
plugin from binder as it is misleading.

I did not upgrade Android plugin versions as newer versions (even 3.6)
require dealing with androidx (#8421).
2022-01-07 09:54:50 -08:00
ZHANG Dapeng 5ae6f9ca25
all: Upgrade Android plugin to 4.2.0
- bump android plugin version to 4.2.0
- migrate deprecated android.support dependencies to androidx dependencies
- bump `targetSdkVersion` to 29
- temporarily ignore lint error for 'MissingClass' due to #8799
- run android CIs with `-Pandroid.useAndroidX=true -Pandroid.enableJetifier=true` flags
- android examples are still using android.support dependencies, will not be updated in this PR.
2022-01-07 09:52:26 -08:00
ZHANG Dapeng 3ad4d9bfb7
all: clean up code related to android api level less than 19 2022-01-07 08:13:32 -08:00
Sergii Tkachenko 6f223920a6 xds: Rename parseCluster() back to processCluster() for consistency
This is to keep names of the top-level process* functions called from
handle*Response functions, and returning *Update resources consistent:

- `handleLdsResponse()` -> `LdsUpdate processClientSideListener()`
                           `LdsUpdate processServerSideListener()`
- `handleCdsResponse()` -> `CdsUpdate processCluster()`
- `handleRdsResponse()` -> `RdsUpdate processRouteConfiguration()`
- `handleEdsResponse()` -> `EdsUpdate processClusterLoadAssignment()`

For some reason, processCluster() was renamed to parseCluster() in
fa4b980e0.
2022-01-06 13:23:34 -05:00
ZHANG Dapeng b32d2d2de9
xds: parse ClusterSpecifierPlugin from RouteConfiguration in xDS response
Implement the xds Client section of go/grpc-rls-in-xds#heading=h.9kitavdfxxiw
2022-01-06 10:22:57 -08:00
Eric Anderson 80c3be0f80
Bump protobuf to 3.19.2 2022-01-06 09:08:50 -08:00
ZHANG Dapeng 86b8b265ba
.github/workflows: publish test results for failed job
The GitHub Actions Linux Testing only reports limited information (can not see full stacktrace, time consumed, or stderr from child threads) when unit tests fail. Adding a step to upload the test report to Artifacts if the test fails. If the test is successful, no artifacts will be uploaded.
2022-01-05 10:31:22 -08:00
Daniel Norberg 24e345c06d
readme: grpc-netty-shaded runtime scope
We should recommend runtime scope for grpc-netty-shaded.

https://github.com/grpc/grpc-java/issues/8606#issuecomment-1004504316
2022-01-04 15:39:19 -08:00
sanjaypujare e474e3dc7e
buildscripts: always make sure we are using jdk8 (#8800) 2022-01-04 13:01:02 -08:00
Lidi Zheng 80f1be03f0
Use xds-test-server-5 as the GCE interop server (#8777) 2021-12-21 16:39:31 -08:00
ZHANG Dapeng 86ca55483b
Update README etc to reference 1.43.1 (#8775) 2021-12-21 15:18:52 -08:00
Mohan Li b244ba8d4c
xds: add skipNetCmd flag to fallback test client (#8765)
We are setting up fallback test based on TD. Currently the test client is compiled in google3, so we must run it in a container so that the client can have the GRTE dependency. However, container does not have `ip`, `iptables`, etc network command, so we plan to run the network command outside of the container. To do this, add a new flag `skipNetCmd` to skip network commands inside the test client.
2021-12-20 13:00:42 -08:00
ZHANG Dapeng 042f9879d4
all: remove deprecated StreamInfo.transportAttrs (#8768)
APIs such as `StreamInfo.getTransportAttrs()` were [deprecated](860e97d12a (diff-aa4049f54d6d5d462700e9221344184a37d2068b3ba7d715abd417b1df5bf883R114)) since 1.41.0. Removing now.
2021-12-20 09:46:25 -08:00
ZHANG Dapeng 63756ec951
core: remove unused method in AutoConfiguredLoadBalancer (#8769)
The method added in #5821 seems not used now.
2021-12-17 07:36:00 -08:00
Eric Anderson d9eb30cd92
Bump GSON to 2.8.9 2021-12-15 14:03:36 -08:00
ZHANG Dapeng 282a62e418
Update README etc to reference 1.43.0 (#8760) 2021-12-15 10:27:01 -08:00
ZHANG Dapeng 531db504ca
core: fix race condition in idleTimer & ManagedChannel#enterIdle
PR for Spikhalskiy/grpc-java@6d260b8

Hot fix of #8714
2021-12-14 17:55:48 -08:00
Eric Anderson efd968bcbb Upgrade Protobuf to 3.19.1 and Guava to 30.1.1
Protobuf uses Guava 30.1.1, so I upgrade it at the same time. It also
caused an update to rules_jvm_external and reworking the Bazel build.
Protobuf no longer requires bind() so they were dropped. Although
Protobuf's protobuf_deps() brings in rules_jvm_external, and so we don't
need to define it ourselves, it seems better to define it directly and
not depend on transitive deps since we use it directly.

Protobuf now has support for maven_install() by exposing
PROTOBUF_MAVEN_ARTIFACTS, which required reorganizing the WORKSPACE to
use maven_install() after loading protobuf. Protobuf still doesn't
define target overrides for itself so we still maintain those. When
reorganizing the WORKSPACE I noticed http_archive should ideally be
above io_grpc_grpc_java as most users will need it there, so I fixed
that since there were lots of other load()-reordering already.
2021-12-09 10:35:39 -08:00
Grant Oakley e28145ab6a
Enclose all operations using obtained Parcels in try-finally blocks that will recycle the Parcel in the case that any exception is thrown. (#8733) 2021-12-08 14:39:42 -08:00
apolcyn 24330bccff
Replace C2P resolver env var with experimental scheme suffix (#8744)
Java analogue of grpc/grpc#28294
2021-12-07 13:29:29 -08:00
Sergii Tkachenko 7aaa418ec7 rls: Fix RouteLookupConfig test arguments
This PR fixes a few cosmetic violations of the ErrorProne patterns
introduced in PR #8645: ParameterName, and TimeUnitMismatch.
2021-12-01 18:54:13 -05:00
John Cormie 27b03c66a6
Send empty shutdown flags to avoid a binder memory leak (#8728) 2021-11-30 16:00:43 -08:00
ZHANG Dapeng 65c00cf24e
Start 1.44.0 development cycle (#8729) 2021-11-30 11:53:56 -08:00
ZHANG Dapeng 2330922c38
rls: overhaul RouteLookupConfig validation (#8645)
The `RlsProtoData.RouteLookupConfig` class is out-of-date. 

- Some of the fields were long, but now are of `Duration` type. 
- Some of the fields are deleted. 
- The validation of some of the fields either have been changed or were wrong since beginning.

Now overhaul all the fields in `RlsProtoData.RouteLookupConfig` class based on the spec http://go/grpc-rls-lb-policy-design#heading=h.y3h669gfpown.

Also move the validation logic in json parsing rather than in the constructor of `RouteLookupConfig`.
2021-11-30 08:36:20 -08:00
ZHANG Dapeng cb4b91418c
javadoc: update new API `@since` version (#8727)
The @since version in commits 5a3b8e2 and a2398ce were missing and incorrect respectively.
2021-11-29 10:22:32 -08:00
ZHANG Dapeng a4334eb5c3
census: fix NPE in calling recordFinishedAttempt() (#8706)
Fix the NPE as shown in the following stacktrace:

```
Caused by: java.lang.RuntimeException: java.lang.NullPointerException with message: null
        at io.grpc.census.CensusStatsModule$ClientTracer.recordFinishedAttempt(CensusStatsModule.java:388) ~[grpc-census-1.42.0.jar:1.42.0]
        at io.grpc.census.CensusStatsModule$CallAttemptsTracerFactory.recordFinishedCall(CensusStatsModule.java:525) ~[grpc-census-1.42.0.jar:1.42.0]
        at io.grpc.census.CensusStatsModule$CallAttemptsTracerFactory.attemptEnded(CensusStatsModule.java:492) ~[grpc-census-1.42.0.jar:1.42.0]
        at io.grpc.census.CensusStatsModule$ClientTracer.streamClosed(CensusStatsModule.java:345) ~[grpc-census-1.42.0.jar:1.42.0]
        at io.grpc.internal.StatsTraceContext.streamClosed(StatsTraceContext.java:155) ~[grpc-core-1.42.0.jar:1.42.0]
        at io.grpc.internal.AbstractClientStream$TransportState.closeListener(AbstractClientStream.java:458) ~[grpc-core-1.42.0.jar:1.42.0]
        at io.grpc.internal.AbstractClientStream$TransportState.access$400(AbstractClientStream.java:221) ~[grpc-core-1.42.0.jar:1.42.0]
        at io.grpc.internal.AbstractClientStream$TransportState$1.run(AbstractClientStream.java:442) ~[grpc-core-1.42.0.jar:1.42.0]
        at io.grpc.internal.AbstractClientStream$TransportState.deframerClosed(AbstractClientStream.java:278) ~[grpc-core-1.42.0.jar:1.42.0]
        at io.grpc.internal.Http2ClientStreamTransportState.deframerClosed(Http2ClientStreamTransportState.java:31) ~[grpc-core-1.42.0.jar:1.42.0]
        at io.grpc.internal.MessageDeframer.close(MessageDeframer.java:233) ~[grpc-core-1.42.0.jar:1.42.0]
        at io.grpc.internal.MessageDeframer.closeWhenComplete(MessageDeframer.java:191) ~[grpc-core-1.42.0.jar:1.42.0]
        at io.grpc.internal.AbstractStream$TransportState.closeDeframer(AbstractStream.java:200) ~[grpc-core-1.42.0.jar:1.42.0]
        at io.grpc.internal.AbstractClientStream$TransportState.transportReportStatus(AbstractClientStream.java:445) ~[grpc-core-1.42.0.jar:1.42.0]
        at io.grpc.internal.AbstractClientStream$TransportState.transportReportStatus(AbstractClientStream.java:401) ~[grpc-core-1.42.0.jar:1.42.0]
        at io.grpc.internal.AbstractClientStream$TransportState.inboundTrailersReceived(AbstractClientStream.java:384) ~[grpc-core-1.42.0.jar:1.42.0]
        at io.grpc.internal.Http2ClientStreamTransportState.transportTrailersReceived(Http2ClientStreamTransportState.java:183) ~[grpc-core-1.42.0.jar:1.42.0]
        at io.grpc.netty.shaded.io.grpc.netty.NettyClientStream$TransportState.transportHeadersReceived(NettyClientStream.java:334) ~[grpc-netty-shaded-1.42.0.jar:1.42.0]
        at io.grpc.netty.shaded.io.grpc.netty.NettyClientHandler.onHeadersRead(NettyClientHandler.java:372) ~[grpc-netty-shaded-1.42.0.jar:1.42.0]
        at io.grpc.netty.shaded.io.grpc.netty.NettyClientHandler.access$1200(NettyClientHandler.java:91) ~[grpc-netty-shaded-1.42.0.jar:1.42.0]
        at io.grpc.netty.shaded.io.grpc.netty.NettyClientHandler$FrameListener.onHeadersRead(NettyClientHandler.java:934) ~[grpc-netty-shaded-1.42.0.jar:1.42.0]
```

The NPE can happen when `ClientCall.Listener.onClose()` and `StatsTraceContext.streamClosed()` (or `ClientStreamListener.closed()`) are invoked concurrently in different threads.  Note that `CensusStatsModule$CallAttemptsTracerFactory.attemptEnded()` in the above stack trace would observe `callEnded==true` in such a race condition.

The following are the possible scenarios that the race between `ClientCall.Listener.onClose()` and `ClientStreamListener.closed()` can happen:

- Deadline exceeded but the underlying real stream is [not committed](https://github.com/grpc/grpc-java/blob/v1.42.0/core/src/main/java/io/grpc/internal/RetriableStream.java#L486-L495), the `ClientCall.Listener` may be closed earlier than the stream listener. (This is the case of the above stack trace, in which the inbound end-of-stream is received observing `callEnded==true`. Even if nothing inbound is received, there is still a chance that the NPE can happen.)
- DelayedClientTransport.PendingStream has created a realStream but `setStream(realStream)` is [not called yet](https://github.com/grpc/grpc-java/blob/v1.42.0/core/src/main/java/io/grpc/internal/DelayedClientTransport.java#L366-L372), when deadline exceeded. (This has little chance to happen, only for the very first RPC on the channel.)
- Hedging case.

In deadline-exceeded cases, the shorter the deadline is, the more likely the race can happen.
2021-11-29 08:48:51 -08:00
markb74 ee581bfdfa
buildscripts: add config for building grpc-binder artifact (#8722) 2021-11-23 18:11:54 +01:00
ZHANG Dapeng 5f3a5f8b37
xds: support xdstp scheme in resource URIs for federation (#8716)
Implement applying `server_listener_resource_name_template` and `client_listener_resource_name_template` with xdstp scheme, extracting authorities from xdstp resource URI and lookup authorities map in bootstrap.
2021-11-22 09:02:35 -08:00
ZHANG Dapeng a5f1fb51b8
core: have JsonUtil support parsing String value as number (#8711)
As documented in https://developers.google.com/protocol-buffers/docs/proto3#json,
the canonical proto-to-json converter converts int64 (Java long) values to string values in Json rather than Json numbers (Java Double). Conversely, either Json string value or number value are accepted to be converted to int64 proto value.

To better support service configs defined by protobuf messages, support parsing String values as numbers in `JsonUtil`.
2021-11-19 10:12:39 -08:00
yifeizhuang 8382bd8e04
xds: fix clusterImplLoadBalancer NPE when lrs is null (#8713) 2021-11-18 14:30:35 -08:00
ZHANG Dapeng dd0db6cf41
xds: terminate XdsServer start() thread when shutdownNow() is called
`XdsServerWrapper.start()` [blocks](https://github.com/grpc/grpc-java/blob/master/xds/src/main/java/io/grpc/xds/XdsServerWrapper.java#L162) until `LdsResourceWatcher`'s callback is called. If no callback is called due to whatever issue of the XdsClient, the server start() will be stuck forever, even we call `shutdownNow()`.

Changing the `shutdownNow()` behavior to unblock `start()` immediately.
2021-11-17 19:54:40 -08:00
beatrausch 5a3b8e2141
okhttp: introduced new TLS1.2 cipher suites and internal okhttp implementation for TLS1.3 prepared (#8650)
This introduces new TLS 1.2 cipher suites (#8610) and prepares the
internal okhttp implementation for TLS1.3. A new method for creating
internal ConnectionSpec was added to be able to use the newly introduced
cipher suites in the OkHttpChannelBuilder. Okhttp cipher suites
synchronized with the ones from netty.
2021-11-16 18:29:29 -08:00
Mohan Li a2398ce5db
alts: Make GoogleDefaultChannelCredentials take a CallCredentials (#8548)
DirectPath is going to support non-default service account. This commit
allows users to pass CallCredentials to GoogleDefaultChannelCredentials.
See design in go/directpath-file-credential-google-default-creds
2021-11-15 15:46:56 -08:00
sanjaypujare b746bab97b
buildscripts: rename xds-k8s to psm-security as part of tech-debt cleanup and name clarity (#8695) 2021-11-12 17:40:07 -08:00
yifeizhuang 71c5eb07d3
Update README etc to reference 1.42.1 (#8694) 2021-11-12 16:54:35 -08:00
yifeizhuang 881747a63d
xds: migrate udpa proto to xds directory (#8686)
fix https://github.com/grpc/grpc-java/issues/8631:
1. import udpa protos form new git repo `https://github.com/cncf/xds.git` instead of  `https://github.com/cncf/udpa.git`
2. use proto from xds directory not udpa directory in `https://github.com/cncf/xds.git`, details was here https://github.com/cncf/xds/issues/2#issuecomment-875838155
3. support both versions of TypeStruct
4. remove v1 orca service in old directory and use the new one v3, and refer to v3 in ORCA related area
2021-11-11 10:07:14 -08:00
ZHANG Dapeng ad0971ef5f
xds: fix parsing RouteLookupClusterSpecifier mistake (#8641)
- Partially revert the change of RlsProtoData.java  in #8612  by removing `public` accessor
- Have grpc-xds no longer strongly depend on grpc-rls. The application will need grpc-rls as runtime dependencies if they need route lookup feature in xds.
- Parse RouteLookupServiceClusterSpecifierPlugin config to the Json/Map representation of `io.grpc.lookup.v1.RouteLookupClusterSpecifier` instead of `io.grpc.rls.RlsProtoData.RouteLookupConfig`
2021-11-10 11:27:42 -08:00
ZHANG Dapeng b3579db574
xds: Migrate away deprecated fields in CsdsService (#8675)
Migrate deprecate `xds_config` field to `generic_xds_configs` 

https://www.envoyproxy.io/docs/envoy/latest/api-v3/service/status/v3/csds.proto#service-status-v3-clientconfig

As per grpc/proposal#267.

The c++ version is grpc/grpc#27794
2021-11-10 08:38:44 -08:00
ZHANG Dapeng 389b865b9b
xds: populate LRS ServerInfo to CdsUpdate (#8676)
Replace `String lrsServerName` with `ServerInfo lrsServerInfo` in `CdsUpdate`.

See http://go/grpc-xds-federation#heading=h.gh3gjftay27x for details.

This PR is only refactoring. Federation support is not implemented until the TODO [here](a5c526c12f/xds/src/main/java/io/grpc/xds/ClientXdsClient.java (L2280)) is addressed.

Resolves #8628
2021-11-09 16:37:54 -08:00
Kevin Wooten 6518d7bd6d
Copy macOS x86 artifacts to aarch during upload (#8680) 2021-11-09 10:36:04 -08:00
Eric Anderson b6eafbe695 netty: Add system property to disable Connection header check
A user has a proxy that is sending "Connection: close", which is against
the HTTP/2 spec, but will take time to fix.

Fixes #8674
2021-11-09 09:26:18 -08:00
yifeizhuang 0b0079c8a1
xds: fix xdsClient resource not exist for invalid resource, fix xdsServerWrapper start on resource not exist (#8660)
Fix bugs:
1. Invalid resource at xdsClient, the watcher should have been delivered an error instead of resource not found.
2. If the resource is properly determined to not exist, it shouldn't cause start() to fail. From A36 xDS for Servers:
"XdsServer's start must not fail due to transient xDS issues, like missing xDS configuration from the xDS server."
2021-11-08 15:21:59 -08:00
cfredri4 ab7f867a4a
xds: Fix incorrect (old) javadoc for BootstrapperImpl (#8671) 2021-11-08 10:25:03 -08:00
Eric Anderson fe9026ed8a kokoro: Increase xds-k8s timeout to 3 hours
The addition of the authz tests in 0d345721 is causing the tests to
exceed their timeout. By itself, the authz test takes about an hour in
this environment. Before the authz tests, xds-k8s was taking an hour
and a half.
2021-11-05 10:04:48 -07:00
Sergii Tkachenko d548a35ab9 Update README etc to reference 1.42.0 2021-11-05 13:01:50 -04:00
Eric Anderson 0d34572149 kokoro: Enable xds authz_test
It is successfully passing against prod:
https://source.cloud.google.com/results/invocations/e2be0996-ed4d-4a4c-90ad-20bc706f9f70/targets
2021-11-04 16:31:16 -07:00
yifeizhuang a5c526c12f
xds: remove filter chain uuid name generator (#8663)
Generating a uuid in filterChain breaks the de-duplication detection which causes XdsServer to cycle connections, so removing it.
An empty name is now allowed. The name is currently only used for debug purpose.
2021-11-04 14:10:03 -07:00
sanjaypujare c0b8eff984
interop-testing: assign server as soon as it is built instead of after start (#8662) 2021-11-04 12:31:11 -07:00
Sergii Tkachenko efec994f4c Update MAINTAINERS.md 2021-11-04 14:50:34 -04:00
yifeizhuang 93a77a78a9
Revert "xds: add xds end to end interop test (#8618)" (#8656)
This reverts commit 0000cba665.
2021-11-03 12:13:05 -07:00
Eric Anderson bc12a1eb66 RELEASING.md: Individual OSSRH account is no longer needed
Most of the OSSRH interactions are performed by a robot.
2021-11-03 11:26:27 -07:00
yifeizhuang 0000cba665
xds: add xds end to end interop test (#8618)
Add AbstractXdsInteropTest, XdsTestControlPlaneService and only ping-pong testcase in initial implementation.
AbstractXdsInteropTest sets up the test control plane, create xdsClient and xdServer using bootstrap override, test case extending AbstractXdsInteropTest is supposed to override the control plane config and run the verification.

XdsTestControlPlaneService only has static xds configurations, not able to keep states.

How to run:
 ./gradlew :grpc-interop-testing:installDist -PskipCodegen=true
 ./interop-testing/build/install/grpc-interop-testing/bin/xds-e2e-test-client
2021-11-02 13:20:41 -07:00
Terry Wilson c1e19af86d
grpclb: fallback timer only when not already using fallback backends. (#8646)
Addresses a problem where we initially only resolve addresses to the backends, but not the load balancer and then later resolve addresses to both. In this situation the fallback timer was started during the second instance even if it resulted in the timer later failing as we were already using fallback backends.

This change assures that a fallback time is only ever started if we are not already using the fallback backends.

This is a follow-up fix to #8253.
2021-11-02 12:47:47 -07:00
markb74 746501dff6
binder: SecurityPolicy updates (take 2). (#8637)
The previous attempt at this CL relied on guava's Hashing class which
is still in beta. This update compares Signature objects directly instead
of SHA256 hashs, removing the need for the Hashing class.

Add additional comments to the security policy class, to mention that
implementing new policies requires significant care.

With that in mind, add security policies to check the peer app's
signature, so people can create cross-app communication without
having to implement their own policy.

Finally, add the UntrustedSecurityPolicies class, since that's
inevitably a policy which is sometimes needed.
2021-11-01 18:57:30 +01:00
ZHANG Dapeng a46560e4fc
xds: refactor XdsClient in preparation to support federation (#8630)
See go/java-xds-client-api-for-federation for detailed description
2021-11-01 09:44:58 -07:00
markb74 14eb3b265f
Support BinderChannelBuilder.forTarget. (#8633)
Allows this class to be used with custom name resolvers.
2021-11-01 14:01:56 +01:00
ZHANG Dapeng 59c6b49fd4
xds: lazily init MessagePrinter (#8639)
Just for cleanup. The printer might be used in other class e.g. to convert RLS proto to string/Map.
2021-10-29 11:46:00 -07:00
ZHANG Dapeng 602624887f
rls: sync latest rls protos from grpc-proto (#8638) 2021-10-29 10:12:38 -07:00
Eric Anderson ee395e0e43 Revert "binder: SecurityPolicy updates. (#8632)"
This reverts commit 997592192b.

Hashing is a Beta API in Guava, so we can't use it as-is.
2021-10-28 13:18:14 -07:00
markb74 997592192b
binder: SecurityPolicy updates. (#8632)
Add additional comments to the security policy class, to mention that implementing new policies requires significant care.

Also add security policies which check the Sha256 of a peer apps's signature, so people can do trusted cross-app communication without having to implement their own policy.

Finally, add the UntrustedSecurityPolicies class, since that's inevitably a policy you sometimes need as well.
2021-10-28 11:30:43 +02:00
ZHANG Dapeng f30d07dc2d
xds: add RlsClusterSpecifierPlugin for RLS-in-xDS (#8612)
Add RlsClusterSpecifierPlugin as per the [design doc](http://go/grpc-rls-in-xds#heading=h.dmyrvi6ohebx)

The structure of `ClusterSpecifierPlugin` is very similar to `io.grpc.xds.Filter`.

The following changes to the existing code are made:

- move `ConfigOrError` class out of `Filter` class to be shared with `ClusterSpecifierPlugin`
- make `io.grpc.rls.RlsProtoData` public to be accessible by `io.grpc.xds`
- treat empty defaultTarget in `io.grpc.rls.RlsProtoData.RouteLookupConfig` as null to support both json and proto config without defaultTarget field specified.
2021-10-27 09:07:15 -07:00
Sergii Tkachenko e0ecd5cfde
RELEASING.md: remove Travis; check milestones before the cut
* Update RELEASING.md

1) Remove Travis Job
2) Add a note to check milestones before cutting the branch
2021-10-25 15:34:28 -04:00
markb74 607362a7d2
Add support for anonymous in-process servers. (#8589)
Support anonymous in-process servers, and InProcessChannelBuilder.forTarget.

Anonymous servers aren't registered statically, meaning they can't be looked up by name.
Only the AnonymousInProcessSocketAddress passed to InProcessServerBuilder.forAddress(),
(or subsequently fetched from Server.getListenSockets()) can be used to connect to the server.

Supporting InProcessChannelBuilder.forTarget is particularly useful for production
Android usage of in-process servers, where process startup latency is crucial.
A custom name resolver can be used to create the server instance on demand
without directly impacting the startup latency of in-process gRPC clients.

Together, these features support a more-standard approach to "OnDeviceServer" referenced in gRFC L73.
https://github.com/grpc/proposal/blob/master/L73-java-binderchannel.md#ondeviceserver
2021-10-25 20:59:48 +02:00
ZHANG Dapeng 203515dd3d
rls: fix connectivity state aggregation (#8625)
Fix connectivity state aggregation as per http://go/grpc-rls-lb-policy-design#heading=h.6e8tt7xcwcdn

> Note that, for the purposes of aggregation, when a child policy reports TRANSIENT_FAILURE, we consider it to continue to be in that state until it reports READY (i.e., we ignore CONNECTING in between the two, no matter how many times it bounces back and forth between TRANSIENT_FAILURE and CONNECTING).
2021-10-21 21:24:51 -07:00
ZHANG Dapeng 00bb283090
xds: add protection flag for federation (#8619)
See https://github.com/grpc/proposal/pull/268/files#diff-e68147af61f13db5bd497e86ffd970fef6af29b88f4f23fb486deefdb35dfea3R659 for detail.
2021-10-20 17:59:21 -07:00
ZHANG Dapeng 2e87cd6ae3
Update README for Android API level (#8620)
We dropped support for Android API levels <19 in #8583
2021-10-20 17:56:53 -07:00
Benjamin Peterson 1fe62dd417
Fix sentences with a missing "be". (#8613) 2021-10-20 15:14:10 -07:00
yifeizhuang b86f4eba55
xds: fix non permanent link to envoy rbac doc #8615 2021-10-20 11:13:57 -07:00
Sergii Tkachenko 6d41b4283a Start 1.43.0 development cycle 2021-10-20 13:47:03 -04:00
ZhenLian d2b9151e7b
core: remove DSA check in CertificateUtils 2021-10-19 19:50:33 -04:00
ZHANG Dapeng 1f90e0e28d
xds: add and parse new bootstrap fields for federation (#8608)
Made changes as per "Bootstrap File Changes" section in go/grpc-xds-federation and implemented bootstrap file parsing logic for the change.
2021-10-18 16:19:34 -07:00
ZhenLian e9b0c2e851
Make CertificateUtils to use other key algorithms (#8609) 2021-10-15 14:42:14 -07:00
Sergii Tkachenko 0376de15b8
Fix AbstractManagedChannelImplBuilder#maxInboundMessageSize(int) ABI (#8607)
In refactoring described in #7211, the implementation of #maxInboundMessageSize(int)
(and its corresponding field) were pulled down from internal AbstractManagedChannelImplBuilder
to concrete classes that actually enforce this setting. For the same reason, it wasn't ported
to ManagedChannelImplBuilder (the #delegate()).

Then AbstractManagedChannelImplBuilder was brought back to fix ABI backward compatibility,
and temporarily turned into a ForwardingChannelBuilder, ref PR #7564. Eventually it will
be deleted, after a period with "bridge" ABI solution introduced in #7834.

However, restoring AbstractManagedChannelImplBuilder unintentionally made ABI of
pre-refactoring builds expect it to be a method of AbstractManagedChannelImplBuilder,
and not concrete classes, ref #8313.

The end goal is to keep #maxInboundMessageSize(int) only in concrete classes that enforce it.
To fix method's ABI, we temporary reintroduce it to the original layer it was removed from:
AbstractManagedChannelImplBuilder. This class' only intention is to provide short-term
ABI compatibility. Once we move forward with dropping the ABI, both fixes are no longer
necessary, and both will perish with removing AbstractManagedChannelImplBuilder.
2021-10-14 17:25:06 -07:00
ZHANG Dapeng 9f644a0861
xds: migrate Bootstrapper data classes to use AutoValue (#8594)
As many new fields will be added to `BootstrapInfo` for xds federation support, refactor `Bootstrapper.java` to use `AutoValue`. All the other files are just mechanical changes due to the refactoring.
2021-10-14 11:55:29 -07:00
yifeizhuang 8e5c18819c
enable rbac by default (#8604) 2021-10-14 11:14:48 -07:00
ZHANG Dapeng 48e3bafb11
rls: limit cache_size in rls config to 5M (#8603)
In the latest grpc-rls-lb-policy-design, if the value of cache_size_bytes is greater than 5M, we cap it at 5M.
2021-10-14 10:01:56 -07:00
Eric Anderson 7cf0578176 .github/workflows: Bump codecov-action to v2
The codecov bash uploader is being replaced (supposedly partially for
security reasons, but it seems maintenance reasons are the real goal).
https://about.codecov.io/blog/codecov-uploader-deprecation-plan/

v1 uses the bash uploader. v2 uses the new uploader. The bash uploader
will begin seeing brownouts soon.
2021-10-13 10:37:31 -07:00
markb74 9266174812
Fix code & javadoc warnings in the binder package. (#8588)
Note: I didn't fix all javadoc warnings mentioned in #8585, since
they're not generated with a modern java version, and the fix feels
worse than the warning.

Specifically, {@link X.Y} generates a warning if only X is imported,
and {@link Z} generates a warning if Z is declared later in the class.

In particular, attempting to fix the first issue by importing X.Y results
in a code-readability warning suggesting I shouldn't do that.
2021-10-09 12:27:01 +02:00
Ivo List bb51bb6dfa
java_grpc_library.bzl: Fix parameters of java_common.compile (#7598)
Parameter host_javabase is removed.

This is preparation for flipping incompatible_java_common_parameters in
Bazel 5. See https://github.com/bazelbuild/bazel/issues/12373

Bazel versions prior to 4 require host_javabase, so are no longer supported.
2021-10-08 13:48:22 -07:00
markb74 0d25d8f7d6
Publish binder in releases. (#8585) 2021-10-08 12:03:44 +02:00
yifeizhuang a2e2f56565
xds: override bootstrap for xds server (#8575)
added xdsServerBuilder method `overrideBootstrapForTest()`. Fix issue https://github.com/grpc/grpc-java/issues/7819
2021-10-07 16:17:08 -07:00
Terry Wilson 83d36104e1
Source k8s test driver install script from core repo (#8573)
The test driver install script is read directly from the core repo master branch and the copy in the Java repo is deleted.
2021-10-07 13:05:03 -07:00
Lidi Zheng 8ac9a4e7bd [xDS interop] add Docker tagging logic to the xds_url_map job 2021-10-07 09:08:23 -07:00
yifeizhuang e939bf6fb8
rbac: fix status code PERMISSION_DENIED (#8578)
RBAC should fail with PERMISSION_DENIED, fix https://github.com/grpc/grpc-java/issues/8576
2021-10-06 11:02:42 -07:00
ZHANG Dapeng 2e84b0f20a
android: bump min Android SDK version to 19 (#8583)
As Google Play Service [discontinued updates for Jelly Bean (API levels 16, 17 & 18)](https://android-developers.googleblog.com/2021/07/google-play-services-discontinuing-jelly-bean.html).
2021-10-06 10:02:32 -07:00
Terry Wilson fc57cad4ec
Revert "Revert "core/auth: Remove CallCredentials2 (#8464)"" (#8572)
This reverts commit a91cc85dfd.
2021-10-05 10:34:44 -07:00
Eric Anderson 979508ea44 context: Remove misleading example that leaks CancellableContext
The example should unconditionally cancel the context, but fails to. And
it is really unclear what situation the example is demonstrating as the
Runnable looping on isCancelled() is guaranteed to have returned when
the Throwable catch is run.

It is non-trivial to fix up this example such that it is concise,
useful, and correct as it essentially needs a rewrite. We have other
examples demonstrating CancellableContext usage. We can just rely on
them instead.
2021-10-04 13:36:20 -07:00
Eric Anderson 0e85737636 .github/workflows: Swap from adoptopenjdk to temurin
Adopt OpenJDK is longer seeing new releases, and instead has moved under
the Eclipse umbrella with Temurin releases.
https://blog.adoptopenjdk.net/2021/08/goodbye-adoptopenjdk-hello-adoptium/
https://github.com/actions/setup-java#supported-distributions

The adopt binaries still work, but won't see new versions.
2021-09-29 14:55:12 -07:00
Sumit Bhagwani 2b4a474759
Fix javadoc (#8570) 2021-09-29 13:41:32 -07:00
Eric Anderson dc4a41498e xds: Register RBAC with pretty-printer
Ideally we should plumb this through Filter, but FilterRegistry will
need to be plumbed to XdsClient and it started becoming non-trivial
compared to the "just add two lines." Expediency is helpful as the XDS
logs are pretty hard to read without the pretty-printing.
2021-09-29 11:28:25 -07:00
markb74 fcc7b9694e
Add LifecycleOnDestroyHelper to support shutdown of channel/server on Android lifecycle changes (#8568) 2021-09-29 20:04:47 +02:00
ZHANG Dapeng 28f2647aaf
core: move closed check from Stream.isReady() to Call.isReady() (#8566)
This fixes data race described in #8565.

We are doubtful whether checking closed in isReady() is necessary (#3201 might be a requirement), but it was easier to just maintain the existing behavior than think heavily about it.
2021-09-29 09:42:59 -07:00
markb74 f57de6bd03
Make binder instrumentation tests run on kokoro. (#8563)
The tests run as part of the existing android-interop-testing job.

We needed to modify the manifest of the apk built under android-interop-testing to declare Android Services used by the binder tests.
2021-09-29 11:28:14 +02:00
Liam Miller-Cushon 9209c1eaf5
Migrate off deprecated mockito method (#8562)
See: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/ArgumentMatchers.html#anyListOf-java.lang.Class-
2021-09-28 14:18:53 -07:00
yifeizhuang fbded2a05f
default throw ServerCallStreamObserver.setOnCloseHandler (#8564) 2021-09-28 13:31:40 -07:00
Lidi Zheng 0287d83182 Add testing_version flag 2021-09-27 15:19:41 -07:00
Eric Anderson 816a54a83b api: Add doc snippet to convert types for defaultServiceConfig()
Tested with Jackson's `new ObjectMapper().readValue(json, Map.class)`.

Fixes #8300
2021-09-27 14:14:35 -07:00
Eric Anderson 192688f1f2 netty: Requests with Connection header are malformed
Although this is part of HTTP/2 and should have already been handled
already, it was noticed as part of RBAC work to avoid matching
hop-by-hop headers. See gRFC A41.

Also add a warning if creating Metadata.Key for "Connection". Use this
to try to help diagnose a client if it happens to blindly copy headers
from HTTP/1, as PROTOCOL_ERROR is hard to debug.

This rolls-forward 6e89919 after it was reverted in 7669656, now that
the test proxy has been fixed.
2021-09-27 12:59:15 -07:00
Eric Anderson 60475de204 xds: Log about fallback credentials, not supplier
The sslContextProviderSupplier is used by the xds creds themselves when
the control plane has security configured. But the fallback credentials
don't use such a supplier and may not even be using TLS.

Language tweak following #8554.
2021-09-24 14:11:33 -07:00
yifeizhuang 0245a72926
xds: error descriptions improvements(#8554) 2021-09-24 10:36:00 -07:00
yifeizhuang ce311bdfd8
tsan: fix SdsProtocolNegotiatorsTest tsan failure due to thread unsafeness (#8374) 2021-09-23 16:25:38 -07:00
Zhouyihai Ding cf41181c48
alts: add channel logs in handshake
The logs are to help with debugging issues for an internal customer.
2021-09-22 21:40:41 -07:00
Eric Anderson e76efbb5da Update README etc to reference 1.41.0 2021-09-22 16:50:35 -07:00
Eric Anderson 499c51fa3f RELEASING.md: Bump protobuf version to match build.gradle
For 1.40.0 the protobuf version was bumped to the latest version, which
we hadn't tested at all. We want to bump to the version used in the
release.
2021-09-22 13:36:42 -07:00
John Cormie 3ff23d3684
Synchronize access to acknowledgedOutgoingBytes/transmitWindowFull. (#8547)
Fixes #8536
2021-09-22 12:19:48 -07:00
John Cormie 46dbac3eb6
Make manifest usable with android_instrumentation_test()s in google3 (#8545) 2021-09-22 11:53:16 -07:00
Jan Tattermusch 3049c2c147 reenable previously disabled aarch64 tests 2021-09-22 10:53:10 -07:00
markb74 e244065b0c
Fix flakey security policy tests. (#8550)
Using ShadowProcess to set the processes uID doesn't help since SecurityPolicies class fetches the ID in a static initializer, and it may have already been loaded.

Instead, just rely on whatever the uID is already, and ensure the other UIDs we test with are offset from that first value.
2021-09-22 19:19:10 +02:00
Zhouyihai Ding 5396a1de3d
grpclb: remove redundant logs and add a system property to hide server lists in logs
The server list updates are very verbose and currently logged every second, causing a huge log spam if `ChannelLogger` is completely enabled. For debugging an internal issue, we need to turn on `ChannelLogger` but hide the server list updates from the logs to keep the log size reasonable.
2021-09-22 10:13:42 -07:00
Zhouyihai Ding e41df60bea
core: change the mapping from ChannelLogLevel to java.util.logging.Level
Instead of `ChannelLogLevel.{DEBUG,INFO}` mapping to the same java level, `ChannelLogLevel.{WARNING,ERROR}` will shame the same java level. This allows us to be able to independently control the visibility of `ChannelLogLevel.DEBUG` logs which are the most verbose.
2021-09-22 09:43:08 -07:00
yifeizhuang f33daf0d9e
xds: implement equals hashcode in rbac matcher tree (#8546) 2021-09-21 16:29:07 -07:00
Piotr Morgwai Kotarbinski a6abb1b8d9
stub: add ServerCallStreamObserver.setOnCloseHandler(...) (#8452)
This allows for user code to be notified when the messages are actually
put on the wire and the stream is closed.

Fixes #5895
2021-09-21 11:31:04 -07:00
ZHANG Dapeng 29d238afca
api,stub: clarify StreamObserver and Listener param type (#8544) 2021-09-21 10:38:41 -07:00
ZHANG Dapeng 25022f6846
dep: bump netty to 4.1.63.Final and tcnative to 2.0.38.Final (#8167)
Upgrade Netty. This should also resolve #7830.
2021-09-21 09:14:54 -07:00
yifeizhuang e4a13778e0
xds: disable rbac by default (#8537) 2021-09-20 13:46:36 -07:00
ZhenLian 838438cedb
AdvancedTls: add functions to load credentials from static files (#8525)
* AdvancedTls: add functions to load credentials from static files
2021-09-17 09:45:41 -07:00
yifeizhuang 38a554c23a
xds: implement RBAC gRFC misc cases (#8518) 2021-09-16 16:12:52 -07:00
yifeizhuang fcf13952bb
xds, rbac: build per route serverInterceptor for httpConfig (#8524) 2021-09-16 12:35:09 -07:00
Eric Anderson 9d9d8ec66b
xds: Fix test compilation for confused javac
The internal build fails with "reference to assertThat is ambiguous". It
isn't clear why the internal build fails while the external one is okay,
but it is clear that the wildcard T return of readOutbound() is probably
confusing things as javac is considering assertThat(BigDecimal) as a
possible match.

The T return type is a hidden, convenience cast. We force the type
passed to assertThat() to be Object to avoid any ambiguity.
2021-09-16 12:09:15 -07:00
sanjaypujare 49842d2af1
xds: add hashCode and equals back to SslContextProviderSupplier (#8528) 2021-09-15 15:46:22 -07:00
Eric Anderson 7669656725 Revert "netty: Requests with Connection header are malformed"
This reverts commit 6e89919e32.

This was found to break a test proxy. We'll work on fixing the proxy and
then roll this forward again.
2021-09-15 15:20:40 -07:00
Eric Anderson 43b507160f xds: Drain old server connections on Listener updates
This is necessary to make sure all connections are using the new
configuration.
2021-09-15 10:08:28 -07:00
Eric Anderson 5307b69c9e netty: Allow protocol negotiators to shut down transport, with grace period
This will be used for draining old connections when xDS configuration
changes.
2021-09-15 10:08:28 -07:00
Eric Anderson 122b3b2f7c
netty: Support Host header on server-side
We want to know the single, unambiguous authority for the request. If
there is no authority, we use host instead. While authority would be
most typical for HTTP/2, requests proxied from HTTP/1 may use host
instead of authority.

This is generally useful, but the impetus is RBAC. See gRFC A41.
2021-09-15 09:40:56 -07:00
ZHANG Dapeng 3b237339c7
core: discard outbound content-length header (#8522)
Since netty version v4.1.67, content-lenght header validation will be enforced. So once grpc upgrades netty to that version or above, RPCs with invalid content-length header will fail.

Some libraries such as HTTP to gRPC adapters blindly copy all HTTP headers to gRPC metadata, but the content-length header is one of those that shouldn't be forwarded because gRPC uses different encoding. This mistake has already been in existence for a long time.

Discard outbound content-length headers in gRPC, so that users who encounter invalid content-length issue when upgrading grpc-java version on server/client side would be able to workaround by upgrading grpc-java on client/server side as well without fixing the HTTP adapter.
2021-09-13 17:15:45 -07:00
Terry Wilson 876f56e2ea
api: Stabilize the Status.asException() call. (#8520)
Removes the ExperimentalApi annotation from this call.

Contributes to: #4683
2021-09-13 14:54:25 -07:00
Eric Anderson 6e89919e32
netty: Requests with Connection header are malformed
Although this is part of HTTP/2 and should have already been handled
already, it was noticed as part of RBAC work to avoid matching
hop-by-hop headers. See gRFC A41.

Also add a warning if creating Metadata.Key for "Connection". Use this
to try to help diagnose a client if it happens to blindly copy headers
from HTTP/1, as PROTOCOL_ERROR is hard to debug.
2021-09-13 11:30:19 -07:00
ZHANG Dapeng 7c6f53ab79
all: add internal API to disable retry stats (#8510)
Resolves b/197648853 for internal performance regression. Reporting retry stats caused significant amount of performance overhead internally.
2021-09-13 09:12:04 -07:00
ZHANG Dapeng 9ff54059d8
xds: populate envoy RetryPolicy with no retryOn to resolver (#8511)
Envoy RetryPolicy with empty retryOn should not be ignored as no retry config when selecting Route config. Therefore, if xDS update for a route contains a RetryPolicy that has no RetryOn value that we support, but the virtual host config does, xds client should choose the Envoy RetryPolicy from the route (even with no RetryOn), rather than choosing the one from virtual host, and try to convert it into grpc RetryPolicy, and end up with no retry.
2021-09-13 08:31:00 -07:00
ZHANG Dapeng 7a65c74283
xds: apply valid resources while NACKing update (#8506)
Implementing [gRFC A46](https://github.com/grpc/proposal/pull/260)
2021-09-11 21:57:47 -07:00
yifeizhuang 7ad7876e99
fix header matcher for null value (#8503) 2021-09-09 12:15:27 -07:00
yifeizhuang a6df9de7bb
xds: add terminal http filter verification, remove lame route filter, add hcm as terminal network filter verification (#8342)
* xds: add terminal filter verification, remove lame route filter

* move last filter check inline

* add server validate terminal filter
2021-09-09 09:55:27 -07:00
Benjamin Peterson 67d5f1b0d6 stub: update CallStreamObserver stabilization issue 2021-09-09 09:53:47 -07:00
yifeizhuang be7aa50441
xds: referenciate server routing config (#8491)
* routing config ref

* atomic ref virtual host list

* Revert "routing config ref"

This reverts commit cbcad5744f.

* test: noop config non-static, better validation
2021-09-08 18:32:26 -07:00
Eric Anderson 9870db1f47 stub: Document that noop onCancelHandler is useful
setOnCancelHandler tells gRPC that the application is handling
cancellation. But it's fine to have noop behavior within the handler
itself if the application doesn't need it. It is just a way to opt-in to
the more recent no-exception-from-onNext behavior. Let's mention this
use-case in the docs to make it more obvious it is a possibility.

Came up as part of #8409.
2021-09-08 16:48:20 -07:00
sanjaypujare 22603810b9
xds: use the new cert-provider instances if present (#8494) 2021-09-08 16:06:21 -07:00
sanjaypujare f71eedff40
xds: remove hashCode() and equals() for SslContextProviderSupplier (#8496) 2021-09-08 15:38:26 -07:00
ZhenLian fb00463001
fix a flaky test in advanced TLS (#8474)
* fix a flaky test in advanced tls
2021-09-08 11:43:23 -07:00
Eric Anderson 1f1396f3f0 Start 1.42.0 development cycle 2021-09-08 09:10:20 -07:00
ZHANG Dapeng cd346832ba
rls: migrate deprecated server/path to extraKeys (#8469)
The [`server` and `path` fields](https://github.com/grpc/grpc-java/blob/v1.40.1/rls/src/main/proto/grpc/lookup/v1/rls.proto#L25-L32) in `RouteLookupRequest` are deprecated. Instead, we will send the server/path information in side of [`key_map`](https://github.com/grpc/grpc-java/blob/v1.40.1/rls/src/main/proto/grpc/lookup/v1/rls.proto#L45).

The keys for the server, service and method in the `key_map` will be the _values_ of `host`, `service`, `method` fields respectively in [`extraKeys`](https://github.com/grpc/grpc-java/blob/v1.40.1/rls/src/main/proto/grpc/lookup/v1/rls_config.proto#L69) in RlsConfig.

We will also include all entries in the [`constantKey`](https://github.com/grpc/grpc-java/blob/v1.40.1/rls/src/main/proto/grpc/lookup/v1/rls_config.proto#L80) in RlsConfig into `RouteLookupRequest`.


Other changes:

- Add AutoValue library for ExtraKeys class, just like data classes used in grpc-xds. Will migrate other data classes to AutoValue as well.
- Not to keep `targetType` field in the route lookup request data class, because we always use "grpc" as targetType.
2021-09-07 21:32:33 -07:00
sanjaypujare 5dc6e0ca54
xds: update Envoy protos to a later revision for the new CertificateProvider definitions (#8490) 2021-09-07 14:27:49 -07:00
Sergii Tkachenko 6cd911757a
census: make internal linter happy
TODO is preferred to FIXME.
2021-09-03 13:26:43 -07:00
ZHANG Dapeng 5475cf12bb
xds: fix parsing retryOn values (#8477)
- Envoy ignores white spaces in `retryOn` field
https://github.com/envoyproxy/envoy/blob/v1.19.1/source/common/router/retry_state_impl.cc#L166

  We should do the same.

- Envoy ignores unsupported values https://github.com/envoyproxy/envoy/blob/v1.19.1/source/common/router/config_impl.cc#L89-L90
  and we should do the same.
2021-09-03 12:47:38 -07:00
sanjaypujare 4828698bec
xds: enable PSM security by default (#8478) 2021-09-03 12:38:26 -07:00
Sergii Tkachenko a91cc85dfd
Revert "core/auth: Remove CallCredentials2 (#8464)"
This reverts commit 7cde473efa.
2021-09-02 17:20:20 -07:00
Brice Jaglin 62fafe7eda core: clarify exception message
Reformulate message to highlight that SizeEnforcingInputStream is
applied on the message size of the message after decompression.
2021-09-02 15:18:00 -07:00
Daniel Zou ffebe231c0
netty-shaded: Rename the directory of netty shaded resources to avoid collisions 2021-09-02 18:12:10 -04:00
zpencer 0838b73674
netty: remove unneeded TransportTracer null checks 2021-09-02 12:01:44 -07:00
ZHANG Dapeng 07747c59a2
xds: Fix WeakReference bug in SharedCallCounterMap (#8466)
Fixes #8397.
#8397 is caused by mistakenly clearing up a map entry right after the entry is recreated after gc. Reproduced in regression test.
2021-09-02 10:25:15 -07:00
ZHANG Dapeng 2faa748797
census: Fix retry stats data race (#8459)
There is data race in `CensusStatsModule. CallAttemptsTracerFactory`:

If client call is cancelled while an active stream on the transport is not committed, then a [noop substream](https://github.com/grpc/grpc-java/blob/v1.40.0/core/src/main/java/io/grpc/internal/RetriableStream.java#L486) will be committed and the active stream will be cancelled. Because the active stream cancellation triggers the stream listener closed() on the _transport_ thread, the closed() method can be invoked concurrently with the call listener onClose(). Therefore, one `CallAttemptsTracerFactory.attemptEnded()` can be called concurrently with `CallAttemptsTracerFactory.callEnded()`, and there could be data race on RETRY_DELAY_PER_CALL. See also the regression test added.

The same data race can happen in hedging case when one of hedges is committed and completes the call, other uncommitted hedges would cancel themselves and trigger their stream listeners closed() on the transport_thread concurrently. 

Fixing the race by recording RETRY_DELAY_PER_CALL once both the conditions are met: 
- callEnded is true 
- number of active streams is 0.
2021-09-02 10:24:22 -07:00
Anuraag Agrawal 522b37bc3b
Fix drift in MessageFramer comment (#8427) 2021-09-02 08:56:56 -07:00
sanjaypujare b0b250024f
xds: fix implementation to comply with gRFC for security (#8468) 2021-09-01 10:49:33 -07:00
Terry Wilson 7cde473efa
core/auth: Remove CallCredentials2 (#8464)
- Removes CallCredentials2
- Removes CallCredentials2ApplyingTest
- Adds two tests from CallCredentials2ApplyingTest to CallCredentialsApplyingTest
- Updates GoogleAuthLibraryCallCredentials to extend from CallCredentials instead of CallCredentials2
2021-09-01 09:49:20 -07:00
Sergii Tkachenko 4fa612ae3d
xds: fix java style 2021-08-31 16:45:37 -07:00
Lidi Zheng 40f70ca3c1
Change to a non-workload-identity GKE cluster (#8461)
Part of grpc/grpc#27189 and b/198291728.

By disabling the workload identity, we should be able to run tests faster and avoid future IAM policy size issue.

Kokoro run: https://fusion2.corp.google.com/invocations/b52b1684-47de-406d-a9f6-644909755f34/targets
2021-08-31 10:35:51 -07:00
Eric Anderson 5cc94a5488
stub: Document StreamObserver is an async API
Missing docs were brought up in #8423
2021-08-30 11:15:05 -07:00
yifeizhuang b3ef588520
Fix Java Style (#8458) 2021-08-27 16:35:23 -07:00
apolcyn 137bdaa868
interop-testing: add soak test cases to test service client 2021-08-27 15:30:43 -07:00
Kurt Alfred Kluever f3337f28ce
stub: Add @InlineMe to deprecated gRPC APIs (#8457)
Read more @ https://errorprone.info/docs/inlineme
2021-08-27 14:11:06 -07:00
yifeizhuang 0f6380b470
xds: server side xDS routing and config application (#8318)
Added routing config discovery for HCM in LdsUpdate in XdsServerWrapper. This can be LDS inline or through RDS. Deal with inflight SslContextProviderSupplier resource handling. Discovered routing config is updated to FilterChainSelectorRef.
Added routing config data field in FilterChainSelector. Filter chain matching would resulting in setting a new attribute key for server routing config. Filter chain matching logics mostly not changed.
Installed ConfigApplyingInterceptor in XdsServerWrapper's delegateBuilder. It fetches server routing config attribute set above. It does routing match and creates server interceptors for the http filters as a result.
2021-08-27 13:30:47 -07:00
Kurt Alfred Kluever 46d47d52d9
Update error-prone to the latest release (2.9.0) (#8456)
required as a prerequisite to using `@InlineMe.`
2021-08-27 11:24:27 -07:00
Terry Wilson df4ac5973c
core: Exit idle mode in enterIdle() if there are pending calls or delayed transport.
This change assures that if there are only calls in real transport the
channel will remain in idle mode. Idle mode will be exited if there
are calls in delayed transport to allow them to be processed.
2021-08-26 14:42:27 -07:00
Alexander Polcyn f1b699bbf1 Update default XDS server name in C2P resolver 2021-08-26 13:57:19 -07:00
ZhenLian 3cb0696b1f
advancedtls: change enum to use UPPER_SNAKE_CASE (#8446) 2021-08-25 16:13:09 -07:00
ZHANG Dapeng 8a5694b7f8
Update README etc to reference 1.40.1 (#8448) 2021-08-25 10:58:42 -07:00
yifeizhuang 48219d902a
fix import warning (#8441) 2021-08-24 16:33:12 -07:00
yifeizhuang fddc6552b3
upgrade cronet to 92.4515.131 (#8445) 2021-08-24 14:58:14 -07:00
ZHANG Dapeng 6776fa7c8b
xds: enable ring hash by default (#8442) 2021-08-24 13:09:33 -07:00
ZHANG Dapeng cae2339366
xds: fix RingHash LB null pointer issue (#8438) 2021-08-24 11:27:02 -07:00
Terry Wilson e45aab085c
core: Don't mark calls as cancelled if they are successfully completed. (#8408)
The semantics around cancel vary slightly between ServerCall and CancellableContext - the context should always be cancelled regardless of the outcome of the call while the ServerCall should only be cancelled on a non-OK status.

This fixes a bug where the ServerCall was always marked cancelled regardless of call status.

Fixes #5882
2021-08-20 14:42:01 -07:00
Lidi Zheng c54fcba2ee
Extend the xds_url_map job's timeout to 90 minutes (#8429)
As title. We recently had one flake caused by the Kokoro job timeout.
2021-08-20 12:12:54 -07:00
ZHANG Dapeng 29172a9665
interop-testing: fix misleading log message (#8426)
`logger.log(Level.WARNING, "Rpc failed: {0}", t)` will just print a literal "Rpc failed: {0}" followed by exception details.
2021-08-20 11:02:03 -07:00
Eric Anderson e32e177d5a xds: Avoid logging and throwing errors
The FINE logging was just repeating the exceptions. But really, it is
trivial to avoid exceptions in this case and that is beneficial because
it will avoid an expensive error handling path in something that is
trivial to trigger remotely.

The WARNING may be a bit much if connections don't match the filter
chains often in production, but it seems most likely a misconfiguration
and not something that would be seen often.
2021-08-18 10:06:28 -07:00
Eric Anderson 8026ccde4b netty: Don't use old-style classpath for shadow plugin
Seems it was introduced unnecessarily in dc74a31b. This also removes the
jcenter reference which is a repository that no longer receives updates.
2021-08-18 10:04:21 -07:00
ZhenLian 2c2ebaebd5
advancedtls: adding AdvancedTlsX509TrustManager and AdvancedTlsX509KeyManager (#8175)
* add advanced TLS classes and tests
2021-08-17 16:13:30 -07:00
yifeizhuang 90606abdf1 Update README etc to reference 1.40.0 2021-08-17 15:03:54 -07:00
Eric Anderson 3e9488be25 buildscripts: Increase memory for Gradle in Android CI
We've still been seeing random memory-related failures with the Android
CI, but it is nowhere near as severe as it was. But even when running
locally with "-Xmx512m -XX:MaxMetaspaceSize=512m" I get failures. Our CI
environment has lots of RAM; let's use it.
2021-08-17 12:31:49 -07:00
Lidi Zheng 6a6a5279c0
Add a branch name in xds_url_map's CloudBuild (#8405) 2021-08-12 13:45:19 -07:00
ZHANG Dapeng c8db48e2b1
xds: enable xDS retry by default (#8403) 2021-08-12 10:01:32 -07:00
ZHANG Dapeng bdf9a96476
core: enable retry by default (#8402)
Stabilize `enableRetry()` and `disableRetry()`.

Disable retry in `ManagedChannelImplTest` because each call attempt will fork the headers to a new instance, and add a ClientStreamTracer.Factory for bufferSizeLimit in CallOptions, which makes verification not straightforward.
2021-08-11 14:44:23 -07:00
Lidi Zheng 2a636420ef
Update xDS client/server image per-branch tag after build (#8400) 2021-08-11 14:01:21 -07:00
ZHANG Dapeng 2142902343
core: fix retry flow control issue (#8401)
There has been an issue about flow control when retry is enabled.

Currently we call `masterListener.onReady()` whenever `substreamListener.onReady()` is called.

The user's `onReady()` implementation might do

```
while(observer.isReady()) {
  // send one more message.
}
```

However, currently if the `RetriableStream` is still draining, `isReady()` is false, and user's `onReady()` exits immediately. And because `substreamListener.onReady()` is already called, it may not be called again after drained.

This PR fixes the issue by

- Use a SerializeExecutor to call all `masterListener` callbacks.
- Once `RetriableStream` is drained, check `isReady()` and if so call `onReady()`.
- Once `substreamListener.onReady()` is called, check `isReady()` and only if so we call `masterListener.onReady()`.
2021-08-11 10:25:57 -07:00
ZHANG Dapeng fd2a58a55e
all: implement retry stats (#8362) 2021-08-11 10:24:37 -07:00
yifeizhuang 1eb1d157a7
xds: allow injecting bootstrapOverride in xdsNameResolverProvider (#8358) 2021-08-11 10:12:20 -07:00
skyguard1 96a5c25056
rls: fix routeLookupClient may be null in RlsLoadBalancer.requestConnection() (#8379) 2021-08-09 20:22:44 -07:00
Eric Anderson 51d1484c3c api: Document that NameResolvers shouldn't block
Fixes #8190
2021-08-09 16:41:26 -07:00
yifeizhuang bb06739cd7
xds: refactor xdsServer wrapper, modify filter chain matching handler for server routing config (#8333)
This is split from #8318, refactoring changes include:
1. FilterChainMatchingHandler
1.1. Previously filter chain match is built-in in XdsServerCredential for xdsServer. (But it does not have to be XdsServerCredential.) The protocol negotiator associated with the XdsServerCredential does the filter chain match computation. Now filter chain match is through a FilterChainMatchingHandler and it always run. As a result, it sets attributes of sslContextProviderSupplier from xds config in protocol negotiation event.
1.2. The previous protocol negotiator associated with the XdsServerCredential is modified to just lookup the config in the attribute set above and decide to use xds config credential or fallback credential.
1.3. Previously credential is a must in XdsBuilder. Now credential becomes optional to allow routing config to be fetched. Xds TCP listener update will always be used to run filter chain match.
Later, we will add routing config in filter chain match and apply http filter configs by installing ConfigApplyingInterceptor.
2. Removed xdsClientWrapperForServerXds, unnecessarily complicated. 
3. Changed event attribute key. Previously filter chain matching happens in the xdsClientWrapperForServerXds, the xds client wrapper is passed to negotiation handler via attributes to allow protocol negotiator to trigger the filter chain matching computation.
Now the attributes becomes an atomic config selector reference that xdsServerWrapper will inject by watching xds resources updates via xds client.
4. Previously there are multiple server states enum in xdsServerWrapper, this is removed because it is unnecessarily complicated. But there are still isServing status to avoid re-start delegate upon listener update.
5. Previously xdsServerWrapper ignores any xds updates once initial started, now we allow dynamic update to happen even if server is up. This is done via updating config selector atomic reference upon listener update.
6. Previously xdsServerWrapper synchronizes on the server object, this is modified to syncContext to be more manageable.
2021-08-09 09:32:36 -07:00
ZHANG Dapeng cbda32a3c1
core: fix RetriableStream edge case bug introduced in #8386 (#8393)
While adding regression tests to #8386, I found a bug in an edge case: while retry attempt is draining the last buffered entry, if it is in the mean time committed and then we cancel the call, the stream will never be cancelled. See the regression test case `commitAndCancelWhileDraining()`.
2021-08-06 18:32:55 -07:00
Eric Anderson 20ac1999d4
stub: Mark Stub-based MetadataUtils methods deprecated
We don't want other APIs to copy the stub-based API to attach the
interceptor. The API has a shorter name, but isn't actually all that
easier to use and isn't fluent like using the interceptor API.

These are _very_ old methods, so we won't be quick to delete them. Seems
we should have them deprecated at least a year or two; they are easy to
maintain in the mean time.

See API Review notes in #1789
2021-08-06 14:14:17 -07:00
Eric Anderson 7942f35c47 binder: Disable flaky SecurityPolicy tests
Not using `@Ignore` because the tests can probably run successfully
under Bazel.

See #8391
2021-08-06 12:20:39 -07:00
Eric Anderson 0e7e0b4f57 api: Clarify Server APIs can be used before start()
Fixes #8349
2021-08-06 11:26:17 -07:00
ZHANG Dapeng 3668f2e52c
core: fix bug RetriableStream cancel() racing with start() (#8386)
There is a bug in the scenario of the following sequence of events:

- `call.start()` 
- received retryable status and about to retry
- The retry attempt Substream is created but not yet `drain()` 
- `call.cancel()`

But `stream.cancel()` cannot be called prior to `stream.start()`, otherwise retry will cause a failure with IllegalStateException. The current RetriableStream code must be fixed to not cancel a stream until `start()` is called in `drain()`.
2021-08-05 18:22:37 -07:00
Nick Ufer 9dd0c66929 netty: removes TODO in test for NettyServer 2021-08-05 11:27:27 -07:00
ZHANG Dapeng c77083f013
core: fix old ClientStreamTracer.Factory creating tracers twice (#8381)
Fix a bug introduced in #8355 : old ClientStreamTracer.Factory implementation creates tracers twice.
2021-08-04 14:32:49 -07:00
sanjaypujare 0d80c33bce
xds: log error and fail start() if server-listener-resource-name-template not set or not using xds_v3 (#8375) 2021-08-03 13:01:09 -07:00
Eric Anderson 57bd087cdf buildscripts: Build android instrumentation tests in android CI
Binder's :build was missing. Cronet build failed without specifying
Java 8 because of the transitive Guava dependency.
2021-08-02 16:52:30 -07:00
Eric Anderson f781d24ddd Mostly revert "Run binderchannel android tests. (#8306)"
This partilaly reverts commit 5e18ff208a.
It leaves the compilation fix that was made to
BinderClientTransportTest.

Running instrumentation tests via firebase requires a `--app` argument.
However, we don't have such an app and it isn't immediately clear how
we'll go about making one. Revert the change to let android-testing to
start passing again.

This problem wasn't noticed before merging the original commit because
android-testing is a post-commit CI.
2021-08-02 16:13:33 -07:00
ZHANG Dapeng 1833587597
binder: fix binder build (#8366)
The binder module fail to compile because in #8355, the class BinderClientTransportTest was not refactored correspondingly.
2021-08-02 15:54:55 -07:00
Eric Anderson 75691c8588 build.gradle: Remove non-standard MANIFEST.MF attributes
Including the build user's name doesn't provide much value and may
surprise some people. Built-JDK is actually wrong, as it is reporting
Gradle's Java version, not the javac version. And Source-/Target-
Compatibility isn't useful if nobody looks at it. Generally people just
look at the bytecode version itself, which is much more reliable and
doesn't have questions as to whether it should be '8' or '1.8'.
2021-08-02 14:14:02 -07:00
Eric Anderson 62b4364a77 api: Fix Javadoc reference to NameResolver.Args
NameResolver.Helper was a short-lived class that didn't get very far. We
chose NameResolver.Args instead and didn't mirror LoadBalancer.
2021-08-02 13:09:40 -07:00
Eric Anderson f6ce672369 Revert "core: correcting a minor resource releasing issue"
This reverts commit b9becb5c8e. It is the
caller's responsibility to close their InputStream. The change ended up
closing the passed InputStream.
2021-08-02 11:32:14 -07:00
ZHANG Dapeng 860e97d12a
all: API refactoring in preparation to support retry stats (#8355)
Rebased PR #8343 into the first commit of this PR, then (the 2nd commit) reverted the part for metric recording of retry attempts. The PR as a whole is mechanical refactoring. No behavior change (except that some of the old code path when tracer is created is moved into the new method `streamCreated()`).

The API change is documented in go/grpc-stats-api-change-for-retry-java
2021-07-31 18:33:02 -07:00
Eric Anderson b2764595e6 netty: Refine workaround for Netty header processing for transparent retries
Nginx and C core don't do graceful GOAWAY and retries have matured such
that transparent retries may soon be on by default. Refining the
workaround thus can reduces error rate for users.

Fixes #8310
2021-07-30 16:42:21 -07:00
ZHANG Dapeng d836f38979
core: add real transport test for retry buffer limit (#8354)
The unit tests in RetriableStreamTest do not really test buffer limit from end to end, because the buffer limit is implemented using ClientStreamTracer.Factory, and the tracer callback outboundMessageSize() is only triggered in AbstractClientStream after message serialization. In fact, it was broken without failing any existing tests (#8343 (comment))

This PR adds a retry buffer limit test that runs through the AbstractClientStream code path.
2021-07-28 18:59:50 -07:00
yifeizhuang 343eed1c04
Start 1.41.0 development cycle (#8351) 2021-07-28 15:27:55 -07:00
April Kyle Nassi 1867e2caa5
Update MAINTAINERS.md (#8352)
moved 2 to emeritus list
2021-07-28 14:45:19 -07:00
Ran 1e858921e1
xds: stop checking if protos are null (#8347) 2021-07-27 13:37:26 -07:00
Sergii Tkachenko bf6db5a77c
xds: sync envoy proto to commit 62ca8bd2b5960ed1c6ce2be97d3120cee719ecab (#8346)
* xds: sync envoy proto to commit 62ca8bd2b5960ed1c6ce2be97d3120cee719ecab
* Suppress warnings for newly deprecated xDS proto fields

Sync to the latest update to pick up https://github.com/envoyproxy/envoy/pull/16942 for forward compatibility with upcoming xDS Rate Limiting features.
Internal Envoy import CL for `62ca8bd2b5960ed1c6ce2be97d3120cee719ecab`: cl/381356375

Suppressed warnings for newly deprecated xDS proto fields:
1) `PerXdsConfig xds_config` to be replaced with `GenericXdsConfig generic_xds_configs`, but this work yet to be planned
2) `HttpConnectionManager`'s `uint32  setXffNumTrustedHops` to be replaced with `TypedExtensionConfig OriginalIpDetectionExtensions`: https://github.com/envoyproxy/envoy/pull/14855
2021-07-26 20:01:42 -04:00
sanjaypujare ced7bc62a3
xds: accept an empty defaultValidationContext to support TD sending an LDSupdate like that (#8345) 2021-07-26 16:58:08 -07:00
Lidi Zheng 39b7415bc0
Fix a typo in xds_url_map.cfg (#8344) 2021-07-26 16:41:34 -07:00
ZHANG Dapeng 438f8d9e78
interop-testing: extend XdsTestServer features to support retry test
Extend XdsTestServer features as specified in go/xds-retry-interop-test

See also xds retry interop test case implementation grpc/grpc#26746, grpc/grpc#26791

Previously, rpc-behavior values in the request headers are handled in tow different places, one in interceptor and the other in service implementation via Context. I moved all the rpc-behavior handling in interceptor, Context is not needed any more.
2021-07-26 12:04:58 -07:00
Lidi Zheng b3a26b732e
Add xDS k8s url-map Kokoro job (#8340)
Related PR grpc/grpc#26764
Related CL cl/386366746

This test suite will be run every 6 hours, and takes around 30 minutes. The script is copied from xds-k8s.sh, and removed the generation of server image.
2021-07-26 10:14:27 -07:00
John Cormie ecac0da655
Clarify the ServerCallHandler API contract. (#8339)
- Focus the summary fragment
- Clarify that implementations don't just have access to "call" and
"headers" while running -- they in fact take ownership of these
arguments from the caller.
- Make explicit the caller's obligation to the returned Listener.
- Clarify that "{@code call} will be closed with an error" is actually
an obligation placed on the caller (who may be a user-defined
ServerInterceptor).
2021-07-26 09:58:15 -07:00
sanjaypujare 38cba5c8dd
xds: add all validations related to security as described in A29 gRFC (#8331) 2021-07-25 22:51:50 -07:00
ZHANG Dapeng f3642422b4
xds: support xds retry policy (#8304) 2021-07-22 12:04:06 -07:00
Chengyuan Zhang f2ed41aca0
Bump Protobuf Gradle Plugin to 0.8.17 (#8336) 2021-07-21 19:30:38 -07:00
yifeizhuang 4c1272febd
api: use <scheme,provider> map in nameResoverRegistry (#8323)
An improvement that makes name resolver provider scheme matching more explicit in name resolver registry.
2021-07-21 10:03:55 -07:00
Eric Anderson a282019902
netty: Use charset=utf-8, not encoding=utf-8 for error pages
This has been wrong since the introduction of the code in df357cb8.
Noticed as part of https://github.com/grpc/grpc-go/pull/4491 . The error
text is generally ASCII, so this probably doesn't matter much.
2021-07-19 13:32:11 -07:00
Robert Turner b9becb5c8e
core: correcting a minor resource releasing issue
This change adds a traditional try/finally block around readers and
streams to control the closing of those objects when the method has
completed rather than relying on the GC to deal with them.

This issue was flagged by an analysis tool via binary analysis of the
grpc-core package as part of a dependency from another project.
2021-07-15 17:08:00 -07:00
ZHANG Dapeng 9ed444ea2a
xds: add hint of fault injection to injected failures (#8326) 2021-07-14 19:37:25 -07:00
markb74 5e18ff208a
Run binderchannel android tests. (#8306) 2021-07-14 13:10:28 +02:00
markb74 eb802cf6b1
Add an asAndroidAppUri() method to AndroidComponentAddress. (#8312)
This returns the address as an "android-app://" uri, which can be
used with AndroidAppNameResolverProvider.
2021-07-14 11:01:07 +02:00
ZHANG Dapeng 4429ec2b78
core: add perAttemptRecvTimeout to retry policy (#8301) 2021-07-12 14:53:48 -07:00
Eric Anderson 9b55aed12e testing: Make more obvious that GrpcServerRule has been replaced
The previous text did explain to use GrpcCleanupRule, but a user just
skimming might not read the long paragraph. Now we have a TL;DR.
2021-07-12 14:46:12 -05:00
sanjaypujare 629748da61
xds: fix the race condition in SslContextProviderSupplier's updateSslContext and close (#8294) 2021-07-09 10:48:18 -07:00
sanjaypujare 3965315039
xds: implement filter-chain uniqueness check as per grfc A36 (#8295) 2021-07-08 17:22:43 -07:00
John Cormie d95eebe1a8
Document the BinderChannel status code mapping. (#8291)
Document the BinderChannel status code mapping.
2021-07-08 16:38:29 -07:00
yifeizhuang 6857d1b482
fix ServerBuilder callExecutor javadoc about direct executor (#8305) 2021-07-08 13:57:14 -07:00
ZhouyihaiDing 22aa8fcef1 Add Info log for gRPC LB's init response 2021-07-08 13:41:49 -05:00
Eric Anderson dd2a422193 binder: Remove unused import 2021-07-08 09:48:43 -05:00
markb74 d4ecc7cdb4
More exposed APIs to support internal transition. (#8303)
All maked with Internal to make it clear these APIs shouldn't
be used normally.
2021-07-05 13:12:49 +02:00
Eric Anderson 0cabf5672a compiler: Add GrpcGenerated annotation to generated class
This can be used by annotation processors to avoid processing the
gRPC-generated code. The normal Generated annotation only has SOURCE
retention, so isn't available to annotation processors.

I don't include the service name within the annotation as that assumes
we'll never have need for any other type of generated class. If there's
a request for exposing service name via an annotation in the future, we
can make an RpcService annotation or the like.

Fixes #8158
2021-07-02 22:11:40 -07:00
Eric Anderson 603135791a gitattributes: Show diffs for golden generated code
'binary' in gitattributes is a macro for '-text -diff' where -text
disables EOL modification and -diff disables textual diffs. However,
these are text files, so we'd actually rather like to have diff.
2021-07-02 22:11:40 -07:00
John Cormie 380f26fd8d
Inform the server of the client's deadline using the standard header. (#8286) 2021-07-02 18:31:50 +02:00
markb74 06d34925f9
binder: Updates to support migrations to this API from internal versions. (#8299) 2021-07-02 12:53:47 +02:00
ZHANG Dapeng f86dc6c89f
Update README etc to reference 1.39.0 (#8298) 2021-06-30 09:23:15 -07:00
ZHANG Dapeng 4f09073e0f
all: remove 2-arg ClientStreamListener.closed()
We used to have two ClientStreamListener.closed() methods. One is simply calling the other with default arg. This doubles debugging (e.g. #7921) and sometimes unit testing work. Deleting the 2-arg method to cleanup.

This PR is purely refactoring.
2021-06-29 10:27:03 -07:00
Eric Anderson f93cfe5add xds: Delete unused ScheduledExecutorService management code
In 02ff64fa2 the SharedResourceHolder.get() was removed and it became
dead code.
2021-06-29 11:33:19 -05:00
Eric Anderson 4814d975a5
xds: Avoid NPE for no filter chain match on server-side 2021-06-29 09:32:37 -07:00
yifeizhuang 7644350ecb
core: fix jumpstream listener not set when closing stream inline (#8290)
* Revert "core: rollback executor supplier, needs investigation (#8289)"

This reverts commit 1b57d48ac1.

* set jumpStream listener before close stream
2021-06-28 08:50:20 -07:00
John Cormie 66faf105dd
Fix BinderSecurityTests that would always pass due to empty 'methods' map (#8287) 2021-06-25 22:15:08 +02:00
yifeizhuang 1b57d48ac1
core: rollback executor supplier, needs investigation (#8289)
* Revert "core: fix boq conformance failures (#8281)"

This reverts commit c1ad5de135.

* Revert "core: allow per-service/method executor (#8266)"

This reverts commit c540229d79.
2021-06-25 13:10:45 -07:00
yifeizhuang 3aa871b7de
xds: remove cell based rbac engine (#8277) 2021-06-25 11:20:11 -07:00
yifeizhuang c1ad5de135
core: fix boq conformance failures (#8281)
Fix false alarm to please boq conformance verifications, ref. go/boq-conformance-violations/BLOCKING#what-should-i-do-instead.
2021-06-24 08:07:06 -07:00
John Cormie c092d94255
Update AndroidComponentAddress to wrap a binding Intent. (#8275)
By considering this Intent's action, data, type, identity and categories
we align gRPC/Binder's addressing with Android's natural equivalence
relation for "cached" IBinders.
2021-06-24 13:38:06 +02:00
sanjaypujare b118a590c8
xds: remove unused SDS code (#8282) 2021-06-23 20:58:22 -07:00
sanjaypujare e4ab8287d0
xds: get rid of legacy SDS and file watching code (#8276) 2021-06-23 11:13:19 -07:00
yifeizhuang c540229d79
core: allow per-service/method executor (#8266)
Add ServerCallExecutorSupplier interface in serverBuilder to allow defining which executor to to handle the server call.
Split StreamCreated() contextRunnable into two to support this new feature: one for method lookup, the other for server call handling. methodLookup() runs on default executor, handleServerCall() may run on the executorSupplier executor.
callbacks are queued after methodLookup() and handleServerCall() on serializing executor to ensure stream listener is set when callbacks starts running.
Make executor settable in serializing executor to allow switching executor for the server call handling runnable as a result of the outcome of the method lookup runnable.
2021-06-21 11:17:36 -07:00
Chengyuan Zhang 9a8bc10f51
xds: unify client and server handling HttpConnectionManager (#8228)
Enables parsing HttpConnectionManager filter for the server side TCP listener, with the same codepath for handling it on the client side. Major changes include:

- Remodeled LdsUpdate with HttpConnectionManager. Now LdsUpdate is an oneof of HttpConnectionManager (for client side) or Listener (for server side). Each of Listener's FiliterChain contains an HttpConnectionManager (required).
Refactored code for validating and parsing the TCP Listener (for server side), put it into ClientXdsClient. The common part of validating/parsing HttpConnectionManager is reused/shared for client side.
- Included the name of FilterChain in the parsed form. As specified by the API, each FilterChain has a unique name. If the name is not provided by the control plane, a UUID is used. FilterChain names can be used for bookkeeping a set of FilterChain easily (e.g., used as map key).
- Added methods isSupportedOnClients() and isSupportedOnServers() to the Filter interface. Parsing the top-level HttpFilter requires knowing if the HttpFilter implementation is supported for the target usage (client-side or server-side). Note, parsing override HttpFilter configs does not need to know whether the config is used for an HttpFilter that is only supported for the client-side or server side.
- Added a new kind of Route: Route with non-forwarding action. Updated the XdsNameResolver being able to handle Route with non-forwarding action: if such a Route is matched to an RPC, that RPC is failed. Note, it is possible that XdsNameResolver receives xDS updates with all Routes with non-forwarding action. That is, the service config will not reference any cluster. Such case can be handled by cluster_manager LB policy's LB config parser: the parser returns the error to Channel and the Channel will handle it as error service config.
2021-06-18 11:57:36 -07:00
Eric Anderson 2258d2e3e9 netty-shaded: Use compile instead of runtime dep in pom for core
This is essentially re-adding #5901 after its behavior was "reverted"
in #8242. At the time grpc-core was the only dependency, so this change
only applies to grpc-core to make it a tiny bit easier to swap to
runtime scope in the future.
2021-06-18 07:48:04 -07:00
Eric Anderson 79e75bace4
Port from Travis-CI to GitHub Actions
Travis-CI no longer has a free tier (only a free trial). That was a
major reason we used Travis-CI, so that external contributors would be
able to run the CI on their forks. Iterating on a Travis config in a
personal repo was also quite convenient. The other reason was that
Travis-CI was safe to run even with untrusted code.

Since the introduction of the permissions field in workflows, GitHub
Actions appears safe to run untrusted code and has a free tier for
external contributors. GitHub Actions and Google Cloud Build are the
main contenders for a Kokoro replacement, but Cloud Build isn't safe for
untrusted code. Instead of migrating to Travis-CI.com from
Travis-CI.org, let's migrate to GitHub Actions and gain some familiarity.

I've really appreciated Travis-CI.org and have wanted to pay for it for
years but wasn't about to give it write permission to the repo. I'm
disappointed to migrate off it, now that the permissions issues have
been sorted out.
2021-06-17 13:32:56 -07:00
Eric Anderson 6201db2d96 Fix aarch64 emulation-triggered flakes
Because we are emulating aarch64 during testing the tests run slower
than normal. Bumping the timeout seems easy and obvious for
StressTestClientTest. The warmup for BinlogHelperTest mirrors what we've
done with timing-based tests in the past. Hopefully that is enough to
lower variance so that it passes consistently; seems likely. I'd rather
not increase the timing fuzziness if I can avoid it, as that reduces the
test's ability to detect issues.

Fixes #8135 (mostly+hopefully)
2021-06-17 13:32:11 -07:00
Sergii Tkachenko 814655cdde buildscripts: add option to use xds-k8s test driver from a fork 2021-06-16 19:09:04 -04:00
ZHANG Dapeng e980ebd118
Start 1.40.0 development cycle (#8263) 2021-06-16 08:04:43 -07:00
Daniel Zou dc74a31be1
Modify netty-shaded resources to reference shaded class names (#8258) 2021-06-16 07:56:48 -07:00
yifeizhuang 84eb285742
xds: add override rbacfilter type url RbacPerProto (#8262) 2021-06-15 16:50:50 -07:00
Chengyuan Zhang 25122f9e83
api: clean up duplicated method in InternalServerInterceptors (#8261) 2021-06-15 15:11:56 -07:00
yifeizhuang c8ba601529
xds: add rbac http filter (#8251) 2021-06-14 12:54:07 -07:00
Chengyuan Zhang 2cbc7fc3a5
grpclb: skip fallback if the LB is already in fallback mode (#8253)
Manually checks if the gRPCLB policy is already in fallback mode when trying to fallback due to receiving address update without LB addresses. 

Commit b956f8852d added an invariant check in the FallbackModeTask runnable to ensure the task is fired only when the LB is not already in fallback mode. However, that commit missed the case that receiving address updates without LB addresses can trigger the run of FallbackModeTask runnable, because the existing implementation chose to reuse the code in FallbackModeTask. In such case, running FallbackModeTask could break the invariant check as the LB policy may already in fallback mode.

This change eliminates the reuse of FallbackModeTask for handling address update without LB address. That is, every time receiving address update, we manually check if it is already in fallback instead of reusing to FallbackModeTask perform the check.

Note there was a discussion brought up whether we should force entering fallback (shutdown existing subchannels) or we should still keep the balancer connection. Different languages have already diverged on this. Go shuts down the balancer connection and all subchannel connections to force using fallback addresses. C-core keep the balancer connection working and does not shutdown subchannels, only let fallback happens after the existing balancer connection and subchannel connections become broken. Java shuts down the balancer connection but not subchannels. This change does not try to change the existing behavior, but only fixes the invariant check breakage.

-------------------
See bug reported in  b/190700476
2021-06-11 14:53:18 -07:00
Eric Anderson 5642e01243
Replace failOnVersionConflict() with custom requireUpperBoundDeps
failOnVersionConflict has never been good for us. It is equivalent to
Maven dependencyConvergence which we discourage our users to use because
it is too tempermental and _creates_ version skew issues over time.
However, we had no real alternative for determining if our deps would be
misinterpeted by Maven.

failOnVersionConflict has been a constant drain and makes it really hard
to do seemingly-trivial upgrades. As evidenced by protobuf/build.gradle
in this change, it also caused _us_ to introduce a version downgrade.

This introduces our own custom requireUpperBoundDeps implementation so
that we can get back to simple dependency upgrades _and_ increase our
confidence in a consistent dependency tree.
2021-06-11 14:01:18 -07:00
Penn (Dapeng) Zhang aa18b2c228 grpclb: update load_balancer.proto 2021-06-11 13:28:48 -07:00
Penn (Dapeng) Zhang 11c0d1d81e rls: update rls proto 2021-06-11 13:28:48 -07:00
markb74 b846ae79bb
Allow SecurityPolicy definitions. (#8254)
Internally this was package visible to retain strict control
over the available policies. However, that kind of strict control
doesn't work with the open-source version, since users will want
to create their own policies. There's at least google-specific
policy internally.
2021-06-11 18:02:36 +02:00
Eric Anderson 8360e60330 netty/shaded: Leverage shadow plugin's publishing support
https://github.com/johnrengelman/shadow/pull/543 fixed project support,
which means the workaround is no longer necessary.
2021-06-11 08:32:11 -07:00
Chengyuan Zhang 91948b2606
xds: fix lint (#8248) 2021-06-09 14:57:26 -07:00
Chengyuan Zhang d41094944c
xds: equally weight endpoints within locality if endpoint-level weight unspecified (#8245)
Use a multiplier of 1 for endpoints with endpoint-level load balancing weight unspecified when computing weights for mixing-locality load balancing. Therefore, if a locality has endpoints without endpoint-level load balancing weight, they are weighted equally within the locality.
2021-06-09 12:04:17 -07:00
yifeizhuang b7f3fddc76
xds, rbac: implement rbac engine (#8168) 2021-06-08 14:45:11 -07:00
Eric Anderson d4c31ffad4 netty/shaded: Include deps automatically
Previously it required manually listing the direct deps of grpc-netty
which is error-prone as evidinced by the fact that we were missing
multiple deps (guava, perfmark-api). This didn't cause a problem because
grpc-core happens to bring in these same deps.
2021-06-08 12:27:12 -07:00
Chengyuan Zhang fa4b980e07
xds: use defaults for unspecified ring_hash_lb_config values (#8237)
Sets ring_hash LB config to its default values (min_ring_size = 1024 and max_ring_size = 8M) if not given by the control plane. This applies to both parsing RingHashLbConfig from xDS proto and parsing RingHashConfig from the JSON config (currently not used). If the values are given by the control plane, they are validated such that min_ring_size is not less than max_ring_size and do not exceed the 8M limit.
2021-06-07 14:26:50 -07:00
Eric Anderson 29618a6bb6 Bump Protobuf to 3.17.2
Removed some references to the protobuf version from COMPILING.md and
compiler/README.md to make updates a tiny bit easier.
2021-06-07 11:20:48 -07:00
Chengyuan Zhang e51a17574f
xds: append a random number to C2P generated node id (#8239)
Adding a random number to the xDS stream node id helps debugging for distinguishing between different clients.
2021-06-07 11:01:04 -07:00
sanjaypujare 4209c8d8cc
xds: close SslContexrProviderSupplier when the CDS LoadBalancer is shut down to prevent leakage (#8240) 2021-06-07 10:53:57 -07:00
markb74 0c723f7ca9
binder: Server and Channel Builders for BinderChannel. (#8218)
binder: Server and Channel Builders for BinderChannel.

Also adds 3 additional tests.
2021-06-07 19:39:20 +02:00
Amit Shirodkar a6d78c5e3e
fix build on ppc64le (#8141) 2021-06-07 00:10:29 -07:00
Eric Anderson 50012832de Bump Protobuf Gradle Plugin to 0.8.16
This version works around a warning about DuplicateStrategy in Gradle 6
that will be an error in Gradle 7 caused by [a bug in the plugin][1].
Bumping the version makes a clean build with `--warning-mode all` (at
least if skipping Android and codegen).

[1]: https://github.com/google/protobuf-gradle-plugin/issues/470
2021-06-04 07:55:58 -07:00
sanjaypujare d8d378454f
xds: remove XdsChannelBuilder and related code that uses old/unsupported interfaces (#8231) 2021-06-03 10:07:05 -07:00
Eric Anderson 005452f6cf Replace accidental U+FFFC with space in GH Action lock.yml 2021-06-03 07:43:50 -07:00
Eric Anderson 01a6364b05 Swap from the Lock GH App to lock-threads GH Action
The Lock App [is unhealthy][1]. GitHub Actions now has [a better
security model][2] such that we think we can safely use it.

The time of day to run the action was randomly generated.

[1]: https://github.com/dessant/lock-threads-app/issues/2
[2]: https://github.blog/changelog/2021-04-20-github-actions-control-permissions-for-github_token/
2021-06-02 15:51:12 -07:00
sanjaypujare 087d7bc7d5
xds: move the unsupported filterChainMatch matchers to the ranking stage for correct outcomes (#8219) 2021-06-02 10:10:58 -07:00
sanjaypujare 54b4e93927
xds: replace PriorityHeap with simpler logic that keeps track of top matches (#8225) 2021-06-02 10:09:42 -07:00
markb74 1cd925c3dd
Remove InternalMetadataHelper. (#8209)
This class wasn't really necessary.
2021-06-02 11:03:29 +02:00
Chengyuan Zhang a589c2c68f
xds: fix order of processing resolution errors with original cluster ordering (#8224)
When aggregating the endpoint resolution errors of the list of clusters in ClusterResolverLoadBalancer, clusters should be processed in its original order as received in the LB config. The last cluster's error is used as the overall error status.
2021-06-01 11:22:24 -07:00
Menghan Li d4e90a78fd
buildscript: fold header/path matching tests to all (#8054) 2021-05-27 09:47:50 -07:00
Chengyuan Zhang 8129c4e673
xds: import v3 RBAC http filter proto (#8215) 2021-05-27 09:43:56 -07:00
markb74 f88d362bc7
Fix the use of scheduler pools in BinderServer. (#8210)
Switch to using scheduled pools in BinderServer.
2021-05-27 13:37:22 +02:00
sanjaypujare bfcba82dd5
xds: remove MeshCaCertificateProvider and DynamicReloadingCertificate{Provider (#8214) 2021-05-26 19:35:51 -07:00
sanjaypujare 328071bbce
xds: replace DownstreamTlsContext by SslContextProviderSupplier in the Listener (#8205) 2021-05-26 14:42:47 -07:00
ZHANG Dapeng 6aeeba805f
xds: enhance delay injection error message on DEADLINE_EXCEEDED (#8185)
When an RPC is injected with a delay and then fails with DEADLINE_EXCEEDED (partially) due to the delay, it could confuse users if the error message does not mention the existence of the delay injection, because end users normally are not the same people who configured fault injection policy in control plane.
2021-05-26 14:35:45 -07:00
Eric Anderson a7792d3d14 Limit permissions to gradlew validator GH Action
I've already limited the grpc-wide setting to read-only access, but
limiting it explicitly here seems like a good idea; all workflows should
explicitly set their permissions since any action can implicitly access
the GITHUB_TOKEN.
2021-05-26 14:24:29 -07:00
Chengyuan Zhang 505594ac53
xds: change google_default/compute_engine creds to select TLS if the xDS cluster name is prefixed with 'google_cfe_' (#8152)
Following up changes in bbc5f61abb, the cluster_resolver LB policy uses the hostname received in CDS responses for discovering LOGICAL_DNS cluster endpoints.

Based on the new design, TD will generate a CFE cluster called "google_cfe_${service_name}" (e.g., for DirectPath service "cloud-bigtable.googleapis.com", the cluster name will be "google_cfe_cloud-bigtable.googleapis.com") for each DirectPath service. google_default/compute_engine creds will identify CFE clusters by the name having the prefix "google_cfe_".
2021-05-26 12:06:23 -07:00
Chengyuan Zhang bbc5f61abb
xds: use load assignment endpoint address in Cluster as the DNS hostname for LOGICAL_DNS (#8151)
Fixes the source of hostname used for DNS resolution in the cluster_resolver LB policy for LOGICAL_DNS clusters. The change includes:

- parse the single endpoint address from the embedded Cluster resource in CDS responses as the DNS hostname for LOGICAL_DNS cluster and include it in CdsUpdate being notified to the CDS LB policy.
- propagate the DNS hostname to the cluster_resolver LB policy via its LB config (DiscoveryMechanism for LOGICAL_DNS cluster).
- cluster_resolver LB policy takes the DNS hostname from the DiscoveryMechanism for LOGICAL_DNS cluster and use it as the name for DNS resolution.
2021-05-26 12:02:18 -07:00
markb74 8e18c11bbd
binder: BinderTransport implementation. (#8031)
This is the first major code drop for binderchannel, containing the transport class and its internals.
2021-05-26 14:54:32 +02:00
yifeizhuang 2239dd717c
tsan, xds: fix data race (#8206) 2021-05-25 13:35:09 -07:00
sanjaypujare 5b1c3fa12c
xds: shutDown the scheduledExecutorService when the provider is shutdown (#8198) 2021-05-24 12:45:01 -07:00
cfredri4 c8cd4cb260
netty: Support SocketAddress with ChannelCredentials (#8194)
This adds support for creating a Netty Channel with SocketAddress and ChannelCredentials.

This aligns with NettyServerBuilder.forAddress(SocketAddress address, ServerCredentials creds).
2021-05-24 09:49:20 -07:00
sanjaypujare 869b395ec0
xds: ignore unknown SAN name type instead of throwing exception (#8183) 2021-05-19 11:48:11 -07:00
Eric Gribkoff 465c932b41
Update README etc to reference 1.38.0 (#8189) 2021-05-19 00:09:36 -07:00
Chengyuan Zhang 86465b3399
xds: cluster_resolver LB policy should wait until all clusters being resolved before propagating endpoints to child LB policy (#8176)
Do not propagate partial endpoint discovery results to the child LB policy of cluster_resolver LB policy. This could avoid premature RPC failures when connections to resolved endpoints fail while there are other unresolved endpoints. Also, endpoints should be attempted in the order of clusters they belong to: endpoints from a lower-priority cluster should not be used before endpoints from a higher-priority cluster are attempted. Most importantly, it should not fallback to use DNS-resolved endpoints before all EDS-resolved endpoints failed.
2021-05-18 13:14:37 -07:00
Chengyuan Zhang e5d0e9d9a8
api, core: support zero copy into protobuf (#8102)
Enables a codepath for zero-copy protobuf deserialization. Two new InputStream extension interfaces are added:

- HasByteBuffer: allows access to the underlying buffers containing inbound bytes directly without copying
- Detachable: allows customer marshaller to keep the buffers around until the application code is done with using the protobuf messages

Applications can implement a custom marshaller that takes over the ownership of ByteBuffers and wrap them into ByteStrings with protobuf's UnsafeByteOperations support. Then a RopeByteString, which is a in-place composite of ByteStrings can be created. This enables using the zero-copy codepath (requires immutable ByteBuffer indication) of CodedInputStream for deserialization.
2021-05-14 14:45:03 -07:00
Chengyuan Zhang fd8964f7d1
Update README etc to reference 1.37.1 (#8179) 2021-05-14 12:42:28 -07:00
Chengyuan Zhang 413deb7f0c
xds: implement PriorityChildConfig toString() (#8173) 2021-05-12 16:01:40 -07:00
Chengyuan Zhang 2335eb5b63
xds: eliminate test verification for nondeterministic behaviors (#8172)
When the ring_hash LB policy enters TRANSIENT_FAILURE, it tries to connect one of the IDLE subchannels. Which subchannel to be connected to is non-deterministic, it just choose the first one from the subchannels map.

The existing test creates 4 subchannels, brings down 2 of them to let ring_hash LB policy enter TRANSIENT_FAILURE. But which one fo the remaining two subchannels to be kicked off connection is nondeterministic. This introduces trouble for verifying the behavior. This change simplifies the test, to only create 3 subchannels so that there is only one single subchannel remaining in IDLE after bringing the other two down. We are able to easily verify the behavior of ring_hash LB policy requesting connection for that one subchannel.
2021-05-12 14:17:21 -07:00
sanjaypujare e59604b7ce
xds: add null reference checks in SslContextProviderSupplier (#8169) 2021-05-12 10:27:44 -07:00
Eric Anderson e08b9db208
Use @DoNotCall for static methods in Builders that throw
Since static methods are pseudo-inherited by Builder implementations but
are trivially accidentally used, we re-define static methods in each
builder to make them behave more like the caller would expect. However,
not all the methods actually work; some just throw because the caller
was certainly not getting what they would expect.

Annotating with `@DoNotCall` can expose the problems at compile time
instead of runtime. While `@Deprecated` would also be an option, it is a
bit harder to figure out the ramifications and whether we want to go
that route.

This change was suggested by a lint tool for XdsServerBuilder and it
seems appropriate so I applied it to the other similar cases I could
find.
2021-05-12 10:12:52 -07:00
Leonardo Pistone 1a655622c7
Document that xds uses grpc-netty-shaded (#7877) 2021-05-11 19:19:40 -07:00
Eric Anderson 1882c47eb9 netty: Remove Maven pom.properties from netty-shaded
The pom.properties are apparently present to allow tooling to know what
Maven artifact cooresponds to a JAR, just by looking at the JAR. Since
we shade Netty, that produces inaccurate results. This was noticed in
in #8077.
2021-05-11 15:36:44 -07:00
ZHANG Dapeng 8dc16cd569
okhttp: let frameReader report existing goAwayStatus when socket closed
`OkHttpClientTransport.ClientFrameHandler` will fail a stream with `Status.UNAVAILABLE.withDescription("End of stream or IOException")` when socket is closed with an error. However, it does not include any more error detail. This PR provides more error detail in case there is an existing goaway status, e.g. netty server can send goaway with lastKnownStreamId=MAX_INT when header size exceeded max allowed size netty/netty/pull/10775 and shutdown the connection.

Test: `io.grpc.okhttp.OkHttpTransportTest.serverChecksInboundMetadataSize` with `netty-4.1.54.Final`
2021-05-11 14:23:39 -07:00
Chengyuan Zhang f4fe466fb0
xds: lazily and only parse headers with matchers matching the key (#8163)
In normal cases, we only have a few header matchers but the number of headers can be completely up to the application. Indexing headers eagerly parses all headers, even for those with no matcher matching the key. We should only parse header values for those with key matching the header matcher (aka, only call Metadata.get() with key that has some matcher looking for).
2021-05-11 14:20:02 -07:00
Chengyuan Zhang dbc5786c30
xds: ring_hash self recover from TRANSIENT_FAILURE by attempting to connect one subchannel (#8144)
Kicks off connection for one of IDLE subchannels (if exist) when the ring_hash LB policy is reporting TRANSIENT_FAILURE to its upstream.

While the ring_hash policy is reporting TRANSIENT_FAILURE, it will not be getting any pick requests from the priority policy. However, because the ring_hash policy does not attempt to reconnect to subchannels unless it is getting pick requests, it will need special handling to ensure that it will eventually recover from TRANSIENT_FAILURE state once the problem is resolved. Specifically, it will make sure that it is attempting to connect (after applicable backoff period) to at least one subchannel at any given time.
2021-05-11 01:58:57 -07:00
sanjaypujare 0c2d8edc4c
xds: refactor TlsContextManager related code to remove dependency on Bootstrapper (#8150) 2021-05-10 13:13:26 -07:00
Chengyuan Zhang c7afb89708
grpclb: use a standalone Context for gRPCLB control plane RPCs (#8154)
Inject a standalone Context that is independent of application RPCs to GrpclbLoadBalancer for control plane RPCs. The control plane RPC should be independent and not impacted by the lifetime of Context used for application RPCs.
2021-05-10 10:21:36 -07:00
Chengyuan Zhang 7b09056aa4
xds: use a standalone Context for xDS control plane RPCs (#8153)
Control plane RPCs are independent of application RPCs, they can stand for completely different lifetime. So the context for making application RPCs should not be propagated to control plane RPCs. This change makes control plane RPCs use the ROOT Context.
2021-05-07 18:00:47 -07:00
Sergii Tkachenko 976daf2dd0 buildscripts: switch xds-k8s cluster to 1.20.x 2021-05-05 20:01:15 -04:00
Eric Gribkoff c0eca6de25
Start 1.39.0 development cycle (#8147) 2021-05-05 16:30:38 -07:00
Lidi Zheng d2160ea703
Extend the xDS interop tests timeout to 360 mins (#8133) 2021-05-05 10:18:44 -07:00
sanjaypujare c9e327d42f
xds: extend SslContextProviderSupplier to DowmstreamTlsContext for server side (#8146) 2021-05-04 22:19:15 -07:00
yifeizhuang 27b1641653
xds: import envoy (#8145) 2021-05-04 16:20:44 -07:00
Chengyuan Zhang fcaf9a9583
xds: ignore balancing state update from downstream after LB shutdown (#8134)
LoadBalancers should not propagate balancing state updates after itself being shutdown.

For LB policies that maintain a group of child LB policies with each having its independent lifetime, balancing state update propagations from each child LB policy can go out of the lifetime of its parent easily, especially for cases that balancing state update is put to the back of the queue and not propagated up inline.

For LBs that are simple pass-through in the middle of the LB tree structure, it isn't a big issue as its lifecycle would be the same as its child. Transitively, It would behave correctly as long as its downstream is doing in the right way.

This change is a sanity cleanup for LB policies that maintain multiple child LB policies to preserve the invariant that further balancing state updates from their child policies will not get propagated.
2021-05-04 15:56:56 -07:00
Chengyuan Zhang ee000f0dc1
xds: throw away subchannel references after ring_hash is shutdown (#8140)
Similar to 368c43aec4. 

Clean up subchannels after the RingHashLoadBalancer itself is shutdown to prevent further balancing state updates being propagated to the upstream.

Note this should not be considered as a fix for any problem anybody is noticing. Upstreams of RingHashLoadBalancer should not rely on this, it should still have its own logic for maintaining the lifecycle of downstream LB and ignore invalid upcalls when necessary.
2021-05-04 13:35:37 -07:00
Eric Anderson 16eb5a47ec Stabilize ChannelCredentials
Some of the experimental API annotations were changed to other issues or
became `@Internal` to match their related APIs.

Fixes #7479
2021-05-03 16:22:43 -07:00
Eric Anderson d42f3b8fcb Stabilize ServerCredentials
Some of the experimental API annotations were changed to other issues or
became @Internal to match their related APIs.

Fixes #7621
2021-05-03 16:10:24 -07:00
Joris Scharp f0c9ae26d7 examples: exporting the io.grpc.examples.manualflowcontrol client & server to the example bin output folder. This commit improves gRPC to quickly find out this example exists, instead of having to go through the source code. 2021-05-03 10:57:42 -07:00
Chengyuan Zhang 4a339e41ba
xds: fix URI creation used to instantiate DNS name resolver (#8129)
When creating the URI using Channel authority for instantiating a DNS resolver in the cluster_resolver LB policy, a "dns" scheme needs to be manually attached and the Channel authority would be used as the URI path (same as creating Channel with target). Otherwise, the Channel authority will just be used as the scheme and causing name resolver not found.

The change also handles name resolver lookup more defensively. Although it should not happen, if there does have bug causing DNS resolver not being able to be loaded, the cluster_resolver LB policy propagates the INTERNAL error to upstream.
2021-04-30 18:10:40 -07:00
Chengyuan Zhang 368c43aec4
core: throw away subchannel references after round_robin is shutdown (#8132)
Triggering balancing state updates after already being shutdown can be confusing for the upstream of round_robin. In cases of the callers not managing round_robin's lifecycle (e.g., not ignoring updates after it shuts down round_robin, which it should), it can make problem very bad, especially with the behavior that round_robin is actually propagating TRANSIENT_FAILURE with a picker that buffers RPCs.

This change only polishes round_robin by always preserving its invariant. Callers/LBs should not rely on this and should still manage the balancing updates from its downstream correctly based on the downstream's lifetime.
2021-04-30 15:42:44 -07:00
sanjaypujare 02ff64fa21
xds: use singleton XdsClient for server side (#8130) 2021-04-30 09:52:56 -07:00
Chengyuan Zhang 5d99bb07b8
xds: pretty print ClusterConfig message (#8128)
Adds ClusterConfig message descriptor to message printer.
2021-04-29 18:04:03 -07:00
Chengyuan Zhang 42d7fba1b8
xds: implement toString() for pickers to visualize selectable hosts (#8123)
Implements toString() for the wrapping SubchannelPickers so that we are able to see how hosts are selected when sending out RPCs.
2021-04-28 15:16:30 -07:00
Jan Tattermusch 72527708f5
skip flaky :grpc-xds:test in linux aarch64 tests (#8119)
Due to #8118 the :grpc-xds:test currently doesn't provide useful signal.
2021-04-27 10:18:39 -07:00
Sergii Tkachenko fcbc1abc44 buildscripts: xds-k8s pin pip to 21.0.1
pip 21.1 released on Apr 24 introduced a regression for python 3.6.1.
The regression was identified on Apr 24, the fix merged on Apr 25.
The fix is expected to be delivered in the 21.1.1 patch.

There's no clear date, when 21.1.1 will be released.
Until then, pin is temporarily pinned to the previous release, 21.0.1.
2021-04-26 18:15:18 -04:00
yifeizhuang 6755cfed34
tsan, xds: fix XdsClientWrapperForServerSds data races (#8107) 2021-04-26 14:37:11 -07:00
yifeizhuang 8468b5c42f
tsan, xds: fix data races in ServerWrapperForXds (#8114) 2021-04-26 11:58:32 -07:00
Jan Tattermusch b436d0dfb7
Improve emulated linux aarch64 tests, without protoc artifact build
Based on my testing, the tests are currently flaky, so it would be better to first merge it and start running it continuously to asses the situation.
2021-04-26 10:54:28 -07:00
Chengyuan Zhang f33658a6d7
Migrate away from Jcenter (#8111)
Replaces jcenter with mavenCentral.
2021-04-22 15:59:36 -07:00
Lidi Zheng 134e9cbc42
buildscripts: enable CSDS test 2021-04-21 20:48:34 -04:00
Eric Anderson 2eb0a95305 Bump Guava to 30.1 for Bazel
This was missed from a81bf14
2021-04-21 15:49:52 -07:00
ZhenLian 1703d692bc
advancedtls: Add a Utility Class For Loading Certs/Keys (#8023) 2021-04-21 10:07:44 -07:00
Eric Anderson 8a9aa41416 all: Only depend on evaluation of enumerated subprojects
Back in 10fb206 when this for loop was added, we didn't have the
subprojects list. That was added in 9bd7bab, but I failed to update one
reference to rootProject. So all has had an evaluation dependency on all
projects, even though it only needs a subset.

This should have little impact, but would prevent weird scenarios like
an issue in :grpc-gae-interop-testing-jdk8 preventing :all-all from
being loaded. Not to say things wouldn't still fail to load, but that
this bug could distract from the real problem. I noticed this
during #8049.
2021-04-19 14:18:54 -07:00
Eric Anderson 84dc5642bc Allow both old and new behavior from google-auth-library-java
google-auth-library-java:0.25.0 strips port and path parts in the
audience claim ("aud"). Updating the test to pass in both old
and new version of google-auth-library-java.

This commit does not upgrade google-auth-library-java because
it turned out that the upgrade involves the newer Guava version
(google-auth-library-java's dependency) failing with DexingNoClasspathTransform.
Details: https://github.com/grpc/grpc-java/pull/8078#issuecomment-821566805
It's technically possible to exclude the newer Guava, but it's a
good practice avoid excluding the newer version of a library.
2021-04-19 14:13:23 -07:00
Eric Anderson a81bf14f1f Upgrade to Guava 30.1, which warns on Java 7
This change can have large impact from two aspects:
1. It calls out a _large_ impact on the _few_ Java 7 users.
2. It may have _small_ impact on the _many_ Android users.

https://github.com/grpc/grpc-java/issues/4671 tracks gRPC's removal of
Java 7 support. We are quite eager to drop Java 7 support as that would
allow using new language features like default methods. Guava is also
dropping Java 7 support and starting in 30.1 it will warn when used on
Java 7. The purpose of the warning is to help discover users that are
negatively impacted by dropping Java 7 before it becomes a bigger
problem.

The Guava logging check was implemented in such a way that there is an
optional class that uses Java 8 bytecode. While the class is optional at
runtime, the Android build system notices when dexing and fails if
Java 8 language featutres are not enabled. We believe this will not be a
problem for most Android users, but they may need to add to their build:

```
android {
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}
```

See also https://github.com/google/guava/releases/tag/v30.1
2021-04-19 09:16:00 -07:00
Chengyuan Zhang bab1fe38dc
services: move classes with protobuf dependency into io.grpc.protobuf.services (#8056)
To separately manage services/classes with and without protobuf dependency in services package, we are moving classes with protobuf dependency into io.grpc.protobuf.services. This includes healthchecking, reflection, channelz, and binlogging.

Forwarding classes are created to avoid breaking existing users, while they are marked as deprecated to notify users to migrate.
2021-04-16 17:27:12 -07:00
ZHANG Dapeng eb6764841b
netty: fix status message when GOAWAY at MAX_CONCURRENT_STREAMS limit
Resolves #8097
2021-04-16 16:10:38 -07:00
ZHANG Dapeng 49f9380fc9
netty: fix StreamBufferingEncoder GOAWAY bug
Fix a bug in StreamBufferingEncoder: when client receives GOWAY while there are pending streams due to MAX_CONCURRENT_STREAMS, we see the following error:
io.netty.handler.codec.http2.Http2Exception$StreamException: Maximum active streams violated for this endpoint.
2021-04-16 14:23:14 -07:00
Chengyuan Zhang b4fe07d22d
xds: support ring_hash as the endpoint-level LB policy (#7991)
Update LB policy config generation to support ring hash policy as the endpoint-level LB policy.

- Changed the CDS LB policy to accept RING_HASH as the endpoint LB policy from CDS updates. This configuration is directly passed to its child policy (aka, ClusterResolverLoadBalancer) in its config.

- Changed ClusterResolverLoadBalancer to generate different LB configs for its downstream LB policies, depending on the endpoint-level LB policies.
  - If the endpoint-level LB policy is ROUND_ROBIN, the downstream LB policy hierarchy is: PriorityLB -> ClusterImplLB -> WeightedTargetLB -> RoundRobinLB
  - If the endpoin-level LB policy is RNIG_HASH, the downstream LB policy hierarchy is: PriorityLB -> ClusterImplLB -> RingHashLB.
2021-04-16 12:46:55 -07:00
Eric Anderson 31cfb6d32e
all: JacocoMerge must run after grpc-interop-testing's tests (#8093)
Otherwise the executionData would be out-of-date.
2021-04-16 11:10:04 -07:00
Chengyuan Zhang 9614738a7d
core, grpclb, xds: let leaf LB policies explicitly refresh name resolution when subchannel connection is broken (#8048)
Currently each subchannel implicitly refreshes the name resolution when its state changes to IDLE or TRANSIENT_FAILURE. That is, this feature is built into subchannel's internal implementation. Although it eliminates the burden of having LB implementations refreshing the resolver when connections to backends are broken, this is gives LB policies no chance to disable or override this refresh (e.g., in some complex load balancing hierarchy like xDS, LB policies may embed a resolver inside for resolving backends so the refreshing resolution operation should be hooked to the resolver embedded in the LB policy instead of the one in Channel).

In order to make this transition smoothly, we add a check to SubchannelImpl that checks if the LoadBalancer has explicitly called Helper.refreshNameResolution for broken subchannels created by it. If not, it logs a warning and do the refresh.

A temporary LoadBalancer.Helper API ignoreRefreshNameResolution() is added to avoid false-positive warnings for xDS that intentionally does not want a refresh. Once the migration is done, this should be deleted.
2021-04-16 10:49:06 -07:00
Eric Anderson 384f4c401d context: Add docs describing common Key usage
This recently came up in https://stackoverflow.com/a/67062503/4690866,
but it has come up multiple times before. These docs aren't ideal, as
they may be missed by a reader and so references in other parts of the
API would probably be appropriate. There could also be something about
"Context is not a general purpose map." But this is an improvement, and
I didn't want to let the perfect be the enemy of the good.
2021-04-16 09:36:16 -07:00
Tomo Suzuki 4ad49266ec OkHttpClientTransportTest's proxy to use localhost
Fixes #8080. The address 0.0.0.0 (that comes from new Socket(0).
.getLocalSocketAddress()) is for listening with a server, but it
is not meant to be used as the destination address as per
"3.2.1.3 Addressing" in RFC 1122
2021-04-15 10:57:54 -07:00
ZHANG Dapeng d25ebaf57d
core: fix NPE in ConfigSelectingClientCall
Fix the following bug:

ManagedChannelImpl.ConfigSelectingClientCall may return early in start() leaving delegate null, and fails request() method after start().

Currently the bug can only be triggered when using xDS.
2021-04-14 23:06:37 -07:00
Chengyuan Zhang d4fa0ecc07
xds: reduce the size of ring for testing pick distributions (#8079)
In the ring hash LB policy, building the ring is computationally heavy. Although using a larger ring can make the RPC distribution closer to the actual weights of hosts, it takes long time to finish the test.

Internally, each test class is expected to finish within 1 minute, while each of the test cases for testing pick distribution takes about 30 sec. By reducing the ring size by a factor of 10, the time spent for those test cases reduce to 1-2 seconds. Now we need larger tolerance for the distribution (three hosts with weights 1:10:100):

- With a ring size of 100000, the 10000 RPCs distribution is close to 91 : 866 : 9043
- With a ring size of 10000, the 10000 RPCs distribution is close to 104 : 808 : 9088

Roughly, this is still acceptable.
2021-04-12 14:55:31 -07:00
Sergii Tkachenko 278a336d1f buildscript: xds-k8s increase build timeout 2021-04-08 22:05:29 -04:00
Sergii Tkachenko c113ba1030 buildscript: add xds-k8s cluster endpoint override
Missed this in 1b86618ce9
2021-04-08 21:14:08 -04:00
Chengyuan Zhang 95adf96848
xds: implement ring_hash load balancing policy (#7943)
Implementation for the ring hash LB policy. A LoadBalancer that provides consistent hashing based load balancing to upstream hosts, with the "Ketama" hashing that maps hosts onto a circle (the "ring") by hashing its addresses. Each request is routed to a host by hashing some property of the request and finding the nearest corresponding host clockwise around the ring. Each host is placed on the ring some number of times proportional to its weight. With the ring partitioned appropriately, the addition or removal of one host from a set of N hosts will affect only 1/N requests.
2021-04-08 17:58:45 -07:00
Sergii Tkachenko 1b86618ce9 buildscript: use different xds-k8s cluster
In preparation to the Public Preview.
2021-04-08 19:00:34 -04:00
Sergii Tkachenko d971fe629c RELEASING.md: remove JCenter note
JFrog has announced that they are shutting down the JCenter: https://jfrog.com/blog/into-the-sunset-bintray-jcenter-gocenter-and-chartcenter/
2021-04-08 14:03:33 -04:00
Sergii Tkachenko 1b996b171b Update README etc to reference 1.37.0 2021-04-08 12:34:06 -04:00
Sergii Tkachenko 6ad3f5d9e4 xds: Fix error prone UnnecessaryJavacSuppressWarnings in a test 2021-04-07 21:59:31 -04:00
Chengyuan Zhang b956f8852d
grpclb: include fallback reason in error status of failing to fallback (#8035)
Enhance error information reflected by RPC status when failing to fallback (aka, no fallback addresses provided by resolver), by including the original cause of entering fallback. Cases to fallback include:

  - When the fallback timer fires before we have received the first response from the balancer.
     - If no fallback addresses are found, RPCs will be failed with status {UNAVAILABLE, description="Unable to fallback, no fallback addresses found\n Timeout waiting for remote balancer", cause=null}
  - When the balancer RPC finishes before receiving any backend addresses
     - If no fallback addresses are found, RPCs will be failed with status {UNAVAILABLE, description="Unable to fallback, no fallback addresses found\n <description from the status of balancer RPC>", cause=<cause from the status of balancer RPC>}
  - When we get an explicit response from the balancer telling us go into fallback
     - If no fallback addresses are found, RPCs will be failed with status {UNAVAILABLE, description="Unable to fallback, no fallback addresses found\n Fallback requested by balancer", cause=null}
  - When the balancer call has finished *and* we cannot connect to any of the backends in the last response we received from the balancer.
     - Depending on whichever the two happened last, the last happening one is the reason that triggers entering fallback. If no fallback addresses are found, RPCs will be failed with status {UNAVAILABLE, description="Unable to fallback, no fallback addresses found\n <description from the status of balancer RPC>", cause=<cause from the status of balancer RPC>} or {UNAVAILABLE, description="Unable to fallback, no fallback addresses found\n <description from the status of one of the broken subchannels>", cause=<cause from the status of one of the broken subchannels>}

Note all RPCs will fail with UNAVAILABLE status code, the fallback reason will be attached as description and cause (if any).
2021-04-07 18:06:32 -07:00
Sergii Tkachenko 239db4b381 RELEASING.md: Add pre-tagging internal step 2021-04-07 16:36:58 -04:00
sanjaypujare 1a3b02b44b
xds: cache bootstrapInfo in the SslContextProviderFactory to prevent rereading (#8051) 2021-04-05 16:26:29 -07:00
Eric Anderson 5e9a7b6e2f
bom: Do not include grpc-binder (#8038)
Binder is not yet being published, so this artifact wouldn't exist.
2021-04-02 13:03:08 -07:00
sanjaypujare d9956a53df
xds: Fix validation of HCM filter and Router httpFilter (#8039)
* add 1 more check that works with TD now
2021-04-02 09:48:13 -07:00
Eric Anderson d8061c4ced netty: Add support for OpenJSSE
Tested with the interop client on Zulu 8 and Zulu 11 with
-XX:+UseOpenJSSE (after disabling tcnative). I was unable to add a new
case to TlsTest because adding OpenJSSE as a dependency in a Gradle
build fails: https://github.com/openjsse/openjsse/issues/19

Fixes #7907
2021-04-02 09:32:14 -07:00
sanjaypujare ac6461dfe5
xds: expose bootstrap through XdsClient interface (#8041) 2021-04-01 18:45:46 -07:00
markb74 9fc32f1bc9
binder: Add LeakSafeOneWayBinder and tests. (#8021)
Another util class, this one with tests which need to run on
an Android emulator.
2021-03-31 17:39:10 +01:00
Sergii Tkachenko 11c3667b8c interop-testing: xDS interop app uses AdminInterface 2021-03-30 21:23:19 -04:00
sanjaypujare 4896a0fee8
xds: move the state check logic to delegate and eliminate boilerplate code (#8018) 2021-03-25 16:52:15 -07:00
Sergii Tkachenko e4b292aa9b Start 1.38.0 development cycle 2021-03-25 18:49:03 -04:00
Sergii Tkachenko 828b03da27 xds: add CsdsService 2021-03-25 16:20:30 -04:00
Sergii Tkachenko b417b70db1 xds: add csds.proto (v3) with dependencies, generated code 2021-03-25 16:20:30 -04:00
Chengyuan Zhang ad2b26436c
xds: update (local) configurations atomically for each LDS/RDS resource update (#8011)
Fixes inconsistent state of XdsNameResolver with most recently received xDS configurations. The full suite of configurations should always be updated whenever receiving new resource updates, including updates that revoke currently in-use resources. Reference counts for currently in-use clusters should also be cleaned up properly. Otherwise, re-receiving (after being revoked) the same resource can be treated as if the configuration never changed.
2021-03-24 17:06:03 -07:00
ZHANG Dapeng ccedd85418
xds: enforce non-null overrideConfigs field for http filters 2021-03-24 17:05:17 -07:00
markb74 c6d48f7cb1
binder: Some basic binderchannel util code (#7796)
This just adds the ServiceBinding class and
BindServiceFlags, internal utils.

Most binderchannel code relies heavily on Java8 features,
so I'm keeping that requirement, since grpc-java plans to
require Java8 eventually anyway.
2021-03-24 15:40:11 -07:00
ZHANG Dapeng 3ccc6792d5
xds: enable circuit breaking, timeout, fault injection by default 2021-03-24 14:50:59 -07:00
sanjaypujare b7afbc30d1
xds: remove syncContext and just use the executorService (#8006) 2021-03-24 12:41:58 -07:00
sanjaypujare c4dec7517f
xds: add/enhance Javadoc comments for XdsServerBuilder. (#8007) 2021-03-23 10:53:21 -07:00
Eric Anderson 931d95d3f3 okhttp: Fix okio 2.x API incompatibility
okio 2.x is ABI compatible with 1.x but not API compatible. This hasn't
been a problem as users use binaries from Maven Central so the ABI
compatibility is the important part. However, when building with Bazel
the API compatibily is the important part.

Tested with okio 2.10.0

Fixes #8004
2021-03-22 17:55:54 -07:00
Sergii Tkachenko 8ff0b23c2e
xds: ADS parsing: collect parsing errors on NACK; cache resources on ACK 2021-03-22 20:34:03 -04:00
Chengyuan Zhang b2e475712d
alts: make both GoogleDefaultChannelCredentials and ComputeEngineChannelCredentials choose ALTS for backends given by xDS TD (#7999)
GoogleDefaultChannelCredentials and ComputeEngineChannelCredentials are literally the same thing for DirectPath, both of them should behave the same for choosing the protocol negotiator for talking to backends given by Traffic Director.
2021-03-19 17:01:05 -07:00
apolcyn ccd43b64e3
xds: enable v3 API in bootstrap generated by cloud-to-prod resolver (#7995) 2021-03-19 15:26:15 -07:00
apolcyn ab216a1720
interop-testing, xds: Allow using TestServiceClient for making Traffic Director RPCs (#7994)
Updates TestServiceClient to support creating channel without target port (mostly useful for xDS that uses the channel target as the resource name).

Adds an env var for overriding the TD URI used in cloud-to-prod test.
2021-03-19 12:44:52 -07:00
yifeizhuang 043c9d6407
xds: weightedTargetLB collect all failure child pickers to log more error details (#7989) 2021-03-18 17:39:48 -07:00
Chengyuan Zhang f0512db060
xds: delete redundant hash function configuration (#7950)
Initially we were about to support both xx_hash and murmur_hash. But later we decided to support xx_hash only. So for any hashing we are using in xDS, it's going to be xx_hash. Therefore, we do not need to define and carry this configuration around.
2021-03-18 11:48:25 -07:00
sanjaypujare a460f784c6
xds: fix filterChainMatch for multiple matchers, 0-length prefixLength and empty prefixRange list (#7985) 2021-03-18 10:22:35 -07:00
sanjaypujare cd3b0c4412
xds: clean up to remove the cert-instance-override related code (#7986) 2021-03-18 10:22:04 -07:00
Penn (Dapeng) Zhang e8d935e5c9 xds: pretty print http filters 2021-03-18 10:13:36 -07:00
Penn (Dapeng) Zhang 9950d30881 xds: import envoy router.proto 2021-03-18 10:13:36 -07:00
ZHANG Dapeng e4ccf0eeac
buildscript: enable fault injection interop test 2021-03-17 17:41:58 -07:00
ZHANG Dapeng 3ebb3e1924
xds: HttpFilter support 2021-03-17 16:37:13 -07:00
sanjaypujare 69587c5239
xds: use the correct resource id template as per xDS server gRFC (#7978) 2021-03-17 08:22:59 -07:00
Eric Anderson c26ee03cd9 netty: Add Http2Headers.setLong() for inbound headers
Starting in Netty 4.1.60, Netty will validate Content-Length headers
using getAll() and setLong(). While getAll() was documented as only used
in tests, it doesn't appear it was currently used in any tests.

While Http2NettyTest.contentLengthPermitted() was added to confirm that
Content-Length works, it won't actually exercise any interesting
behavior until we upgrade to Netty 4.1.60. However, I did test with
Netty 4.1.60 and it reproduced the failure in
https://github.com/grpc/grpc-java/issues/7953 and passed with this
change.

Since Netty is now observing/modifying the headers, it would seem
appropriate to implement a substantial portion of the Http2Headers API.
However, the surface is much larger than we'd want to implement for a
'quick fix' that could be backported. In addition, it seems much of the
API is just convenience methods, so it is probably appropriate to split
out a AbstractHeaders class from DefaultHeaders in Netty that doesn't
make any assumptions about the header storage mechanism.
2021-03-16 16:36:18 -07:00
sanjaypujare 224247cf02
xds: implement xDS server validations (#7972) 2021-03-16 15:24:04 -07:00
yifeizhuang 71c4ef730e
xds:fix cdsLoadBalancer2 childLb shutdown (#7971) 2021-03-16 12:37:05 -07:00
sanjaypujare be6192e82a
xds: replace ServerXdsClient with ClientXdsClient (#7969) 2021-03-16 11:23:41 -07:00
Ulf Adams f872c6059d
Add .ijwb to .gitignore (#7970)
.ijwb is used for the Bazel IntelliJ plugin.
2021-03-15 01:50:13 -07:00
Chengyuan Zhang c3caafa5ae
grpclb: turn into TRANSIENT_FAILURE if given (by balancer or fallback) an empty list of addresses (#7960)
Turn LB state into TRANSIENT_FAILURE if the list of backend addresses given to be used is found to be empty. It applies to both cases in which the address list is given by the balancer or the resolver (aka, the fallback list).
2021-03-12 17:25:32 -08:00
Eric Anderson 706188ac3c
example-tls: Port to Tls{Channel,Server}Credentials
Using the new credentials API allows using generic APIs instead of
Netty-specific ones and allows using grpc-netty-shaded. The new API is
still marked experimental, but it is intended to be stabilized which
isn't the case for the Netty-specific API.

The client now looks more similar to HelloWorldClient.
2021-03-12 15:46:59 -08:00
ZHANG Dapeng 3f7aa8c592
xds: fix Node.toBuilder() bug 2021-03-12 14:06:00 -08:00
Chengyuan Zhang 8e1c9b6948
xds: change system property for reading bootstrap config (#7961)
Changes from "io.grpc.xds.bootstrapValue" to "io.grpc.xds.bootstrapConfig".
2021-03-12 13:54:58 -08:00
Chengyuan Zhang 9c562c8a6f
grpclb: should not ignore subchannels with CONNECTING state in aggregating the overall LB state (#7959)
We should treat both IDLE and CONNECTING subchannels as "connection in progress" when aggregating for the overall load balancing state. Otherwise, RPCs could fail prematurely if one subchannel enters TF while all the others are still in CONNECTING.

23d279660c made each individual subchannel stay in TF until READY if it previously was in TF. So subchannels with CONNECTING state are those in first time connecting. We should give them time to connect.
2021-03-11 16:48:01 -08:00
sanjaypujare afe883119d
xds: add server side Listener processing to ClientXdsClient (#7955)
* xds: add server side Listener processing to ClientXdsClient

* address review comments

* minor fixes for review comments
2021-03-11 16:23:50 -08:00
yifeizhuang 6a9c9901e4
grpclb: support multiple authorities in lb backends for all SRV records (#7951) 2021-03-11 13:29:41 -08:00
apolcyn 972fda2cd7
Add a flag to interop clients to allow statically configuring grpclb (#7957) 2021-03-11 10:55:18 -08:00
yifeizhuang 528ef63c58
core: Move negotiationLogger from channel attributes to GrpcHttp2ConnectionHandler (#7933) 2021-03-10 16:43:56 -08:00
ZHANG Dapeng 2ca28a2903
stub: stabilize StreamObserver APIs
Resolves #1788
2021-03-10 13:41:31 -08:00
Jiangtao Li bb737a2e31
alts: remove confusing constant name in InternalCheckGcpEnvironment.java (#7954) 2021-03-10 10:00:44 -08:00
Sergii Tkachenko c8d3cf23e6
xds: Simplify ClientXdsClientTestBase by reusing test resources 2021-03-08 09:14:22 -08:00
Chengyuan Zhang 4b52639aa1
xds: implement per-RPC hash generation (#7922)
Generates a hash value for each RPC based on the HashPolicies configured for the Route that the RPC is routed to.
2021-03-05 10:51:42 -08:00
Chengyuan Zhang b5c0a4a97a Make addServices() a final method on ServerBuilder and delete from its forwarders. 2021-03-05 10:03:22 -08:00
Chengyuan Zhang 9e2c817cd8 Make AltsServerBuilder extend ForwardingServerBuilder. 2021-03-05 10:03:22 -08:00
Chengyuan Zhang 18f5fc2d7f
api: implement admin interface API (#7928)
Adds an AdminInterface API that automatically loads available admin services (currently, only supports Channelz and CSDS).
2021-03-04 16:53:03 -08:00
Chengyuan Zhang 37b94b3074
api: delete deprecated NameResolver APIs (#7936)
Deletes deprecated (~2 years) NameResolver APIs that uses NameResolver.Helper/Attributes for passing information from Channel to resolver.
2021-03-04 13:08:18 -08:00
Sergii Tkachenko cf99e8a7b2
xds: add helper to unpack compatible com.google.protobuf.Any messages 2021-03-03 14:46:44 -08:00
Chengyuan Zhang e5ab4d743d
grpclb: fix race between address update and LB stream recreation (#7934)
When the LB stream has been closed and a retry task is scheduled. Receiving a ResolvedAddress update with LB addresses immediately creates a new RPC stream again. Then when the retry task fires, a LB stream already exists.

This change cancels the retry task when the address update causing a new LB stream to be created.
2021-03-02 22:43:26 -08:00
sanjaypujare 46a136d62b
xds: implement listener deletion/re-add and server serving/not-serving logic (#7919) 2021-03-02 10:47:50 -08:00
Chengyuan Zhang a3ca6321ba
xds: fix typo in handling malformed cluster config (#7930) 2021-03-01 16:58:23 -08:00
Chengyuan Zhang a598b973a3
api: add ServerBuilder.addServices() API (#7926) 2021-02-28 23:36:27 -08:00
Eric Anderson cfe7d7c00d Add Codecov.io badge for code coverage
We find codecov.io generally more useful than coveralls.io, so make it a
bit easier to dig into the coverage.

We put it second simply because when people think "test coverage"
without any other details they (rightly) generally assume line coverage;
condition coverage is generally a separate metric. Codecov uses a
combined line+condition coverage metric which is pretty nice, but
if you are unfamiliar with it it appears like code coverage is lower
than it actually is.
2021-02-26 15:19:16 -08:00
ZHANG Dapeng 14432dfe67
xds: import udpa/type/v1/typed_struct.proto 2021-02-26 12:22:04 -08:00
Chengyuan Zhang 7a92de619b
xds: add env var protection for google-c2p resolver (#7918) 2021-02-25 17:55:05 -08:00
ZHANG Dapeng 9b803f338b
Revert "stub: Have ClientCalls.ThreadlessExecutor reject Runnables after end of RPC" (#7920)
This reverts commit 61e0f30 (#7798).

Our stub/core implementation had a bug (#7921) that might make it possible to leak cancellation through to the executor multiple times, typically when a custom interceptor is used. Revert this commit because import of grpc to google internal fails. We think the bug found in the import is legit and in our code. So we revert this change to avoid hurting users until the underlying issue is fixed.
2021-02-25 15:46:17 -08:00
Eric Anderson ae574434ee Update README etc to reference 1.36.0 2021-02-24 10:51:14 -08:00
Nick Hill 61e0f30e38
stub: Have ClientCalls.ThreadlessExecutor reject Runnables after end of RPC
Changes originally proposed as part of #7106.

Fixes #3557
2021-02-23 15:58:05 -08:00
Chengyuan Zhang 2bfa0037ad
xds: implement cloud-to-prod resolver (#7900)
Implemented CloudToProdNameResolver, which will be used for DirectPath with URI scheme "google-c2p". The resolver is only a wrapper that delegates name resolution either to DNS or xDS resolver depending on the environment. If it is delegating to the xDS resolver, it will send HTTP requests (to a local HTTP server) to fetch metadata that is used to generate a bootstrap config. The self-generated bootstrap will be used for xDS.
2021-02-23 12:27:47 -08:00
sanjaypujare bfc67bfcf4
xds: remove the env var GRPC_XDS_EXPERIMENTAL_NEW_SERVER_API (#7914) 2021-02-23 11:15:22 -08:00
Eric Anderson 6fb84bc61c Call the HTTP/2 close() so that GOAWAY is issued 2021-02-22 22:45:24 -08:00
Eric Anderson f2eb0af550 netty: Allow handshakes to be interrupted by channel shutdown
If a handshake is ongoing during shutdown, this would substantially
reduce the time it takes to shut down. Previously, you would need to use
channel.shutdownNow() to have fast shutdown behavior, which is an
unnecessary use of the variant.

When the current approach was written WriteBufferingAndExceptionHandler
didn't exist and so it was hard to predict how the pipeline would react
to events (particularly because of HTTP/2 handler's re-definition of
close()). Now that WBAEH exists, this is more straight-forward.
2021-02-22 22:45:24 -08:00
Chengyuan Zhang 22d1af0c89
xds: implement simple safe and allocation-free xx_hash (#7912)
Implement a simple allocation-free xx_hash utility class without using sun.misc.Unsafe. The hash function mainly targets on xDS use case, which is mostly small strings (endpoint address, headers, etc) and primitive types.

In gRPC's use case, string characters need to be treated as ASCIIs to make the produced hash values match other implementations (Envoy, gRPC-Go, C-core, etc) would produce.

The hashing implementation and tests are borrowed from OpenHFT's XxHash implementation (https://github.com/OpenHFT/Zero-Allocation-Hashing/blob/master/src/main/java/net/openhft/hashing/XxHash.java, see commit 658079a50903c32c54f2ab5c86243244b3ac60ed), which is under Apache 2.0 license. For more details, see https://github.com/OpenHFT/Zero-Allocation-Hashing.

The code is made to be in third_party directory with LISENCE and NOTICE files.
2021-02-22 11:07:25 -08:00
sanjaypujare 6a581f282b
xds: implement the new filterChainMatch algorithm (#7910) 2021-02-19 15:29:27 -08:00
Eric Anderson a55e034732 interop-testing: Specify ca-cert with transport-agnostic Credentials API 2021-02-19 09:30:24 -08:00
Eric Anderson 2e0e238fb2 okhttp: Consume mTLS and Trust/KeyManager Credentials API 2021-02-19 09:30:24 -08:00
Eric Anderson 0eab1c9176 netty: Consume mTLS and Trust/KeyManager Credentials API 2021-02-19 09:30:24 -08:00
Eric Anderson d937ec5baf api: Add mTLS and Trust/KeyManager Credentials API 2021-02-19 09:30:24 -08:00
ZHANG Dapeng 132a40a1cf
xds: implement fault injection interceptor in XdsNameResolver 2021-02-18 14:35:45 -08:00
Sergii Tkachenko e5e9c7a714 xds: sync envoy proto to commit ac9a2637336decdcc52c24add5e8fc39edebb962 2021-02-18 16:11:04 -05:00
ZHANG Dapeng 29864f4fad
xds: gate HttpFilter parsing by env flag 2021-02-17 18:55:43 -08:00
Kristofer Karlsson 3c4d3d2bb2 Move pendingDeadline.cancel out of synchronized block 2021-02-17 15:14:28 -08:00
ZHANG Dapeng e73f31a561
rls: fix rls oobChannel grpclb config service name
The serviceName field in oobChannel grpclb config should not be null, otherwise it will default to the lbHelper.getAuthority(), which perviously defaulted to the lookup service before #7852, but has been overridden to the backend service for authentication in #7852.
2021-02-17 10:10:50 -08:00
yifeizhuang 97b705614b
xds: add proto leakage check at gradle build (#7899) 2021-02-16 16:19:06 -08:00
Eric Anderson 1161ad9ed8 alts: Make concurrent handshake limit part of ALTS instead of TSI
The handshake limit is more a property of ALTS than TSI. This allows
other TSI implementations to accept a high connection rate (b/179376431)
2021-02-12 17:11:21 -08:00
Doug Fawley 3752b9e365
add timeout test case to xds interop tests (#7888) 2021-02-12 14:25:20 -08:00
yifeizhuang 0d2ea9365a
interop-testing: fix alts handshaking race (#7896) 2021-02-12 09:50:49 -08:00
sanjaypujare 8030c3a11d
xds: Implement XdsServingStatusListener as per the new xDS server gRFC (#7876) 2021-02-12 09:22:26 -08:00
Chengyuan Zhang 7b70161eef
xds: XdsClient support for hashing based load balancing (#7859)
This change adds two parts to XdsClient for receiving configurations that support hashing based load balancing policies:

- Each Route contains a list of HashPolicys, which specifies the hash value generation for requests routed to that Route.
- Each Cluster resource can specify lb policy other than "round_robin". If it is "ring_hash", it contains the configuration for mapping each RPC's hash value to one of the endpoints.
2021-02-11 23:54:28 -08:00
yifeizhuang 986a36b947
examples: add ALTS example README.md (#7861) 2021-02-11 16:37:39 -08:00
Chengyuan Zhang f4ef5acfd9
gradle, README: Bump protobuf-gradle-plugin version to 0.8.15 (#7891) 2021-02-11 15:41:18 -08:00
Eric Anderson 2140480736 Start 1.37.0 development cycle 2021-02-11 13:53:10 -08:00
ZHANG Dapeng 7d9ee8f051
rls: fix wrong server field in lookup request again
The previous fix #7878 didn't work because the server field is expected to be full hostname (without port number). Need strip the port part from the authority.
2021-02-10 16:33:59 -08:00
yifeizhuang 7f7821c616
interop-testing: add fake altsHandshakerService for test (#7847) 2021-02-09 16:56:26 -08:00
martin-schaub 514101d90c
alts: Introduce AltsContext to allow outside packages accessing ALTS information 2021-02-09 09:16:28 -08:00
Serhii Zabelnykov 9ba419adc0
api: add nullable annotation to trailersFromThrowable (#7856) 2021-02-08 23:39:38 -08:00
ZHANG Dapeng 23bb2ebf31
all: publish grpc-rls
Making `io.grpc:grpc-rls` a maven artifact from next release.
2021-02-08 21:39:54 -08:00
ZHANG Dapeng cb3317b1fd
rls: fix wrong lookup request server field
The server filed in lookup request as specified in go/dynamic-request-routing/#heading=h.eqjtcpo6u8ep should be the original target, not the RLS server where the lookup request is sent to.
2021-02-08 15:53:36 -08:00
ZHANG Dapeng 2cd45e7a24
rls: forcefully close rls channel when lb is shutdown
RLS RPC deadline is configured by service config, and could be extremely long. When RLS lb is shutdown, any pending RLS PRC should be cancelled. Now using shutdownNow() to forcefully close the RLS channel.
2021-02-08 15:52:53 -08:00
ZHANG Dapeng b1daad6f30
xds: remove GRPC_XDS_EXPERIMENTAL_V3_SUPPORT env flag 2021-02-08 13:42:43 -08:00
Chengyuan Zhang 14332d294c
xds: be tolerant for unspecified locality fields in bootstrap (#7872) 2021-02-05 17:30:07 -08:00
Chengyuan Zhang 01ed082281
xds: clean up value-typed classes (#7863)
This change cleans up most value-typed classes in EnvoyProtoData, which represent immutable xDS configurations used in gRPC. This introduces AutoValue for reducing the amount of boilerplate code for pure data classes.

Not all value-typed classes in xDS have been migrated, some would need more invasive refactoring and would be done next. This change is a pure no-op refactoring. No behavior change should be introduced.

For more details, see PR description.
2021-02-05 12:48:38 -08:00
Eric Anderson f0cf435b85 README.md: Document protobuf-gradle-plugin config for lite
This is part of the examples and other documentation, but a user
starting with the README would find things not working and it be very
unclear why.

Realized this was an issue because of
https://stackoverflow.com/q/66028045/4690866 .
2021-02-03 13:07:23 -08:00
Chengyuan Zhang 0dc37ab77d
xds: reimplement stats management (#7848)
This change reimplements stats recording for the client side:

1. Implemented the new stats objects: ClusterDropStats and ClusterLocalityStats, which match C-core's implementation. The XdsClient APIs for accessing stats objects are

- addClusterDropStats(String clusterName, String edsServiceName)
- addClusterLocalityStats(String clusterName, String edsServiceName, Locality locality)

2. Eliminated the LRS LB policy and incorporate locality load recording in ClusterImplLoadBalancer. The endpoint addresses resolved in ClusterResolverLoadBalancer will attach the locality in each address attributes. In ClusterImplLoadBalancer, its helper's createSubchannel() will populate the address locality and then call XdsClient.addClusterLocalityStats(...) to obtain the per-locality stats object for recording RPCs. This stats object is attached to the created subchannel's attribute. Therefore, ClusterImplLoadBalancer receives Picker update from its child LB policy, the Picker's subchannel will always have the per-locality stats object attached. Helper.pickSubchannel(...) will populate the per-locality stats object and wrap it into the stream tracer for counting RPCs. Note the subchannel's shutdown() is wrapped to call the stats object's Release().
2021-02-03 10:45:59 -08:00
Rui Liu 563288f0ad
netty: Log expected STREAM_CLOSED exceptions for already closed streams at FINE level
See this PR in netty: https://github.com/netty/netty/pull/9798 . It's
possible that one peer has closed the stream, yet another frame from
peers arrives after it. This is largely harmless, as explained in the PR
from netty repository. If we don't do this, the log will be polluted with
these harmless logs.

Example that would no longer be logged:

```
Jan 25, 2021 6:23:51 PM io.grpc.netty.NettyServerHandler onStreamError
WARNING: Stream Error
io.netty.handler.codec.http2.Http2Exception$StreamException: Received DATA frame for an unknown stream 27
        at io.netty.handler.codec.http2.Http2Exception.streamError(Http2Exception.java:147)
        at io.netty.handler.codec.http2.DefaultHttp2ConnectionDecoder$FrameReadListener.shouldIgnoreHeadersOrDataFrame(DefaultHttp2ConnectionDecoder.java:596)
        at io.netty.handler.codec.http2.DefaultHttp2ConnectionDecoder$FrameReadListener.onDataRead(DefaultHttp2ConnectionDecoder.java:239)
        ...
```
2021-02-02 12:21:55 -08:00
Sergii Tkachenko 461b10a907 services: add support for channelz.GetServer() 2021-02-01 19:33:16 -05:00
Martin Schaub 4c5559d54f Make clearer that AltsAuthContext is internal by renaming 2021-02-01 16:31:33 -08:00
Sergii Tkachenko 7f3ddca30f xds: sort FILES in import.sh scripts alphabetically 2021-02-01 18:43:41 -05:00
ZHANG Dapeng 92e7fd370b
core: user is responsible to override authority for resolvingOobChannelBuilder
ManagedChannelImpl should not override authority for createResolvingOobChannel(target, creds), because ManagedChannelImpl does not know what target and creds are.
2021-01-29 09:50:59 -08:00
yifeizhuang ef76337f5c
core: add more delayedStream tests (#7843)
Add more delayedStream tests related to #7750, where we changed to call realStream.start() synchronously with setting realStream.
2021-01-29 09:42:10 -08:00
ZHANG Dapeng 9bb9fef6b0
rls: use channel creds to create resolvingOobChannel 2021-01-29 09:29:39 -08:00
ZHANG Dapeng 9437783838
core: enhance ManagedChannelBuilder.overrideAuthority()
Enhance `ManagedChannelBuilder.overrideAuthority()` to make it impossible to use a different authority to a backend by wrapping ClientTransportFactory.newClientTransport() and setting ClientTransportOptions’ authority. To avoid confusing the LB policy, it would need to keep the original addresses to return during `Subchannel.getAddresses()`

The class `OverrideAuthorityNameResolverFactory` is deleted and its logic is moved into `ManagedChannelImpl`.
2021-01-29 09:29:06 -08:00
sanjaypujare 64676198c5
xds: implement all string matcher types for SAN list matching (#7801) 2021-01-29 08:32:17 +05:30
ZHANG Dapeng 45a151810c
all: implement Helper.createResolvingOobChannelBuilder(target, creds)
- Add APIs to `ClientTransportFactory`:
```java
public interface ClientTransportFactory {
  /**
   * Swaps to a new ChannelCredentials with all other settings unchanged. Returns null if the
   * ChannelCredentials is not supported by the current ClientTransportFactory settings.
   */
  SwapChannelCredentialsResult swapChannelCredentials(ChannelCredentials channelCreds);

  final class SwapChannelCredentialsResult {
    final ClientTransportFactory transportFactory;
    @Nullable final CallCredentials callCredentials;
  }
}
```

- Add `ChannelCredentials` to constructor args of `ManagedChannelImplBuilder`:
 ```java
public ManagedChannelImplBuilder(
      String target, @Nullable ChannelCredentials channelCreds, @Nullable CallCredentials callCreds, ...)
  ```
2021-01-28 09:49:53 -08:00
ZHANG Dapeng a6df2b2ff4
xds: parse HttpFault filter from LDS/RDS response 2021-01-27 20:45:18 -08:00
Chengyuan Zhang 09869528f8
xds: fix bug of missing cluster_service_name conversion in v2 ClusterStats (#7849) 2021-01-27 18:18:22 -08:00
Chengyuan Zhang 14a38ef9b5
interop-testing: implement test client support for xDS timeout test (#7837)
Changes the xDS interop test client to support timeout test.

- Synced xDS test proto messages with grpc-proto.
- Changed RpcConfig to be the configuration for per test method type. Added timeoutSec for its deadline configuration.
- Changed accumulated stats to include RPC status instead of just succeeded/failed.
2021-01-27 17:09:01 -08:00
yifeizhuang ac2ead70b4
core: delay CallCredentialsApplyingTransport shutdown until metadataApplier finalized (#7813)
Improve the CallCredentialsApplyingTransport shutdown lifecycle management. Right now CallCredentialsApplyingTransport shutdown the delegated real transport too early. It should be waiting for the metadataAppliers to finish because they may execute asynchronously. In addition, there is no shutdown check on CallCredentialsApplyingTransport for newStream(). The degraded lifecycle implementation may cause RejectionExecutionException, or accepting new RPCs after the underlying transport is already closed during channel shutdown.

We added listener on metadataApplier to notify completion, a magic counter to track the pending metadataApplier for delaying shutdown, also added shutdown check for newStream().
2021-01-26 12:01:16 -08:00
Eric Anderson dbd903c018
core: Rewrite builder class signatures to avoid internal class
This provides us a path forward with #7211 (hiding
AbstractManagedChannelImplBuilder and AbstractServerImplBuilder) while
providing users a migration path to manage the ABI breakage (#7552). We
do a .class hack so that recompiling avoids the internal class reference
yet the old methods are still available.

Leaving the classes as-is causes javac to compile two versions of each
method, one returning the public class (e.g. ServerBuilder) and one
returning the internal class (e.g., AbstractServerImplBuilder). However,
we rewrite the signature that is used at compile time so that new
compilations will not reference internal-returning methods.

This is intended to be temporary, just to give a migration path. Once we
have given users some time to recompile we will remove this rewriting
and change the generics to use public classes.
2021-01-25 17:29:12 -08:00
Doug Fawley ec270a7757
interop-testing: support rpc sleep behavior for xDS test server (#7836) 2021-01-25 10:14:37 -08:00
Eric Gribkoff 0ffd942fd2
buildscripts: increase xds job timeouts (#7831) 2021-01-25 04:33:01 -08:00
Srini Polavarapu 2a62de0559
Add link to CVE process (#7832) 2021-01-22 12:42:05 -08:00
Chengyuan Zhang 92364c89c7
xds: support reading bootstrap config directly from env var or system property values (#7826)
This change supports reading the bootstrap config from the following places (in order):

- If GRPC_XDS_BOOTSTRAP exists then use its value as the name of the bootstrap file. If the file is missing or the contents of the file are malformed, return an error.

- Else, if io.grpc.xds.bootstrap exists then use its value as the name of the bootstrap file. If the file is missing or the contents are malformed, return an error.

- Else, if GRPC_XDS_BOOTSTRAP_CONFIG exists then use its value as the bootstrap config. If the value is malformed, return an error.

- Else, if io.grpc.xds.bootstrapValue exists then use its value as the bootstrap config. If the value is malformed, return an error.
2021-01-22 00:26:45 -08:00
Nick Hill 2072df9be6
Random acts of garbage reduction
I noticed some opportunities to reduce allocations on hot paths
2021-01-21 10:45:31 -08:00
ZHANG Dapeng ae82c41032
xds: import fault proto 2021-01-21 09:56:57 -08:00
Eric Anderson 7b8105e100
core: DelayedStream should start() real stream immediately
DelayedClientTransport needs to avoid becoming terminated while it owns
RPCs. Previously DelayedClientTransport could terminate when some of its
RPCs had their realStream but realStream.start() hadn't yet been called.

To avoid that, we now make sure to call realStream.start()
synchronously with setting realStream. Since start() and the method
calls before start execute quickly, we can run it in-line. But it does
mean we now need to split the Stream methods into "before start" and
"after start" categories for queuing.

Fixes #6283
2021-01-20 15:01:49 -08:00
Sergii Tkachenko cd2c168f5b examples: Highlight the suggestion to checkout a tag 2021-01-20 15:40:51 -05:00
ZHANG Dapeng 150f994315
buildscript: fix execution path of xds.sh in xds_v3.sh 2021-01-20 09:21:36 -08:00
Chengyuan Zhang a857b5c911
xds: refactor Bootstrapper (#7810)
Split Bootstrapper into Bootstrapper interface and BootstrapperImpl for the concrete implementation. The implementation is cleaned up for better readability and testing. 

Note after this change, the environment variable/system property for setting the path to bootstrap file will be read statically at the time BootstrapImpl class is loaded, instead of when bootstrap() is called. Since in either case the bootstrap file is read for at most once (when the first Channel is created and its resolver starts), the change shouldn't have behavior change from the gRPC client's perspective.
2021-01-19 19:00:15 -08:00
ZHANG Dapeng c1f9658a72
buildscripts: fix buildscript unbound variable error 2021-01-19 18:33:55 -08:00
ZHANG Dapeng 56fc8b8626
buildscripts: add xds_v3 buildscripts 2021-01-19 15:01:21 -08:00
Chengyuan Zhang 29753f2009
xds: google_default should use TLS if address contains no cluster name (#7818)
Fixes bug introduced by 4130c5a1b8. TLS should be selected for addresses without cluster name attributes, even if grpc-xds is in classpath.
2021-01-19 10:16:06 -08:00
Jan Tattermusch b5a0d14da7 testing: Avoid trying Conscrypt on ARM with OpenJDK
This allows io.grpc.testing.integration.Http2OkHttpTest to pass on ARM.

Currently Concrypt doesn't offer an ARM version of the native
components for OpenJDK, so running Http2OkHttpTest ends up with a
failure when ran on an ARM machine:
java.lang.UnsatisfiedLinkError: no conscrypt_openjdk_jni-linux-aarch_64 in java.library.path
2021-01-19 09:27:01 -08:00
Jan Tattermusch 76c5a651a1
Add a simple way to run grpc-java test inside emulated ARM64 docker container 2021-01-19 09:05:22 -08:00
Chengyuan Zhang 1b23cf4f39
xds: fix lint warnings (#7817) 2021-01-15 17:03:39 -08:00
Chengyuan Zhang 4130c5a1b8
alts, xds: backend handshake protocol selection support for xDS in directpath (#7783)
Attaches an attribute on endpoint addresses resolved/discovered using xDS plugin. The attribute indicates whether the endpoint address is a direct Google service endpoint or a CFE. This lets the GoogleDefault credentials choose between ALTS (direct Google service endpoint) and TLS (CFE).

Due to dependency relation between grpc-xds and grpc-alts, GoogleDefault credentials will use the attribute key defined in grpc-xds reflectively.
2021-01-15 16:51:57 -08:00
Kun Zhang 23d279660c
grpclb: keep RR Subchannel state in TRANSIENT_FAILURE until becoming READY (#7816)
If all RR servers are unhealthy, it's possible that at least one
connection is CONNECTING at every moment which causes RR to stay in
CONNECTING. It's better to keep the TRANSIENT_FAILURE state in that
case so that fail-fast RPCs can fail fast.

The same changes have been made for RoundRobinLoadBalancer in #6657
2021-01-15 15:19:52 -08:00
Chengyuan Zhang 9016cf55d7
xds: make XdsAttributes really public internal (#7815)
Change XdsAttributes to InternalXdsAttributes. It is public internal and may be accessed out of grpc-xds.
2021-01-15 12:54:00 -08:00
Chengyuan Zhang 458b0e4447
xds: throw UnsupportedOperation for unimplemented XdsClient interface methods (#7814)
Letting unimplemented XdsClient methods throw avoids misuses.
2021-01-15 11:26:34 -08:00
Chengyuan Zhang 727b17bbcb
xds: delete old CDS and EDS LB policies (#7811)
Deleted old CDS and EDS LB policies as we've migrated to new LB hierachy support new fetures.
2021-01-15 00:06:26 -08:00
Chengyuan Zhang b01dfb9d3c
xds: promote CdsLoadBalancer2 (#7807)
This change migrates to the new LB hierarchy of CDS -> cluster_resolver -> priority -> cluster_impl -> ...
2021-01-14 15:45:18 -08:00
Chengyuan Zhang a584baf86a
xds: implement new CDS LB policy for supporting aggregate clusters (#7722)
The new CDS LB policy supports discovering aggregate clusters and logical DNS clusters. If the cluster given by its config is an aggregate cluster, it recursively resolves into a list of underlying clusters. It creates a cluster_resolver LB policy as its child policy that receives a list of DiscoveryMechanisms with each containing cluster-level configurations for a single non-aggregate cluster.
2021-01-14 13:17:55 -08:00
Chengyuan Zhang ffcc360ba9
core: further clean up leftovers in ManagedChannelImpl's LoadBalancer.Helper and Subchannel implementations (#7806) 2021-01-14 10:41:36 -08:00
Eric Gribkoff 3b03d317cd
Update README etc to reference 1.35.0 (#7804) 2021-01-13 19:34:33 -08:00
Chengyuan Zhang 389c5403e9
core: make subchannel creation timing restriction stricter (#7790)
Throw for subchannel creation if the channel is being shutting down and the delayed transport is terminated (aka, all retry calls has been finished). This enforces load balancer implementations to avoid creating subchannels after being shut down.
2021-01-13 17:01:02 -08:00
Yifei Zhuang ff59104b62
Revert "interop-testing: allow multiple port in test server (#7799)" (#7805)
This reverts commit dac8347063.

Changing from Grpc. newServerBuilder to NettyServerBuilder breaks interop-test with credentials.
2021-01-13 15:08:42 -08:00
Eric Anderson 03d04f1944 api: Reword retry javadoc to make clear service config is source of configuration
Multiple users have tried things like
`mcb.enableRetry().maxRetryAttempts(3)` and been confused when no
retries were performed. Providing a reference to the gRFC and
`defaultServiceConfig()` should greatly increase the clarity of how to
use the method.
2021-01-13 11:36:08 -08:00
Yifei Zhuang dac8347063
interop-testing: allow multiple port in test server (#7799) 2021-01-13 09:47:26 -08:00
Chengyuan Zhang b66d182bb9
api: delete LoadBalancer.Helper APIs that had been deprecated for a long time (#7793) 2021-01-11 15:25:35 -08:00
Chengyuan Zhang ca7f1e4cee
xds: slightly refactor and improve tests for cluster_manager LB policy (#7773) 2021-01-11 10:49:39 -08:00
Chengyuan Zhang 32173975e0
Revert "netty: add exporting SSL/TLS master key log feature (#7724)" (#7792)
This reverts commit 9bc05fba67.
2021-01-08 15:45:58 -08:00
huangqiangxiong 9bc05fba67
netty: add exporting SSL/TLS master key log feature (#7724)
Enable this feature by setting the system property
   -Dio.netty.ssl.masterKeyHandler=true
or
   System.setProperty(SslMasterKeyHandler.SYSTEM_PROP_KEY, "true");
The keys will be written to the log named "io.netty.wireshark" in
the warnning level. To export the keys to a file, you can configure
log factory like: (with log4j.xml for example)
<appender name="key-file" class="org.apache.log4j.RollingFileAppender">
	<param name="file" value="d:/keyfile.txt"/>
	<layout class="org.apache.log4j.PatternLayout">
		<param name="ConversionPattern" value="%m%n"/>
	</layout>
</appender>
<category name="io.netty.wireshark">
	<priority value="DEBUG" />
	<appender-ref ref="key-file" />
</category>

Wireshark can analyze the messages gRPC over TLS with this
key log file.

close #7199
2021-01-08 13:11:24 -08:00
sanjaypujare 2dba43c727
xds: reorder the shutdown of delegate and xds-client for better semantics of ServerWrapperForXds (#7791) 2021-01-08 12:02:09 -08:00
Chengyuan Zhang 18772e2470
xds: wire up re-resolution requests from LB policies for DNS clusters and bypass requests from LB policies for EDS clusters (#7769)
This change wires up the refreshNameResolution() API for triggering DNS re-resolution in ClusterResolverLoadBalancer, which provides a way for downstream LB policies to request a resolution refresh and only re-resolution requests from LB policies for the DNS cluster should trigger the DNS refresh.
2021-01-08 01:08:13 -08:00
Chengyuan Zhang 2755afeaa5
xds: clean up verbose getters and builders on XdsClient interface (#7784)
Eliminate getters and builders for xDS resource data. They are (should be effectively) immutable and mostly only used for internal implementations. Cleaning up getters and builders significantly reduces the verbosity.
2021-01-07 14:55:05 -08:00
Chengyuan Zhang ff52893c79
android-interop-testing: fix wrong instrumented test runner (#7789) 2021-01-07 11:20:24 -08:00
Chengyuan Zhang 70dd45ae70
xds: fix LB policy address and balancing state update propagations (#7772)
Delaying handleResolvedAddresses() for propagating configs to the child LB policy can be problematic. For example, if channel shutdown has been enqueued when calling child policy's handleResolvedAddresses() is being enqueued (e.g., receiving updates from XdsClient), it should not be executed. Otherwise, subchannels may be created by LBs that have already been shut down.

This change fixes LB config propagations in LB policies that manage a group of child LBs and delay the propagation for avoiding reentrancy. LB policies will always directly propagate child LB config/addresses updates directly. On the other hand, upcalls from child LB policies for balancing state updates will be queued and executed later.
2021-01-06 18:25:03 -08:00
sanjaypujare f788eec9e0
xds: multiple changes needed for PSM security GA as discussed (#7777)
* xds: multiple changes needed for GA:
- check to allow XdsServerBuilder.build() only once
- add transportBuilder() to XdsServerBuilder
- remove "grpc/server" hardcoding
- reorder the shutdown of delegate and xdsClient as per new design
2021-01-06 16:44:34 -08:00
Elliotte Rusty Harold 43d2e53a2a
alts: Remove dependency on Apache commons lang 2021-01-06 10:05:44 -08:00
Chengyuan Zhang edfc0d4d02
android-interop-testing: downgrade target SDK version to 26 and eliminate androidx dependencies (#7781)
androidx.appcompat is not ready to be used internally. This change downgrades android-interop-testing's target SDK version to 26 and use android.support's appcompat instead.
2021-01-05 17:41:08 -08:00
Yifei Zhuang 53da588dd1
Move multiple-port ServerImpl to NettyServer (#7674)
Change InternalServer to handle multiple addresses and implemented in NettyServer.
It makes ServerImpl to have a single transport server, and this single transport server (NettyServer) will bind to all listening addresses during bootstrap. (#7674)
2021-01-05 13:24:16 -08:00
ZHANG Dapeng ccef406f89
api: fix LoadBalancer javadoc 2021-01-05 13:12:06 -08:00
Chengyuan Zhang 4548cc5632
xds: fix regression for deleting EDS resources referenced by unchanged CDS resources (#7778)
A bug was introduced in the previous change for processing CDS responses. It mistakenly deleted EDS resources valid still referenced by CDS resources. EDS resource names either appear as the edsServiceName for CDS resources or has the same name as the CDS resources whose edsServiceName is null.

In the previous change, EDS resources having the same name as CDS resources are not retained. This caused LB subtrees for those EDS resources are shut down mistakenly, leading to RPC fails.
2021-01-05 12:08:40 -08:00
Eric Gribkoff f2f3bbeb5d
Start 1.36.0 development cycle (#7770) 2020-12-30 17:14:04 -08:00
Chengyuan Zhang 73fe68eeca
xds: support getting logical DNS and aggregate cluster configurations from CDS responses (#7696)
This change adds support for receiving and extracting configurations for logical DNS clusters and aggregate clusters.
2020-12-30 16:30:35 -08:00
Chengyuan Zhang 64d2bf1256
android, cronet, android-interop-testing: bump Android versions (#7740)
Bumps target SDK version of grpc-android, grpc-cronet, grpc-android-interop-testing to API 29. Major related changes are:

- Migrated android.support to androidx, which is required for Android Q.
- android.net.NetworkInfo is deprecated in SDK 29, suppressed compiler warnings as it is needed for supporting old Android versions.
- Robolectric requires Java 9+ for Android 29, which causes unit tests in grpc-cronet fail. Added annotation to emulate Android 28 for grpc-cronet's test.
- Upgraded Android dependencies accordingly in android-interop-testing.
2020-12-29 18:05:09 -08:00
Eric Anderson 8359d0b710
netty: Upgrade to Netty 4.1.52 and tcnative 2.0.34
The tiny cache size was removed from the bytebuf allocator and so was
deprecated. TLSv1.3 was enabled by the upgrade, which fails mTLS
connections at different times. Conscrypt is incompatible with the
default TrustManager when TLSv1.3 is enabled so we explicitly disable
TLSv1.3 when Conscrypt is used for the moment.
2020-12-29 15:20:46 -08:00
Chengyuan Zhang cddc1a500c
xds: decouple xds channel creation and bootstrapping (#7764)
This change fixes the problem of mismatched lifecycle of the xDS channel and XdsClient. Reading the bootstrap will determine and create the ChannelCredentials for each specified xDS server. An exception will be thrown if any xDS server specifies some channel_creds type that is not supported, not just for the first server (which is the only one to be used now). Reading the bootstrap also determines the xDS protocol version. The xDS channel will have the same lifecycle as the XdsClient instance: an xDS channel is created at the first call of getObject() and is shut down at the same time as the XdsClient is shutting down. A new xDS channel will be created when the ObjectPool creates a new XdsClient instance.
2020-12-28 18:39:14 -08:00
sanjaypujare 67ad78608c
xds: fix typo in a log message (#7762) 2020-12-27 18:10:45 -08:00
Eric Anderson 20197d36ce core: Include wait-for-ready in deadline exceeded insights
There was a report from a user in b/176088054 that experienced an RPC
waiting_for_connection that failed after 45 minutes due to deadline.
That would be quite normal for wait-for-ready, but because we didn't
include that detail in the status we have to do code inspection to
determine if wait-for-ready was enabled.
2020-12-23 13:37:21 -08:00
Eric Anderson b3899087d0 api: Improve code clarity by using Arrays.copyOf()
As noticed by a linter
2020-12-23 13:08:01 -08:00
sanjaypujare a4aa955d66
xds: don't add ServerTlsHandler if current handler is removed - also fix logging. (#7755) 2020-12-23 12:58:53 -08:00
ZHANG Dapeng 7d77f64773
compiler: remove some of the static imports in codegen (#7751)
Resolves #7741 
Some of the static methods in generated code have the same method name but different package name, such `ClientCalls.asyncClientStreamingCall` and `ServerCalls.asyncClientStreamingCall`. It's less readable using static import than using full-qualified method name in-place.
2020-12-23 11:28:03 -08:00
Sergii Tkachenko e5f57adb7f
buildscripts: xDS Kubernetes Interop tests buildscript 2020-12-23 09:52:01 -05:00
ZHANG Dapeng 90d61178a3
all: ChannelCredentials.withoutBearerTokens() and LoadBalancer.Helper API change (#7748)
API change (See go/grpc-rls-callcreds-to-server):

- Add `ChannelCredentials.withoutBearerTokens()`
- Add `createResolvingOobChannelBuilder(String, ChannelCredentials)`, `getChannelCredentials()` and `getUnsafeChannelCredentials()` for `LoadBalancer.Helper`

This PR does not include the implementation of `createResolvingOobChannelBuilder(String, ChannelCredentials)`.
2020-12-22 22:48:39 -08:00
sanjaypujare e530e10648
xds: import latest envoy and udpa protos to get new fields (#7747) 2020-12-22 12:22:40 -08:00
Chengyuan Zhang 5212e3c6df
xds: implement xds_cluster_resolver LB policy (#7685)
Implementation of the xDS cluster_resolver LB policy. It will replace the existing EdsLoadBalancer2.

The cluster_resolver LB policy supports discovering endpoints for aggregate clusters. Its config contains a list of DiscoveryMechanisms for each underlying cluster (the CDS LB policy will flatten an aggregate cluster to a list of underlying clusters), with each represents the mechanism (via EDS or DNS) to be used for resolving endpoints of each underlying cluster. Endpoints in underlying cluster will be resolved independently, but endpoint addresses and the priority/locality structure for each underlying cluster will be combined together before passing down to the child LB policy (aka, Priority LB policy).
2020-12-22 12:16:30 -08:00
Chengyuan Zhang 1e49ac665a
buildscript: ensure dependency convergence (#7745)
Run grpc-all:dependency task in Kokoro. For some unknown reason, building grpc-all doesn't reliably catch dependency conflicts.
2020-12-22 09:09:11 -08:00
Yifei Zhuang a67d816f4b
Revert " check pending stream completion at delayed transport lifecycle (#7720)" (#7744)
This reverts commit 90850128a6.
Alternative solution: alternative #7743
2020-12-21 15:15:00 -08:00
Chengyuan Zhang 0fb2667c96
all: Fix opencensus-api dependency conflict (#7739)
We depend on 0.28.0 while oauth2 depends on 0.24.0. This change replaces oauth2's opencensus-api dependency with our own.
2020-12-21 12:02:17 -08:00
Yifei Zhuang 90850128a6
check pending stream completion at delayed transport lifecycle (#7720)
add onTransferComplete() at delayedStream and wait for all pending streams to complete transfer when shutting down delayedClientTransport
2020-12-21 11:56:51 -08:00
Eric Anderson da939ca762 stub: Stop linking to Guava Javadoc
This resolves the following warning when building with JDK 8 introduced
in 9c5427fd4:
javadoc: warning - Error fetching URL: https://google.github.io/guava/releases/30.0-android/api/docs/

Guava is now building their Javadoc with JDK 11. JDK 11 swapped from
producing package-list to element-list, and stopped creating
package-list entirely. This file is what Javadoc uses to cross-link
documentation, and so it no longer works on the JDK 8 build, even though
the files have virtually the same contents.

ListenableFuture was the only reason we were including the Guava
Javadoc; let's just drop the link instead of worrying about this
silliness.
2020-12-17 17:42:42 -08:00
Eric Anderson ec70b64610
Bump Gradle and plugin versions
Android plugins weren't touched, since they will need a lot more testing
when doing so.
2020-12-17 15:02:27 -08:00
Eric Anderson 499694e9da android-interop-testing: ErrorProne should ignore generated R class
This silences many MutablePublicArray warnings that we can't do anything
about.
2020-12-17 09:13:27 -08:00
Eric Anderson 9c5427fd44
Bump versions for lots of dependencies
I didn't touch Protobuf and Netty; we upgrade those individually. Below
are issues I encountered that caused me to not upgrade (further).

Guava 30.1-android fails to build with Android without enabling
desugaring. https://github.com/google/guava/issues/5358

Robolectric 4.4 breaks AndroidChannelBuilderTest.
https://github.com/grpc/grpc-java/issues/7731

Opencensus 0.28.1+ is incompatible with gRPC.
https://github.com/census-instrumentation/opencensus-java/issues/2069
https://github.com/grpc/grpc-java/issues/7732

Truth now defines the asm dependency as "compile" although it is still
optional. But asm appears to have accidentally included incorrect gradle
module metadata in their release (I see they've disabled the metadata on
master) which make gradle think it requires Java 8. We could asm
everywhere, but that's is annoying. It seems likely this will resolve
itself.

Mockito can be upgraded to 3.4.0, but it deprecates initMocks, which
causes more code churn than I wanted in this commit. I still
synchronized the example versions on 3.4.0, though, as it was already
being used in some examples and the examples don't use initMocks.
2020-12-17 09:04:09 -08:00
Eric Anderson d10d4a6a65 Update README etc to reference 1.34.1 2020-12-15 12:45:28 -08:00
Chengyuan Zhang 9ead2c7c28
xds: move subchannel TLS context attaching code to cluster_impl LB policy (#7709)
This change moves the xDS security implementation that attaches an SSLContextProviderSupplier as EAG attributes from CDS LB policy to cluster_impl LB policy. It is similar to how DropOverload and circuit breakers work. This change assumes the UpstreamTlsContext in an CDS response is configured for underlying clusters in the context of supporting aggregate clusters. The UpstreamTlsContext configuration is obtained from CdsUpdate, then it is passed to the child EDS LB policy, where it is embedded into the cluster_impl LB policy config that the EDS LB policy generates.
2020-12-14 17:08:51 -08:00
ZHANG Dapeng 821ec65f2e
rls: cleanup and minor enhancement for rls logging
Cleanup `toString()` for cache entries, and print more debug information about cache entry when `pickSubchannel()`. This will be more helpful to debug.
2020-12-11 11:45:33 -08:00
Eric Anderson 60d3e7c536
core: On unexpected EOS, mention whether the frame was empty
Empty DATA frames with EOS tell a stronger tale as to where the server
may have its bug.
2020-12-10 14:54:33 -08:00
Eric Anderson 4be68f3287
core: Don't leak CallCredentials into OOB channels
The addition of CompositeChannelCredentials allowed CallCredentials to
be passed to the ManagedChannel itself. But the implementation was buggy
and used the call creds for out-of-band channels as well, which is
inappropriate since they have a different authority.

This also fixes a bug where resolving OOB channels would have CallCreds
duplicated; that wasn't noticed or important because we don't use
CallCreds in OOB channels.

Fixes #7643
2020-12-10 11:49:29 -08:00
sanjaypujare 20fc907b21
xds: fix ServerXdsClient to return subscribed resources only for LDS (#7689) 2020-12-09 17:42:12 -08:00
赵延 f5865d5bf2
examples: Modify the way of getHedgingServiceConfig in io.grpc.examples.hedging.HedgingHelloWorldClient (#7700) 2020-12-09 16:21:23 -08:00
Eric Anderson 26e88d9326 CONTRIBUTING.md: Fix out-of-date CLA documentation
The CLA system swapped a while back and this was left behind.
2020-12-09 14:32:57 -08:00
Sergii Tkachenko d9becc74d8
interop: add channelz to xds interop test server running in non-secure mode 2020-12-09 11:06:52 -05:00
Eric Anderson 8ce6355e89 buildscripts: Combine android builds together
Previously the android projects were separate from the main build and
each other. For quite a while now they have been integrated in the main
project. There's no longer any need to build each separately.
2020-12-07 15:01:51 -08:00
Chengyuan Zhang 71a3c55177
buildscripts: add missing CI coverage for examples (#7708)
Adds CI coverage for building example/android/strictmode and examples/example-jwt-auth. Also cleans up existing Gradle and Maven build command in the CIs.
2020-12-07 14:43:32 -08:00
Eric Anderson f13471d68d buildscripts: Check for out-of-date codegen after android builds
Issues like that fixed in 05048cf3 should have failed the CI, like it
does for the rest of the build (on both Travis and linux_artifacts).
2020-12-07 11:56:06 -08:00
Eric Anderson 3f1563434d xds: Add missing relocations and jacoco exclusions
We have been leaking classes since grpc-xds's inception. That's no good.

Lists are now sorted and use the same package names so they can be
easily compared. Excluding things like com/github/** is too aggressive,
and is unclear what is being targeted.
2020-12-07 11:42:24 -08:00
sanjaypujare 71606479ed
interop: add channelz and reflection support to xds interop test client and server (#7701)
* interop: add channelz support to xds interop test client and server

* add reflection

Co-authored-by: Sergii Tkachenko <sergiitk@google.com>
2020-12-07 10:48:36 -08:00
Eric Anderson ee9286a0f2 buildscripts: Fix grpc-java-artifacts indentation
Re-sort packages, now that the tabs aren't skewing the sorting.

I'm quite confident I had fixed this already, but I had multiple copies
of this file on multiple machines and must have fixed the wrong copy.
2020-12-04 16:42:26 -08:00
ZHANG Dapeng af29777686
all: migrate to interceptor-based config selector
This is migration following #7610
2020-12-04 11:11:57 -08:00
Chengyuan Zhang 0be913467d
xds: move drop support and circuit breaking into xds_cluster_impl LB policy (#7631)
Implementation for cluster_impl LB policy as per C2P design. This policy sits in the middle of priority LB policy and weighted_target LB policy, its major functionality is to handle drops and apply circuit breakers.

The idea is to move implementations of handling drops and circuit breakers from the EDS LB policy (will be split to cluster_resolver LB policy and cluster_impl LB policy) to cluster_impl LB policy.
2020-12-04 10:45:56 -08:00
Eric Anderson 486d82a7e1 Build Linux artifacts using CentOS 7
CentOS 6 is dead and no longer has update servers. CentOS 7 is older
than Debian 9 (oldstable), so binaries hopefully work on both. More
testing is necessary, but everything's broken now, so this is better
than nothing.

We stop using protoc-artifacts because now the container is
straight-forward enough that we can just use our own. Previously the
"devtoolset" stuff made us want to share the container.
2020-12-03 22:56:31 -08:00
ZHANG Dapeng 90e3dcf1ae
xds: provide more debug info for priority lb error-picker
When all priorities fail, update the overall picker with the picker from the last priority. This still does not provide the full detail why all priorities fail but is better than nothing being provided currently.
2020-12-03 14:07:24 -08:00
Eric Anderson 814e36b541 alts: Limit number of concurrent handshakes to 32 2020-12-03 13:51:50 -08:00
Chengyuan Zhang 7dc8ab1c6e
xds: print xDS request messages with JsonFormat (#7679)
Currently xDS response messages are printed with protobuf JsonFormat as they may contain Any-typed messages. JsonFormat internally uses Gson for generating human-readable message representations. The default Gson instance escapes HTML characters, which causes characters like '=' to be printed as '\u003d'. There is nothing can be done on our side to disable this as it is protobuf's internal implementation.

To make the same content consistent in both request and response messages consistent, we use JsonFormat to print both.
2020-12-01 15:57:18 -08:00
Chengyuan Zhang 9b276aa73a Update README etc to reference 1.34.0 2020-12-01 15:47:37 -08:00
Chengyuan Zhang 05048cf3e2
interop-testing: update proto generated service files (#7682) 2020-11-30 22:49:00 -08:00
sanjaypujare a6c3df2f24
xds: fix text in the readme and the comment about the --secure flag (#7676) 2020-11-30 14:58:52 -08:00
ZHANG Dapeng ac2327deb7
api,core: interceptor-based config selector (#7610)
Interceptor-based config selector will be needed for fault injection.

Add `interceptor` field to `InternalConfigSelector.Result`. Keep `callOptions` and `committedCallback` fields for the moment, because it needs a refactoring to migrate the existing xds config selector implementation to the new API.
2020-11-30 09:16:22 -08:00
sanjaypujare 3811ef3d22
xds: fix the new server API for ServerXdsClient (#7666) 2020-11-25 16:52:09 -08:00
Chengyuan Zhang 192614bf51
Revert "netty: create adaptive cumulator" (#7669)
This reverts commit 729175c783.
2020-11-25 14:37:48 -08:00
Eric Anderson f0223eb8e3 alts: Migrate java proto map getter from get<field> to get<field>Map
This is part of a proto-wide cleanup of its map APIs.

cl/344096880
2020-11-25 13:45:21 -08:00
Sergii Tkachenko fd59f1de0c buildscripts: Add xDS GKE interop tests buildscript placeholder 2020-11-25 16:24:07 -05:00
Eric Anderson 902cc019fa example-xds: Change arg from --secure to --xds-creds
The xds creds don't actually guarantee anything is secure. We don't want
to give new users a false impression.
2020-11-25 13:16:48 -08:00
Eric Anderson 0be12b40c3 example-xds: Prefix class names with Xds, instead of suffix
This aligns with normal naming practice.
2020-11-25 11:12:12 -08:00
Eric Anderson 7480dade0f example-xds: Mirror helloworld and hostname example
--secure was moved to front since many languages need flags to precede
positional parameters, and we'd like other languages to use the same
flags when feasible.

:8000 was removed from xds: target in the README, as it isn't all that
useful and is confusing as xDS itself provides the backend port numbers.
2020-11-25 11:12:12 -08:00
Sergii Tkachenko 9211bd1914 interop-testing: rename XdsTestClient secure_mode argument 2020-11-24 20:39:53 -05:00
sanjaypujare f0915e7619
xds: fix xds example to be consistent with hello world example (#7659) 2020-11-24 09:08:27 -08:00
Chengyuan Zhang f2e71a69b6
xds: clean up MessagePrinter (#7658)
In v3, UpstreamTlsContext and DownstreamTlsContext messages are not transitively type-referenced by Cluster and Listener. So the message printer is not able to print them without adding them into the registry manually.
2020-11-24 01:03:14 -08:00
ZHANG Dapeng ca12e7a339
grpclb: improve log for SRV lookup failure (#7647) 2020-11-23 11:09:28 -08:00
Aman Khalid fa1f900856 Remove deprecated javadoc options 2020-11-23 11:09:09 -08:00
Chengyuan Zhang e136d8bdeb
gradle, README: Bump protobuf-gradle-plugin version to 0.8.14 (#7640) 2020-11-23 11:01:34 -08:00
Chengyuan Zhang 1ca8bda17f
xds: fix mistake of taking wrong argument in log message (#7653) 2020-11-20 23:17:03 -08:00
sanjaypujare a7530efd6e
interop: create PSM security xDS interop tests - server & client (#7609)
Co-authored-by: Sergii Tkachenko <hi@sergii.org>
2020-11-20 18:31:40 -08:00
Chengyuan Zhang 40b54079ce
xds: obtain the global SharedCallCounterMap in the xDS resolver only (#7646)
Making the global map for holding atomics that aggregates cluster's outstanding requests an explicit dependency is easier for maintaining the architecture.
2020-11-20 12:02:19 -08:00
wanyingd1996 2bf5ef54da
api: Added documentation for Call onClose hanging problem 2020-11-19 12:45:16 -08:00
sanjaypujare 99df22a7a6
xds: remove temporary APIs and update xds example to use new ServerCreds (#7644) 2020-11-19 10:00:42 -08:00
Chengyuan Zhang 3a10392e4e
RELEASING.md: only project admin can create Cron jobs (#7642) 2020-11-18 16:24:55 -08:00
Chengyuan Zhang f5bbe12c9f
Start 1.35.0 development cycle (#7641) 2020-11-18 13:59:40 -08:00
1960 changed files with 209069 additions and 68456 deletions

1
.bazelrc Normal file
View File

@ -0,0 +1 @@
build --cxxopt=-std=c++14 --host_cxxopt=-std=c++14

8
.gitattributes vendored
View File

@ -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

2
.github/lock.yml vendored
View File

@ -1,2 +0,0 @@
daysUntilLock: 90
lockComment: false

41
.github/workflows/branch-testing.yml vendored Normal file
View File

@ -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

View File

@ -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

20
.github/workflows/lock.yml vendored Normal file
View File

@ -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

110
.github/workflows/testing.yml vendored Normal file
View File

@ -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]
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: 7.0.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 }}
- name: Run bazel test
run: bazelisk test //... --enable_bzlmod=${{ matrix.bzlmod }}
- name: Run example bazel build
run: bazelisk build //... --enable_bzlmod=${{ matrix.bzlmod }}
working-directory: ./examples

8
.gitignore vendored
View File

@ -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
@ -35,3 +37,9 @@ bin
# Emacs
*~
\#*\#
# ARM tests
qemu-arm-static
# Temporary output dir for artifacts
mvn-artifacts

View File

@ -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

View File

@ -12,6 +12,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
load("@rules_jvm_external//:defs.bzl", "artifact")
load(":java_grpc_library.bzl", "java_grpc_library")
java_proto_library(
@ -32,10 +33,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 +46,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"),
],
)

View File

@ -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
`<project-root>/gradle.properties` and add `skipAndroid=true`.
Otherwise, create the file `<project-root>/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 ``<project-root>\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`.
### 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.
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).
```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
After Android SDK is installed, you need to set the `ANDROID_HOME` environment variable to your
Android SDK home directory:
```
$ export ANDROID_HOME=<path-to-your-android-sdk>
# Add 'export ANDROID_HOME=$HOME/Android/Sdk' to your .bashrc or equivalent
```

View File

@ -10,7 +10,8 @@ If you are new to github, please start by reading [Pull Request howto](https://h
## Legal requirements
In order to protect both you and ourselves, you will need to sign the
[Contributor License Agreement](https://identity.linuxfoundation.org/projects/cncf).
[Contributor License Agreement](https://easycla.lfx.linuxfoundation.org/). When
you make a PR, a CLA bot will provide a link for the process.
## Compiling
@ -29,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**.

View File

@ -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)

185
MODULE.bazel Normal file
View File

@ -0,0 +1,185 @@
module(
name = "grpc-java",
compatibility_level = 0,
repo_name = "io_grpc_grpc_java",
version = "1.76.0-SNAPSHOT", # CURRENT_GRPC_VERSION
)
# 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.59.2",
"com.google.auth:google-auth-library-credentials:1.24.1",
"com.google.auth:google-auth-library-oauth2-http:1.24.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.11.0",
"com.google.errorprone:error_prone_annotations:2.30.0",
"com.google.guava:failureaccess:1.0.1",
"com.google.guava:guava:33.3.1-android",
"com.google.re2j:re2j:1.8",
"com.google.s2a.proto.v2:s2a-proto:0.1.2",
"com.google.truth:truth:1.4.2",
"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.124.Final",
"io.netty:netty-codec-http2:4.1.124.Final",
"io.netty:netty-codec-http:4.1.124.Final",
"io.netty:netty-codec-socks:4.1.124.Final",
"io.netty:netty-codec:4.1.124.Final",
"io.netty:netty-common:4.1.124.Final",
"io.netty:netty-handler-proxy:4.1.124.Final",
"io.netty:netty-handler:4.1.124.Final",
"io.netty:netty-resolver:4.1.124.Final",
"io.netty:netty-tcnative-boringssl-static:2.0.70.Final",
"io.netty:netty-tcnative-classes:2.0.70.Final",
"io.netty:netty-transport-native-epoll:jar:linux-x86_64:4.1.124.Final",
"io.netty:netty-transport-native-unix-common:4.1.124.Final",
"io.netty:netty-transport:4.1.124.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.checkerframework:checker-qual:3.12.0",
"org.codehaus.mojo:animal-sniffer-annotations:1.24",
]
# GRPC_DEPS_END
bazel_dep(name = "bazel_jar_jar", version = "0.1.7")
bazel_dep(name = "bazel_skylib", version = "1.7.1")
bazel_dep(name = "googleapis", repo_name = "com_google_googleapis", version = "0.0.0-20240326-1c8d509c5")
bazel_dep(name = "grpc-proto", repo_name = "io_grpc_grpc_proto", version = "0.0.0-20240627-ec30f58")
# Protobuf 25.5+ is incompatible with Bazel 7 with bzlmod
bazel_dep(name = "protobuf", repo_name = "com_google_protobuf", version = "24.4")
bazel_dep(name = "rules_cc", version = "0.0.9")
bazel_dep(name = "rules_java", version = "5.3.5")
bazel_dep(name = "rules_jvm_external", version = "6.0")
bazel_dep(name = "rules_proto", version = "5.3.0-21.7")
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",
)

137
README.md
View File

@ -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).
<table>
<tr>
<td><b>Homepage:</b></td>
@ -20,8 +13,29 @@ Provider on Android. Please see the [Security Readme](SECURITY.md).
</table>
[![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)
[![Coverage Status](https://coveralls.io/repos/grpc/grpc-java/badge.svg?branch=master&service=github)](https://coveralls.io/github/grpc/grpc-java?branch=master)
[![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 21 (Lollipop) 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
---------------
@ -30,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.33.1/examples) and the
[Android example](https://github.com/grpc/grpc-java/tree/v1.33.1/examples/android)
The [examples](https://github.com/grpc/grpc-java/tree/v1.75.0/examples) and the
[Android example](https://github.com/grpc/grpc-java/tree/v1.75.0/examples/android)
are standalone projects that showcase the usage of gRPC.
Download
@ -42,17 +56,18 @@ Download [the JARs][]. Or for Maven with non-Android, add to your `pom.xml`:
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-netty-shaded</artifactId>
<version>1.33.1</version>
<version>1.75.0</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-protobuf</artifactId>
<version>1.33.1</version>
<version>1.75.0</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-stub</artifactId>
<version>1.33.1</version>
<version>1.75.0</version>
</dependency>
<dependency> <!-- necessary for Java 9+ -->
<groupId>org.apache.tomcat</groupId>
@ -64,26 +79,30 @@ Download [the JARs][]. Or for Maven with non-Android, add to your `pom.xml`:
Or for Gradle with non-Android, add to your dependencies:
```gradle
implementation 'io.grpc:grpc-netty-shaded:1.33.1'
implementation 'io.grpc:grpc-protobuf:1.33.1'
implementation 'io.grpc:grpc-stub:1.33.1'
runtimeOnly 'io.grpc:grpc-netty-shaded:1.75.0'
implementation 'io.grpc:grpc-protobuf:1.75.0'
implementation 'io.grpc:grpc-stub:1.75.0'
compileOnly 'org.apache.tomcat:annotations-api:6.0.53' // necessary for Java 9+
```
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.33.1'
implementation 'io.grpc:grpc-protobuf-lite:1.33.1'
implementation 'io.grpc:grpc-stub:1.33.1'
implementation 'io.grpc:grpc-okhttp:1.75.0'
implementation 'io.grpc:grpc-protobuf-lite:1.75.0'
implementation 'io.grpc:grpc-stub:1.75.0'
compileOnly 'org.apache.tomcat:annotations-api:6.0.53' // necessary for Java 9+
```
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.33.1
https://search.maven.org/search?q=g:io.grpc%20AND%20v:1.75.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
--------------
@ -101,7 +120,7 @@ For protobuf-based codegen integrated with the Maven build system, you can use
<extension>
<groupId>kr.motd.maven</groupId>
<artifactId>os-maven-plugin</artifactId>
<version>1.6.2</version>
<version>1.7.1</version>
</extension>
</extensions>
<plugins>
@ -110,9 +129,9 @@ For protobuf-based codegen integrated with the Maven build system, you can use
<artifactId>protobuf-maven-plugin</artifactId>
<version>0.6.1</version>
<configuration>
<protocArtifact>com.google.protobuf:protoc:3.12.0:exe:${os.detected.classifier}</protocArtifact>
<protocArtifact>com.google.protobuf:protoc:3.25.5:exe:${os.detected.classifier}</protocArtifact>
<pluginId>grpc-java</pluginId>
<pluginArtifact>io.grpc:protoc-gen-grpc-java:1.33.1:exe:${os.detected.classifier}</pluginArtifact>
<pluginArtifact>io.grpc:protoc-gen-grpc-java:1.75.0:exe:${os.detected.classifier}</pluginArtifact>
</configuration>
<executions>
<execution>
@ -129,20 +148,20 @@ For protobuf-based codegen integrated with the Maven build system, you can use
[protobuf-maven-plugin]: https://www.xolstice.org/protobuf-maven-plugin/
For protobuf-based codegen integrated with the Gradle build system, you can use
[protobuf-gradle-plugin][]:
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.13'
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.5"
}
plugins {
grpc {
artifact = 'io.grpc:protoc-gen-grpc-java:1.33.1'
artifact = 'io.grpc:protoc-gen-grpc-java:1.75.0'
}
}
generateProtoTasks {
@ -159,7 +178,43 @@ 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.9.5'
}
protobuf {
protoc {
artifact = "com.google.protobuf:protoc:3.25.5"
}
plugins {
grpc {
artifact = 'io.grpc:protoc-gen-grpc-java:1.75.0'
}
}
generateProtoTasks {
all().each { task ->
task.builtins {
java { option 'lite' }
}
task.plugins {
grpc { option 'lite' }
}
}
}
}
```
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
-------------
@ -210,12 +265,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.

View File

@ -4,51 +4,32 @@ How to Create a Release of GRPC Java (for Maintainers Only)
Build Environments
------------------
We deploy GRPC to Maven Central under the following systems:
- Ubuntu 14.04 with Docker 13.03.0 that runs CentOS 6.9
- Ubuntu 14.04 with Docker 13.03.0 that runs CentOS 7
- Windows 7 64-bit with Visual Studio
- Mac OS X 10.14.6
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<major>.<minor>.x`, while the tags include the patch version
`v<major>.<minor>.<patch>`. 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. 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.
7. Close the release milestone.
Build Artifacts
---------------
8. Trigger build as described in "Auto releasing using kokoro" at
go/grpc-java/releasing.
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.
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.
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).
Releasing on Maven Central
--------------------------
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
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).
# 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
Build interop container image
-----------------------------
# Commit the changes
git commit --all -m "[interop] Add grpc-java $MAJOR.$MINOR.$PATCH to client_matrix.py"
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).
# 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
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.
11. Update gh-pages with the new Javadoc. Generally the file is on repo1
15 minutes after publishing:
```
$ git checkout -b bump-readme master
$ git cherry-pick v$MAJOR.$MINOR.$PATCH^
```
```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
```
Update version referenced by tutorials
--------------------------------------
Verify the current version is [live on grpc.io](https://grpc.io/grpc-java/javadoc/).
Update the `grpc_java_release_tag` in
[config.yaml](https://github.com/grpc/grpc.io/blob/master/config.yaml)
of the grpc.io repository.
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.*
Notify the Community
--------------------
Finally, document and publicize the release.
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.
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 <tag> 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.
14. Update README.md. Cherry-pick the commit that updated the README.md into the
master branch.
Update Hosted Javadoc
```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/`.

View File

@ -1,6 +1,16 @@
# Security Policy
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)
@ -15,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.
@ -46,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
@ -65,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
@ -151,7 +170,7 @@ the dependency.
<extension>
<groupId>kr.motd.maven</groupId>
<artifactId>os-maven-plugin</artifactId>
<version>1.6.2</version>
<version>1.7.1</version>
</extension>
</extensions>
<plugins>
@ -235,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
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE Configure PUBLIC "-//Mort Bay Consulting//DTD Configure//EN" "http://www.eclipse.org/jetty/configure.dtd">
<Configure class="org.eclipse.jetty.webapp.WebAppContext">
<!-- Must be done in jetty-env.xml, since jetty-web.xml is loaded too late. -->
<!-- Removing ALPN from the blacklisted server classes (using "-" to remove). -->
<!-- Must prepend to the blacklist since order matters. -->
<Call name="prependServerClass">
<Arg>-org.eclipse.jetty.alpn.</Arg>
</Call>
</Configure>
```
## Enabling TLS on a server
To use TLS on the server, a certificate chain and private key need to be
@ -273,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 <a href="https://github.com/grpc/grpc-java/blob/master/core/src/main/java/io/grpc/Grpc.java">Grpc</a>. 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<SSLSession> SSL_SESSION_CONTEXT = Context.key("SSLSession");
// The application uses this in its handlers.
public static final Context.Key<MySecurityInfo> SECURITY_INFO = Context.key("my.security.Info");
@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call,
@ -310,8 +299,12 @@ public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, Re
if (sslSession == null) {
return next.startCall(call, headers);
}
// This interceptor can provide a centralized policy to process the client's
// certificate. Avoid exposing low-level details (like SSLSession) and
// instead provide a higher-level concept like "authenticated user."
MySecurityInfo info = process(sslSession);
return Contexts.interceptCall(
Context.current().withValue(SSL_SESSION_CONTEXT, sslSession), call, headers, next);
Context.current().withValue(SECURITY_INFO, info), call, headers, next);
}
```
@ -350,10 +343,6 @@ If on Fedora 30 or later and you see "libcrypt.so.1: cannot open shared object
file: No such file or directory". Run `dnf -y install libxcrypt-compat` to
install the necessary dependency.
If you are running inside of an embedded Tomcat runtime (e.g., Spring Boot),
then some versions of `netty-tcnative-boringssl-static` will have conflicts and
won't work. You must use gRPC 1.4.0 or later.
Most dependency versioning problems can be solved by using
`io.grpc:grpc-netty-shaded` instead of `io.grpc:grpc-netty`, although this also
limits your usage of the Netty-specific APIs. `io.grpc:grpc-netty-shaded`
@ -379,7 +368,7 @@ If you are running in a runtime environment that also uses Netty (e.g., Hadoop,
Below are known to work version combinations:
grpc-netty version | netty-handler version | netty-tcnative-boringssl-static version
------------------ | --------------------- | ---------------------------------------
------------------ |-----------------------| ---------------------------------------
1.0.0-1.0.1 | 4.1.3.Final | 1.1.33.Fork19
1.0.2-1.0.3 | 4.1.6.Final | 1.1.33.Fork23
1.1.x-1.3.x | 4.1.8.Final | 1.1.33.Fork26
@ -399,24 +388,30 @@ grpc-netty version | netty-handler version | netty-tcnative-boringssl-static ver
1.25.x-1.27.x | 4.1.42.Final | 2.0.26.Final
1.28.x | 4.1.45.Final | 2.0.28.Final
1.29.x-1.31.x | 4.1.48.Final | 2.0.30.Final
1.32.x- | 4.1.51.Final | 2.0.31.Final
1.32.x-1.34.x | 4.1.51.Final | 2.0.31.Final
1.35.x-1.41.x | 4.1.52.Final | 2.0.34.Final
1.42.x-1.43.x | 4.1.63.Final | 2.0.38.Final
1.44.x-1.47.x | 4.1.72.Final | 2.0.46.Final
1.48.x-1.49.x | 4.1.77.Final | 2.0.53.Final
1.50.x-1.53.x | 4.1.79.Final | 2.0.54.Final
1.54.x-1.55.x | 4.1.87.Final | 2.0.56.Final
1.56.x | 4.1.87.Final | 2.0.61.Final
1.57.x-1.58.x | 4.1.93.Final | 2.0.61.Final
1.59.x | 4.1.97.Final | 2.0.61.Final
1.60.x-1.66.x | 4.1.100.Final | 2.0.61.Final
1.67.x-1.70.x | 4.1.110.Final | 2.0.65.Final
1.71.x-1.74.x | 4.1.110.Final | 2.0.70.Final
1.75.x- | 4.1.124.Final | 2.0.72.Final
_(grpc-netty-shaded avoids issues with keeping these versions in sync.)_
### OkHttp
If you are using gRPC on Android devices, you are most likely using `grpc-okhttp` transport.
If you are using gRPC on Android devices, you are most likely using
`grpc-okhttp` transport.
Find the dependency tree (e.g., `mvn dependency:tree`), and look for versions of:
- `io.grpc:grpc-okhttp`
- `com.squareup.okhttp:okhttp`
If you don't have `grpc-okhttp`, you should add it as a dependency.
If you have both `io.grpc:grpc-netty` and `io.grpc:grpc-okhttp`, you may also have issues. Remove `grpc-netty` if you are on Android.
If you have `okhttp` version below 2.5.0, then it may not work with gRPC.
It is OK to have both `okhttp` 2.x and 3.x since they have different group name and under different packages.
Find the dependency tree (e.g., `mvn dependency:tree`), and look for
`io.grpc:grpc-okhttp`. If you don't have `grpc-okhttp`, you should add it as a
dependency.
# gRPC over plaintext
@ -427,17 +422,12 @@ An option is provided to use gRPC over plaintext without TLS. While this is conv
The following code snippet shows how you can call the Google Cloud PubSub API using gRPC with a service account. The credentials are loaded from a key stored in a well-known location or by detecting that the application is running in an environment that can provide one automatically, e.g. Google Compute Engine. While this example is specific to Google and it's services, similar patterns can be followed for other service providers.
```java
// Create a channel to the test service.
ManagedChannel channel = ManagedChannelBuilder.forTarget("dns:///pubsub.googleapis.com")
// Use the default credentials from the environment
ChannelCredentials creds = GoogleDefaultChannelCredentials.create();
// Create a channel to the service
ManagedChannel channel = Grpc.newChannelBuilder("dns:///pubsub.googleapis.com", creds)
.build();
// Get the default credentials from the environment
GoogleCredentials creds = GoogleCredentials.getApplicationDefault();
// Down-scope the credential to just the scopes required by the service
creds = creds.createScoped(Arrays.asList("https://www.googleapis.com/auth/pubsub"));
// Create an instance of {@link io.grpc.CallCredentials}
CallCredentials callCreds = MoreCallCredentials.from(creds);
// Create a stub with credential
PublisherGrpc.PublisherBlockingStub publisherStub =
PublisherGrpc.newBlockingStub(channel).withCallCredentials(callCreds);
// Create a stub and send an RPC
PublisherGrpc.PublisherBlockingStub publisherStub = PublisherGrpc.newBlockingStub(channel);
publisherStub.publish(someMessage);
```

View File

@ -2,34 +2,46 @@ workspace(name = "io_grpc_grpc_java")
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
http_archive(
name = "rules_java",
url = "https://github.com/bazelbuild/rules_java/releases/download/5.3.5/rules_java-5.3.5.tar.gz",
sha256 = "c73336802d0b4882e40770666ad055212df4ea62cfa6edf9cb0f9d29828a0934",
)
http_archive(
name = "rules_jvm_external",
sha256 = "62133c125bf4109dfd9d2af64830208356ce4ef8b165a6ef15bbff7460b35c3a",
strip_prefix = "rules_jvm_external-3.0",
url = "https://github.com/bazelbuild/rules_jvm_external/archive/3.0.zip",
sha256 = "d31e369b854322ca5098ea12c69d7175ded971435e55c18dd9dd5f29cc5249ac",
strip_prefix = "rules_jvm_external-5.3",
url = "https://github.com/bazelbuild/rules_jvm_external/releases/download/5.3/rules_jvm_external-5.3.tar.gz",
)
load("@rules_jvm_external//:defs.bzl", "maven_install")
load("//:repositories.bzl", "IO_GRPC_GRPC_JAVA_ARTIFACTS")
load("//:repositories.bzl", "IO_GRPC_GRPC_JAVA_OVERRIDE_TARGETS")
maven_install(
artifacts = IO_GRPC_GRPC_JAVA_ARTIFACTS,
generate_compat_repositories = True,
override_targets = IO_GRPC_GRPC_JAVA_OVERRIDE_TARGETS,
repositories = [
"https://repo.maven.apache.org/maven2/",
],
)
load("@maven//:compat.bzl", "compat_repositories")
compat_repositories()
load("//:repositories.bzl", "grpc_java_repositories")
grpc_java_repositories()
load("@bazel_jar_jar//:jar_jar.bzl", "jar_jar_repositories")
jar_jar_repositories()
load("@com_google_protobuf//:protobuf_deps.bzl", "PROTOBUF_MAVEN_ARTIFACTS")
load("@com_google_protobuf//:protobuf_deps.bzl", "protobuf_deps")
protobuf_deps()
load("@com_google_googleapis//:repository_rules.bzl", "switched_rules_by_language")
switched_rules_by_language(
name = "com_google_googleapis_imports",
)
maven_install(
artifacts = IO_GRPC_GRPC_JAVA_ARTIFACTS + PROTOBUF_MAVEN_ARTIFACTS,
override_targets = IO_GRPC_GRPC_JAVA_OVERRIDE_TARGETS,
repositories = [
"https://repo.maven.apache.org/maven2/",
],
strict_visibility = True,
)

1
WORKSPACE.bzlmod Normal file
View File

@ -0,0 +1 @@
# When using bzlmod this makes sure nothing from the legacy WORKSPACE is loaded

View File

@ -10,32 +10,39 @@ description = "gRPC: All"
def subprojects = [
project(':grpc-api'),
project(':grpc-auth'),
project(':grpc-context'),
project(':grpc-core'),
project(':grpc-grpclb'),
project(':grpc-gcp-csm-observability'),
project(':grpc-inprocess'),
project(':grpc-netty'),
project(':grpc-okhttp'),
project(':grpc-opentelemetry'),
project(':grpc-protobuf'),
project(':grpc-protobuf-lite'),
project(':grpc-rls'),
project(':grpc-services'),
project(':grpc-servlet'),
project(':grpc-servlet-jakarta'),
project(':grpc-stub'),
project(':grpc-testing'),
project(':grpc-util'),
project(':grpc-xds'),
]
for (subproject in rootProject.subprojects) {
for (subproject in subprojects) {
if (subproject == project) {
continue
}
evaluationDependsOn(subproject.path)
}
evaluationDependsOn(':grpc-interop-testing')
dependencies {
api subprojects.minus([project(':grpc-protobuf-lite'), project(':grpc-rls')])
api subprojects.minus([project(':grpc-protobuf-lite')])
implementation libraries.guava.jre // JRE required by transitive protobuf-java-util
}
javadoc {
tasks.named("javadoc").configure {
classpath = files(subprojects.collect { subproject ->
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") }

View File

@ -1,3 +1,4 @@
load("@rules_jvm_external//:defs.bzl", "artifact")
load("@rules_proto//proto:defs.bzl", "proto_library")
load("//:java_grpc_library.bzl", "java_grpc_library")
@ -14,16 +15,16 @@ java_library(
"//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"),
],
)
@ -36,18 +37,17 @@ java_library(
deps = [
":alts_internal",
":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",
"@org_apache_commons_commons_lang3//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"),
],
)

View File

@ -2,77 +2,81 @@ 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-core'),
project(":grpc-context"), // Override google-auth dependency with our newer version
project(':grpc-grpclb'),
project(':grpc-protobuf'),
project(':grpc-stub'),
libraries.lang,
libraries.protobuf,
libraries.conscrypt
libraries.protobuf.java,
libraries.conscrypt,
libraries.guava.jre, // JRE required by protobuf-java-util from grpclb
libraries.google.auth.oauth2Http
def nettyDependency = implementation project(':grpc-netty')
implementation (libraries.google_auth_oauth2_http) {
// prefer our own versions instead of google-auth-oauth2-http's dependency
exclude group: 'com.google.guava', module: 'guava'
// we'll always be more up-to-date
exclude group: 'io.grpc', module: 'grpc-context'
}
guavaDependency 'implementation'
compileOnly libraries.javax_annotation
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 { exclude 'io/grpc/alts/internal/**' }
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})
}
@ -83,8 +87,7 @@ shadowJar {
publishing {
publications {
maven(MavenPublication) {
// use shadowJar and remove the original Jar
artifact shadowJar
// We want this to throw an exception if it isn't working
def originalJar = artifacts.find { dep -> dep.classifier == 'original'}
artifacts.remove(originalJar)
@ -94,8 +97,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)

View File

@ -1,30 +1,15 @@
package io.grpc.alts.internal;
import static io.grpc.MethodDescriptor.generateFullMethodName;
import static io.grpc.stub.ClientCalls.asyncBidiStreamingCall;
import static io.grpc.stub.ClientCalls.asyncClientStreamingCall;
import static io.grpc.stub.ClientCalls.asyncServerStreamingCall;
import static io.grpc.stub.ClientCalls.asyncUnaryCall;
import static io.grpc.stub.ClientCalls.blockingServerStreamingCall;
import static io.grpc.stub.ClientCalls.blockingUnaryCall;
import static io.grpc.stub.ClientCalls.futureUnaryCall;
import static io.grpc.stub.ServerCalls.asyncBidiStreamingCall;
import static io.grpc.stub.ServerCalls.asyncClientStreamingCall;
import static io.grpc.stub.ServerCalls.asyncServerStreamingCall;
import static io.grpc.stub.ServerCalls.asyncUnaryCall;
import static io.grpc.stub.ServerCalls.asyncUnimplementedStreamingCall;
import static io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall;
/**
*/
@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<io.grpc.alts.internal.HandshakerReq,
@ -72,6 +57,21 @@ public final class HandshakerServiceGrpc {
return HandshakerServiceStub.newStub(factory, channel);
}
/**
* Creates a new blocking-style stub that supports all types of calls on the service
*/
public static HandshakerServiceBlockingV2Stub newBlockingV2Stub(
io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<HandshakerServiceBlockingV2Stub> factory =
new io.grpc.stub.AbstractStub.StubFactory<HandshakerServiceBlockingV2Stub>() {
@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
*/
@ -104,7 +104,7 @@ public final class HandshakerServiceGrpc {
/**
*/
public static abstract class HandshakerServiceImplBase implements io.grpc.BindableService {
public interface AsyncService {
/**
* <pre>
@ -116,27 +116,28 @@ public final class HandshakerServiceGrpc {
* response before sending next request.
* </pre>
*/
public io.grpc.stub.StreamObserver<io.grpc.alts.internal.HandshakerReq> doHandshake(
default io.grpc.stub.StreamObserver<io.grpc.alts.internal.HandshakerReq> doHandshake(
io.grpc.stub.StreamObserver<io.grpc.alts.internal.HandshakerResp> responseObserver) {
return asyncUnimplementedStreamingCall(getDoHandshakeMethod(), responseObserver);
}
@java.lang.Override public final io.grpc.ServerServiceDefinition bindService() {
return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor())
.addMethod(
getDoHandshakeMethod(),
asyncBidiStreamingCall(
new MethodHandlers<
io.grpc.alts.internal.HandshakerReq,
io.grpc.alts.internal.HandshakerResp>(
this, METHODID_DO_HANDSHAKE)))
.build();
return io.grpc.stub.ServerCalls.asyncUnimplementedStreamingCall(getDoHandshakeMethod(), responseObserver);
}
}
/**
* Base class for the server implementation of the service HandshakerService.
*/
public static final class HandshakerServiceStub extends io.grpc.stub.AbstractAsyncStub<HandshakerServiceStub> {
public static abstract class HandshakerServiceImplBase
implements io.grpc.BindableService, AsyncService {
@java.lang.Override public final io.grpc.ServerServiceDefinition bindService() {
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<HandshakerServiceStub> {
private HandshakerServiceStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
@ -160,14 +161,50 @@ public final class HandshakerServiceGrpc {
*/
public io.grpc.stub.StreamObserver<io.grpc.alts.internal.HandshakerReq> doHandshake(
io.grpc.stub.StreamObserver<io.grpc.alts.internal.HandshakerResp> responseObserver) {
return asyncBidiStreamingCall(
return io.grpc.stub.ClientCalls.asyncBidiStreamingCall(
getChannel().newCall(getDoHandshakeMethod(), getCallOptions()), responseObserver);
}
}
/**
* A stub to allow clients to do synchronous rpc calls to service HandshakerService.
*/
public static final class HandshakerServiceBlockingStub extends io.grpc.stub.AbstractBlockingStub<HandshakerServiceBlockingStub> {
public static final class HandshakerServiceBlockingV2Stub
extends io.grpc.stub.AbstractBlockingStub<HandshakerServiceBlockingV2Stub> {
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);
}
/**
* <pre>
* 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.
* </pre>
*/
@io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/10918")
public io.grpc.stub.BlockingClientCall<io.grpc.alts.internal.HandshakerReq, io.grpc.alts.internal.HandshakerResp>
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<HandshakerServiceBlockingStub> {
private HandshakerServiceBlockingStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
@ -181,8 +218,10 @@ public final class HandshakerServiceGrpc {
}
/**
* A stub to allow clients to do ListenableFuture-style rpc calls to service HandshakerService.
*/
public static final class HandshakerServiceFutureStub extends io.grpc.stub.AbstractFutureStub<HandshakerServiceFutureStub> {
public static final class HandshakerServiceFutureStub
extends io.grpc.stub.AbstractFutureStub<HandshakerServiceFutureStub> {
private HandshakerServiceFutureStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
@ -202,10 +241,10 @@ public final class HandshakerServiceGrpc {
io.grpc.stub.ServerCalls.ServerStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.ClientStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.BidiStreamingMethod<Req, Resp> {
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;
}
@ -233,6 +272,18 @@ public final class HandshakerServiceGrpc {
}
}
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() {}
@ -256,9 +307,9 @@ public final class HandshakerServiceGrpc {
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;
}

View File

@ -18,7 +18,7 @@ package io.grpc.alts;
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 @@ import javax.annotation.Nullable;
/**
* 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<AltsChannelBuilder> {
public final class AltsChannelBuilder extends ForwardingChannelBuilder2<AltsChannelBuilder> {
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);
}

View File

@ -36,7 +36,7 @@ import java.util.logging.Level;
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 {
@ -93,7 +93,7 @@ public final class AltsChannelCredentials {
}
InternalProtocolNegotiator.ClientFactory buildProtocolNegotiatorFactory() {
if (!CheckGcpEnvironment.isOnGcp()) {
if (!InternalCheckGcpEnvironment.isOnGcp()) {
if (enableUntrustedAlts) {
logger.log(
Level.WARNING,

View File

@ -0,0 +1,91 @@
/*
* 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.alts;
import io.grpc.ExperimentalApi;
import io.grpc.alts.internal.AltsInternalContext;
import io.grpc.alts.internal.HandshakerResult;
import io.grpc.alts.internal.Identity;
/** {@code AltsContext} contains security-related information on the ALTS channel. */
@ExperimentalApi("https://github.com/grpc/grpc-java/issues/7864")
public final class AltsContext {
private final AltsInternalContext wrapped;
AltsContext(AltsInternalContext wrapped) {
this.wrapped = wrapped;
}
/**
* Creates an {@code AltsContext} for testing purposes.
* @param peerServiceAccount the peer service account of the to be created {@code AltsContext}
* @param localServiceAccount the local service account of the to be created {@code AltsContext}
* @return the created {@code AltsContext}
*/
public static AltsContext createTestInstance(String peerServiceAccount,
String localServiceAccount) {
return new AltsContext(new AltsInternalContext(HandshakerResult.newBuilder()
.setPeerIdentity(Identity.newBuilder().setServiceAccount(peerServiceAccount).build())
.setLocalIdentity(Identity.newBuilder().setServiceAccount(localServiceAccount).build())
.build()));
}
/**
* Get security level.
*
* @return the context's security level.
*/
public SecurityLevel getSecurityLevel() {
switch (wrapped.getSecurityLevel()) {
case SECURITY_NONE:
return SecurityLevel.SECURITY_NONE;
case INTEGRITY_ONLY:
return SecurityLevel.INTEGRITY_ONLY;
case INTEGRITY_AND_PRIVACY:
return SecurityLevel.INTEGRITY_AND_PRIVACY;
default:
return SecurityLevel.UNKNOWN;
}
}
/**
* Get peer service account.
*
* @return the context's peer service account.
*/
public String getPeerServiceAccount() {
return wrapped.getPeerServiceAccount();
}
/**
* Get local service account.
*
* @return the context's local service account.
*/
public String getLocalServiceAccount() {
return wrapped.getLocalServiceAccount();
}
/** SecurityLevel of the ALTS channel. */
public enum SecurityLevel {
UNKNOWN,
SECURITY_NONE,
INTEGRITY_ONLY,
INTEGRITY_AND_PRIVACY,
}
}

View File

@ -0,0 +1,99 @@
/*
* 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.alts;
import io.grpc.Attributes;
import io.grpc.ClientCall;
import io.grpc.ExperimentalApi;
import io.grpc.ServerCall;
import io.grpc.alts.internal.AltsInternalContext;
import io.grpc.alts.internal.AltsProtocolNegotiator;
/** Utility class for {@link AltsContext}. */
@ExperimentalApi("https://github.com/grpc/grpc-java/issues/7864")
public final class AltsContextUtil {
private AltsContextUtil() {}
/**
* 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) {
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");
}
return new AltsContext((AltsInternalContext) authContext);
}
/**
* Checks if the {@link ServerCall} contains ALTS information.
*
* @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) {
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;
}
}

View File

@ -20,6 +20,7 @@ import io.grpc.BindableService;
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 @@ import java.util.concurrent.TimeUnit;
* a production server on Google Cloud Platform.
*/
@ExperimentalApi("https://github.com/grpc/grpc-java/issues/4151")
public final class AltsServerBuilder extends ServerBuilder<AltsServerBuilder> {
public final class AltsServerBuilder extends ForwardingServerBuilder<AltsServerBuilder> {
private final NettyServerBuilder delegate;
private final AltsServerCredentials.Builder credentialsBuilder =
new AltsServerCredentials.Builder();
@ -68,6 +69,11 @@ public final class AltsServerBuilder extends ServerBuilder<AltsServerBuilder> {
return this;
}
@Override
protected ServerBuilder<?> delegate() {
return delegate;
}
/** {@inheritDoc} */
@Override
public AltsServerBuilder handshakeTimeout(long timeout, TimeUnit unit) {

View File

@ -32,7 +32,7 @@ import java.util.logging.Logger;
* 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 final class AltsServerCredentials {
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<Channel> handshakerChannelPool =
SharedResourcePool.forResource(HandshakerServiceChannel.SHARED_HANDSHAKER_CHANNEL);
@ -76,7 +76,7 @@ public final class AltsServerCredentials {
}
InternalProtocolNegotiator.ProtocolNegotiator buildProtocolNegotiator() {
if (!CheckGcpEnvironment.isOnGcp()) {
if (!InternalCheckGcpEnvironment.isOnGcp()) {
if (enableUntrustedAlts) {
logger.log(
Level.WARNING,

View File

@ -18,7 +18,7 @@ package io.grpc.alts;
import io.grpc.ServerCall;
import io.grpc.Status;
import io.grpc.alts.internal.AltsAuthContext;
import io.grpc.alts.internal.AltsInternalContext;
import io.grpc.alts.internal.AltsProtocolNegotiator;
import java.util.Collection;
@ -34,8 +34,8 @@ public final class AuthorizationUtil {
*/
public static Status clientAuthorizationCheck(
ServerCall<?, ?> call, Collection<String> expectedServiceAccounts) {
AltsAuthContext altsContext =
(AltsAuthContext) call.getAttributes().get(AltsProtocolNegotiator.AUTH_CONTEXT_KEY);
AltsInternalContext altsContext =
(AltsInternalContext) call.getAttributes().get(AltsProtocolNegotiator.AUTH_CONTEXT_KEY);
if (altsContext == null) {
return Status.PERMISSION_DENIED.withDescription("Peer ALTS AuthContext not found");
}

View File

@ -35,7 +35,7 @@ public final class ComputeEngineChannelBuilder
}
/** "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 final class ComputeEngineChannelBuilder
}
@Override
@SuppressWarnings("deprecation") // Not extending ForwardingChannelBuilder2 to preserve ABI.
protected NettyChannelBuilder delegate() {
return delegate;
}

View File

@ -21,7 +21,6 @@ import com.google.common.collect.ImmutableList;
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 @@ import javax.net.ssl.SSLException;
* 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() {}
@ -49,7 +47,7 @@ public final class ComputeEngineChannelCredentials {
ChannelCredentials nettyCredentials =
InternalNettyChannelCredentials.create(createClientFactory());
CallCredentials callCredentials;
if (CheckGcpEnvironment.isOnGcp()) {
if (InternalCheckGcpEnvironment.isOnGcp()) {
callCredentials = MoreCallCredentials.from(ComputeEngineCredentials.create());
} else {
callCredentials = new FailingCallCredentials(

View File

@ -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);
}
}
}

View File

@ -38,7 +38,4 @@ final class FailingCallCredentials extends CallCredentials {
CallCredentials.MetadataApplier applier) {
applier.fail(status);
}
@Override
public void thisUsesUnstableApi() {}
}

View File

@ -35,7 +35,7 @@ public final class GoogleDefaultChannelBuilder
}
/** "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 final class GoogleDefaultChannelBuilder
}
@Override
@SuppressWarnings("deprecation") // Not extending ForwardingChannelBuilder2 to preserve ABI.
protected NettyChannelBuilder delegate() {
return delegate;
}

View File

@ -21,7 +21,6 @@ import com.google.common.collect.ImmutableList;
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 @@ 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 GoogleDefaultChannelCredentials() {}
@ -46,31 +44,75 @@ public final class 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();
}
private static InternalProtocolNegotiator.ClientFactory createClientFactory() {
SslContext sslContext;
try {
sslContext = GrpcSslContexts.forClient().build();
} catch (SSLException e) {
throw new RuntimeException(e);
/**
* Returns a new instance of {@link Builder}.
*
* @since 1.43.0
*/
public static Builder newBuilder() {
return new Builder();
}
/**
* 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;
}
/** 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.<String>of(),
SharedResourcePool.forResource(HandshakerServiceChannel.SHARED_HANDSHAKER_CHANNEL),
sslContext);
}
return new GoogleDefaultProtocolNegotiatorFactory(
/* targetServiceAccounts= */ ImmutableList.<String>of(),
SharedResourcePool.forResource(HandshakerServiceChannel.SHARED_HANDSHAKER_CHANNEL),
sslContext);
}
}

View File

@ -21,12 +21,14 @@ import io.grpc.Channel;
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;
/**
@ -44,6 +46,9 @@ final class HandshakerServiceChannel {
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<Channel> {
private final String target;
@ -56,12 +61,16 @@ final class HandshakerServiceChannel {
/* 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);
}

View File

@ -19,27 +19,34 @@ package io.grpc.alts;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.common.annotations.VisibleForTesting;
import io.grpc.Internal;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.lang3.SystemUtils;
/** Class for checking if the system is running on Google Cloud Platform (GCP). */
final class CheckGcpEnvironment {
/**
* 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(CheckGcpEnvironment.class.getName());
private static final String DMI_PRODUCT_NAME = "/sys/class/dmi/id/product_name";
private static final Logger logger =
Logger.getLogger(InternalCheckGcpEnvironment.class.getName());
private static final String WINDOWS_COMMAND = "powershell.exe";
private static Boolean cachedResult = null;
// Construct me not!
private CheckGcpEnvironment() {}
private InternalCheckGcpEnvironment() {}
static synchronized boolean isOnGcp() {
/** Returns {@code true} if currently running on Google Cloud Platform (GCP). */
public static synchronized boolean isOnGcp() {
if (cachedResult == null) {
cachedResult = isRunningOnGcp();
}
@ -65,11 +72,13 @@ final class CheckGcpEnvironment {
}
private static boolean isRunningOnGcp() {
String osName = System.getProperty("os.name").toLowerCase(Locale.ENGLISH);
try {
if (SystemUtils.IS_OS_LINUX) {
if (osName.startsWith("linux")) {
// Checks GCE residency on Linux platform.
return checkProductNameOnLinux(Files.newBufferedReader(Paths.get(DMI_PRODUCT_NAME), UTF_8));
} else if (SystemUtils.IS_OS_WINDOWS) {
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 =
new ProcessBuilder()

View File

@ -20,19 +20,17 @@ import com.google.common.annotations.VisibleForTesting;
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 @@ class AltsHandshakerClient {
}
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 @@ class AltsHandshakerClient {
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 @@ class AltsHandshakerClient {
.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);
}

View File

@ -33,7 +33,7 @@ class AltsHandshakerStub {
private final HandshakerServiceStub serviceStub;
private final ArrayBlockingQueue<Optional<HandshakerResp>> responseQueue =
new ArrayBlockingQueue<>(1);
private final AtomicReference<String> exceptionMessage = new AtomicReference<>();
private final AtomicReference<ThrowableInfo> exceptionMessage = new AtomicReference<>();
private static final long HANDSHAKE_RPC_DEADLINE_SECS = 20;
@ -64,12 +64,18 @@ class AltsHandshakerStub {
if (!responseQueue.isEmpty()) {
throw new IOException("Received an unexpected response.");
}
writer.onNext(req);
Optional<HandshakerResp> 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 @@ class AltsHandshakerStub {
/** 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 @@ class AltsHandshakerStub {
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 @@ class AltsHandshakerStub {
@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<HandshakerResp> result = Optional.absent();
AltsHandshakerStub.this.responseQueue.offer(result);
@ -120,10 +126,22 @@ class AltsHandshakerStub {
/** 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<HandshakerResp> 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;
}
}
}

View File

@ -19,12 +19,12 @@ package io.grpc.alts.internal;
import com.google.common.annotations.VisibleForTesting;
import java.util.Map;
/** AltsAuthContext contains security-related context information about an ALTs connection. */
public final class AltsAuthContext {
/** AltsInternalContext contains security-related context information about an ALTs connection. */
public final class AltsInternalContext {
final AltsContext context;
/** Create a new AltsAuthContext. */
public AltsAuthContext(HandshakerResult result) {
/** Create a new AltsInternalContext. */
public AltsInternalContext(HandshakerResult result) {
context =
AltsContext.newBuilder()
.setApplicationProtocol(result.getApplicationProtocol())
@ -39,8 +39,8 @@ public final class AltsAuthContext {
}
@VisibleForTesting
public static AltsAuthContext getDefaultInstance() {
return new AltsAuthContext(HandshakerResult.newBuilder().build());
public static AltsInternalContext getDefaultInstance() {
return new AltsInternalContext(HandshakerResult.newBuilder().build());
}
/**
@ -103,6 +103,6 @@ public final class AltsAuthContext {
* @return the context's peer attributes.
*/
public Map<String, String> getPeerAttributes() {
return context.getPeerAttributes();
return context.getPeerAttributesMap();
}
}

View File

@ -23,6 +23,7 @@ import com.google.common.collect.ImmutableList;
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;
@ -38,8 +39,11 @@ import io.grpc.netty.InternalProtocolNegotiators;
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;
@ -51,14 +55,27 @@ import javax.annotation.Nullable;
public final class AltsProtocolNegotiator {
private static final Logger logger = Logger.getLogger(AltsProtocolNegotiator.class.getName());
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<TsiPeer> TSI_PEER_KEY = Attributes.Key.create("TSI_PEER");
public static final Attributes.Key<TsiPeer> TSI_PEER_KEY =
Attributes.Key.create("internal:TSI_PEER");
@Grpc.TransportAttr
public static final Attributes.Key<Object> 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.
@ -107,12 +124,16 @@ public final class AltsProtocolNegotiator {
@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());
ChannelHandler wuah = InternalProtocolNegotiators.waitUntilActiveHandler(thh);
ChannelHandler thh = new TsiHandshakeHandler(
gnh, nettyHandshaker, new AltsHandshakeValidator(), handshakeSemaphore,
negotiationLogger);
ChannelHandler wuah = InternalProtocolNegotiators.waitUntilActiveHandler(thh,
negotiationLogger);
return wuah;
}
@ -131,11 +152,13 @@ public final class AltsProtocolNegotiator {
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);
}
}
@ -162,12 +185,16 @@ public final class AltsProtocolNegotiator {
@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());
ChannelHandler wuah = InternalProtocolNegotiators.waitUntilActiveHandler(thh);
ChannelHandler thh = new TsiHandshakeHandler(
gnh, nettyHandshaker, new AltsHandshakeValidator(), handshakeSemaphore,
negotiationLogger);
ChannelHandler wuah = InternalProtocolNegotiators.waitUntilActiveHandler(thh,
negotiationLogger);
return wuah;
}
@ -183,6 +210,9 @@ public final class AltsProtocolNegotiator {
*/
public static final class GoogleDefaultProtocolNegotiatorFactory
implements InternalProtocolNegotiator.ClientFactory {
@VisibleForTesting
@Nullable
static Attributes.Key<String> clusterNameAttrKey = loadClusterNameAttrKey();
private final ImmutableList<String> targetServiceAccounts;
private final ObjectPool<Channel> handshakerChannelPool;
private final SslContext sslContext;
@ -205,28 +235,53 @@ public final class AltsProtocolNegotiator {
return new GoogleDefaultProtocolNegotiator(
targetServiceAccounts,
handshakerChannelPool,
sslContext);
sslContext,
clusterNameAttrKey);
}
@Override
public int getDefaultPort() {
return 443;
}
@SuppressWarnings("unchecked")
@Nullable
private static Attributes.Key<String> loadClusterNameAttrKey() {
Attributes.Key<String> key = null;
try {
Class<?> klass = Class.forName("io.grpc.xds.InternalXdsAttributes");
key = (Attributes.Key<String>) 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 {
private final TsiHandshakerFactory handshakerFactory;
private final LazyChannel lazyHandshakerChannel;
private final SslContext sslContext;
@Nullable
private final Attributes.Key<String> clusterNameAttrKey;
GoogleDefaultProtocolNegotiator(
ImmutableList<String> targetServiceAccounts,
ObjectPool<Channel> handshakerChannelPool,
SslContext sslContext) {
SslContext sslContext,
@Nullable Attributes.Key<String> clusterNameAttrKey) {
this.lazyHandshakerChannel = new LazyChannel(handshakerChannelPool);
this.handshakerFactory =
new ClientTsiHandshakerFactory(targetServiceAccounts, lazyHandshakerChannel);
this.sslContext = checkNotNull(sslContext, "checkNotNull");
this.clusterNameAttrKey = clusterNameAttrKey;
}
@Override
@ -237,22 +292,51 @@ public final class AltsProtocolNegotiator {
@Override
public ChannelHandler newHandler(GrpcHttp2ConnectionHandler grpcHandler) {
ChannelHandler gnh = InternalProtocolNegotiators.grpcNegotiationHandler(grpcHandler);
ChannelLogger negotiationLogger = grpcHandler.getNegotiationLogger();
ChannelHandler securityHandler;
boolean isXdsDirectPath = false;
if (clusterNameAttrKey != null) {
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) {
TsiHandshaker handshaker = handshakerFactory.newHandshaker(grpcHandler.getAuthority());
|| grpcHandler.getEagAttributes().get(GrpclbConstants.ATTR_LB_PROVIDED_BACKEND) != null
|| isXdsDirectPath) {
TsiHandshaker handshaker =
handshakerFactory.newHandshaker(grpcHandler.getAuthority(), negotiationLogger);
NettyTsiHandshaker nettyHandshaker = new NettyTsiHandshaker(handshaker);
securityHandler =
new TsiHandshakeHandler(gnh, nettyHandshaker, new AltsHandshakeValidator());
securityHandler = new TsiHandshakeHandler(
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");
@ -272,7 +356,8 @@ public final class AltsProtocolNegotiator {
}
@Override
public TsiHandshaker newHandshaker(@Nullable String authority) {
public TsiHandshaker newHandshaker(
@Nullable String authority, ChannelLogger negotiationLogger) {
AltsClientOptions handshakerOptions =
new AltsClientOptions.Builder()
.setRpcProtocolVersions(RpcProtocolVersionsUtil.getRpcProtocolVersions())
@ -280,7 +365,9 @@ public final class AltsProtocolNegotiator {
.setTargetName(authority)
.build();
return AltsTsiHandshaker.newClient(
HandshakerServiceGrpc.newStub(lazyHandshakerChannel.get()), handshakerOptions);
HandshakerServiceGrpc.newStub(lazyHandshakerChannel.get()),
handshakerOptions,
negotiationLogger);
}
}
@ -318,26 +405,51 @@ public final class AltsProtocolNegotiator {
@Override
public SecurityDetails validatePeerObject(Object peerObject) throws GeneralSecurityException {
AltsAuthContext altsAuthContext = (AltsAuthContext) peerObject;
AltsInternalContext altsContext = (AltsInternalContext) peerObject;
// Checks peer Rpc Protocol Versions in the ALTS auth context. Fails the connection if
// Rpc Protocol Versions mismatch.
RpcVersionsCheckResult checkResult =
RpcProtocolVersionsUtil.checkRpcProtocolVersions(
RpcProtocolVersionsUtil.getRpcProtocolVersions(),
altsAuthContext.getPeerRpcVersions());
altsContext.getPeerRpcVersions());
if (!checkResult.getResult()) {
String errorMessage =
"Local Rpc Protocol Versions "
+ RpcProtocolVersionsUtil.getRpcProtocolVersions()
+ " are not compatible with peer Rpc Protocol Versions "
+ altsAuthContext.getPeerRpcVersions();
+ altsContext.getPeerRpcVersions();
throw Status.UNAVAILABLE.withDescription(errorMessage).asRuntimeException();
}
return new SecurityDetails(
SecurityLevel.PRIVACY_AND_INTEGRITY,
new Security(new OtherSecurity("alts", Any.pack(altsAuthContext.context))));
new Security(new OtherSecurity("alts", Any.pack(altsContext.context))));
}
}
@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() {}
}

View File

@ -20,6 +20,8 @@ import static com.google.common.base.Preconditions.checkState;
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.nio.ByteBuffer;
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;
}
/**
@ -80,6 +85,7 @@ public final class AltsTsiHandshaker implements TsiHandshaker {
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.
@ -120,17 +126,19 @@ public final class AltsTsiHandshaker implements TsiHandshaker {
@Override
public Object extractPeerObject() throws GeneralSecurityException {
Preconditions.checkState(!isInProgress(), "Handshake is not complete.");
return new AltsAuthContext(handshaker.getResult());
return new AltsInternalContext(handshaker.getResult());
}
/** 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 final class AltsTsiHandshaker implements TsiHandshaker {
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 final class AltsTsiHandshaker implements TsiHandshaker {
}
/**
* 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 final class AltsTsiHandshaker implements TsiHandshaker {
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);
}

View File

@ -0,0 +1,61 @@
/*
* 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.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;
/** Provides a semaphore primitive, without blocking waiting on permits. */
final class AsyncSemaphore {
private final Object lock = new Object();
@SuppressWarnings("JdkObsolete") // LinkedList avoids high watermark memory issues
private final Queue<ChannelPromise> queue = new LinkedList<>();
@GuardedBy("lock")
private int permits;
public AsyncSemaphore(int permits) {
this.permits = permits;
}
public ChannelFuture acquire(ChannelHandlerContext ctx) {
synchronized (lock) {
if (permits > 0) {
permits--;
return ctx.newSucceededFuture();
}
ChannelPromise promise = ctx.newPromise();
queue.add(promise);
return promise;
}
}
public void release() {
ChannelPromise next;
synchronized (lock) {
next = queue.poll();
if (next == null) {
permits++;
return;
}
}
next.setSuccess();
}
}

View File

@ -21,8 +21,8 @@ import java.security.GeneralSecurityException;
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.
*
* <p>Note that we provide implementations of this interface that provide integrity only and

View File

@ -99,7 +99,7 @@ public final class NettyTsiHandshaker {
}
/**
* 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.
*/

View File

@ -78,7 +78,7 @@ public final class ProtectedPromise extends DefaultChannelPromise {
if (!doneAllocating) {
doneAllocating = true;
if (successfulCount == expectedCount) {
trySuccessInternal(null);
trySuccessInternal();
return super.setSuccess(null);
}
}
@ -117,18 +117,18 @@ public final class ProtectedPromise extends DefaultChannelPromise {
}
@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 final class ProtectedPromise extends DefaultChannelPromise {
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);
}
}

View File

@ -22,15 +22,16 @@ import static io.grpc.alts.internal.AltsProtocolNegotiator.AUTH_CONTEXT_KEY;
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;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
@ -82,17 +83,33 @@ public final class TsiHandshakeHandler extends ByteToMessageDecoder {
private final NettyTsiHandshaker handshaker;
private final HandshakeValidator handshakeValidator;
private final ChannelHandler next;
private final AsyncSemaphore semaphore;
private ProtocolNegotiationEvent pne;
private boolean semaphoreAcquired;
private final ChannelLogger negotiationLogger;
/**
* Constructs a TsiHandshakeHandler.
*/
public TsiHandshakeHandler(
ChannelHandler next, NettyTsiHandshaker handshaker, HandshakeValidator handshakeValidator) {
ChannelHandler next, NettyTsiHandshaker handshaker, HandshakeValidator handshakeValidator,
ChannelLogger negotiationLogger) {
this(next, handshaker, handshakeValidator, null, negotiationLogger);
}
/**
* Constructs a TsHandshakeHandler. If a semaphore is provided, a permit from the semaphore is
* required to start the handshake and is returned when the handshake ends.
*/
public TsiHandshakeHandler(
ChannelHandler next, NettyTsiHandshaker handshaker, HandshakeValidator handshakeValidator,
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
@ -137,13 +154,36 @@ public final class TsiHandshakeHandler extends ByteToMessageDecoder {
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
public void userEventTriggered(final ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof ProtocolNegotiationEvent) {
checkState(pne == null, "negotiation already started");
pne = (ProtocolNegotiationEvent) evt;
InternalProtocolNegotiators.negotiationLogger(ctx)
.log(ChannelLogLevel.INFO, "TsiHandshake started");
sendHandshake(ctx);
negotiationLogger.log(ChannelLogLevel.INFO, "TsiHandshake started");
ChannelFuture acquire = semaphoreAcquire(ctx);
if (acquire.isSuccess()) {
semaphoreAcquired = true;
sendHandshake(ctx);
} else {
acquire.addListener(new ChannelFutureListener() {
@Override public void operationComplete(ChannelFuture future) {
if (!future.isSuccess()) {
ctx.fireExceptionCaught(future.cause());
return;
}
if (ctx.isRemoved()) {
semaphoreRelease();
return;
}
semaphoreAcquired = true;
try {
sendHandshake(ctx);
} catch (Exception ex) {
ctx.fireExceptionCaught(ex);
}
ctx.flush();
}
});
}
} else {
super.userEventTriggered(ctx, evt);
}
@ -152,8 +192,7 @@ public final class TsiHandshakeHandler extends ByteToMessageDecoder {
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)
@ -188,6 +227,24 @@ public final class TsiHandshakeHandler extends ByteToMessageDecoder {
@Override
protected void handlerRemoved0(ChannelHandlerContext ctx) throws Exception {
if (semaphoreAcquired) {
semaphoreRelease();
semaphoreAcquired = false;
}
handshaker.close();
}
}
private ChannelFuture semaphoreAcquire(ChannelHandlerContext ctx) {
if (semaphore == null) {
return ctx.newSucceededFuture();
} else {
return semaphore.acquire(ctx);
}
}
private void semaphoreRelease() {
if (semaphore != null) {
semaphore.release();
}
}
}

View File

@ -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

View File

@ -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);
}

View File

@ -0,0 +1,134 @@
/*
* 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.alts;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
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;
import io.grpc.alts.internal.AltsProtocolNegotiator;
import io.grpc.alts.internal.HandshakerResult;
import io.grpc.alts.internal.Identity;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link AltsContextUtil}. */
@RunWith(JUnit4.class)
public class AltsContextUtilTest {
@Test
public void check_noAttributeValue() {
assertFalse(AltsContextUtil.check(Attributes.newBuilder().build()));
}
@Test
public void check_unexpectedAttributeValueType() {
assertFalse(AltsContextUtil.check(Attributes.newBuilder()
.set(AltsProtocolNegotiator.AUTH_CONTEXT_KEY, new Object())
.build()));
}
@Test
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, AltsInternalContext.getDefaultInstance())
.build());
assertTrue(AltsContextUtil.check(call));
}
@Test
public void checkClient_altsInternalContext() {
ClientCall<?,?> call = mock(ClientCall.class);
when(call.getAttributes()).thenReturn(Attributes.newBuilder()
.set(AltsProtocolNegotiator.AUTH_CONTEXT_KEY, AltsInternalContext.getDefaultInstance())
.build());
assertTrue(AltsContextUtil.check(call));
}
@Test
public void createFrom_altsInternalContext() {
HandshakerResult handshakerResult =
HandshakerResult.newBuilder()
.setPeerIdentity(Identity.newBuilder().setServiceAccount("remote@peer"))
.setLocalIdentity(Identity.newBuilder().setServiceAccount("local@peer"))
.build();
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 createFrom_noAttributeValue() {
AltsContextUtil.createFrom(Attributes.newBuilder().build());
}
@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());
}
}

View File

@ -24,7 +24,7 @@ import io.grpc.Metadata;
import io.grpc.MethodDescriptor;
import io.grpc.ServerCall;
import io.grpc.Status;
import io.grpc.alts.internal.AltsAuthContext;
import io.grpc.alts.internal.AltsInternalContext;
import io.grpc.alts.internal.AltsProtocolNegotiator;
import io.grpc.alts.internal.HandshakerResult;
import io.grpc.alts.internal.Identity;
@ -65,8 +65,8 @@ public final class AuthorizationUtilTest {
HandshakerResult.newBuilder()
.setPeerIdentity(Identity.newBuilder().setServiceAccount(peerServiceAccount))
.build();
AltsAuthContext altsAuthContext = new AltsAuthContext(handshakerResult);
attrsBuilder.set(AltsProtocolNegotiator.AUTH_CONTEXT_KEY, altsAuthContext);
AltsInternalContext altsContext = new AltsInternalContext(handshakerResult);
attrsBuilder.set(AltsProtocolNegotiator.AUTH_CONTEXT_KEY, altsContext);
}
attrs = attrsBuilder.build();
}

View File

@ -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;
}
}
}

View File

@ -46,7 +46,7 @@ public final class HandshakerServiceChannelTest {
so.onCompleted();
}
})
.build());
.build());
private Resource<Channel> resource;
@Before

View File

@ -26,37 +26,37 @@ import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public final class CheckGcpEnvironmentTest {
public final class InternalCheckGcpEnvironmentTest {
@Test
public void checkGcpLinuxPlatformData() throws Exception {
BufferedReader reader;
reader = new BufferedReader(new StringReader("HP Z440 Workstation"));
assertFalse(CheckGcpEnvironment.checkProductNameOnLinux(reader));
assertFalse(InternalCheckGcpEnvironment.checkProductNameOnLinux(reader));
reader = new BufferedReader(new StringReader("Google"));
assertTrue(CheckGcpEnvironment.checkProductNameOnLinux(reader));
assertTrue(InternalCheckGcpEnvironment.checkProductNameOnLinux(reader));
reader = new BufferedReader(new StringReader("Google Compute Engine"));
assertTrue(CheckGcpEnvironment.checkProductNameOnLinux(reader));
assertTrue(InternalCheckGcpEnvironment.checkProductNameOnLinux(reader));
reader = new BufferedReader(new StringReader("Google Compute Engine "));
assertTrue(CheckGcpEnvironment.checkProductNameOnLinux(reader));
assertTrue(InternalCheckGcpEnvironment.checkProductNameOnLinux(reader));
}
@Test
public void checkGcpWindowsPlatformData() throws Exception {
BufferedReader reader;
reader = new BufferedReader(new StringReader("Product : Google"));
assertFalse(CheckGcpEnvironment.checkBiosDataOnWindows(reader));
assertFalse(InternalCheckGcpEnvironment.checkBiosDataOnWindows(reader));
reader = new BufferedReader(new StringReader("Manufacturer : LENOVO"));
assertFalse(CheckGcpEnvironment.checkBiosDataOnWindows(reader));
assertFalse(InternalCheckGcpEnvironment.checkBiosDataOnWindows(reader));
reader = new BufferedReader(new StringReader("Manufacturer : Google Compute Engine"));
assertFalse(CheckGcpEnvironment.checkBiosDataOnWindows(reader));
assertFalse(InternalCheckGcpEnvironment.checkBiosDataOnWindows(reader));
reader = new BufferedReader(new StringReader("Manufacturer : Google"));
assertTrue(CheckGcpEnvironment.checkBiosDataOnWindows(reader));
assertTrue(InternalCheckGcpEnvironment.checkBiosDataOnWindows(reader));
reader = new BufferedReader(new StringReader("Manufacturer:Google"));
assertTrue(CheckGcpEnvironment.checkBiosDataOnWindows(reader));
assertTrue(InternalCheckGcpEnvironment.checkBiosDataOnWindows(reader));
reader = new BufferedReader(new StringReader("Manufacturer : Google "));
assertTrue(CheckGcpEnvironment.checkBiosDataOnWindows(reader));
assertTrue(InternalCheckGcpEnvironment.checkBiosDataOnWindows(reader));
reader = new BufferedReader(new StringReader("BIOSVersion : 1.0\nManufacturer : Google\n"));
assertTrue(CheckGcpEnvironment.checkBiosDataOnWindows(reader));
assertTrue(InternalCheckGcpEnvironment.checkBiosDataOnWindows(reader));
}
}

View File

@ -117,7 +117,7 @@ public final class AesGcmHkdfAeadCrypterTest {
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 final class AesGcmHkdfAeadCrypterTest {
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);

View File

@ -29,6 +29,7 @@ import static org.mockito.Mockito.when;
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 class AltsHandshakerClientTest {
.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 class AltsHandshakerClientTest {
.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();

View File

@ -32,7 +32,7 @@ import org.junit.runners.JUnit4;
@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 @@ public class AltsHandshakerStubTest {
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 class AltsHandshakerStubTest {
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();

View File

@ -25,9 +25,9 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link AltsAuthContext}. */
/** Unit tests for {@link AltsInternalContext}. */
@RunWith(JUnit4.class)
public final class AltsAuthContextTest {
public final class AltsInternalContextTest {
private static final int TEST_MAX_RPC_VERSION_MAJOR = 3;
private static final int TEST_MAX_RPC_VERSION_MINOR = 5;
private static final int TEST_MIN_RPC_VERSION_MAJOR = 2;
@ -75,16 +75,16 @@ public final class AltsAuthContextTest {
}
@Test
public void testAltsAuthContext() {
AltsAuthContext authContext = new AltsAuthContext(handshakerResult);
assertEquals(TEST_APPLICATION_PROTOCOL, authContext.getApplicationProtocol());
assertEquals(TEST_RECORD_PROTOCOL, authContext.getRecordProtocol());
assertEquals(TEST_SECURITY_LEVEL, authContext.getSecurityLevel());
assertEquals(TEST_PEER_SERVICE_ACCOUNT, authContext.getPeerServiceAccount());
assertEquals(TEST_LOCAL_SERVICE_ACCOUNT, authContext.getLocalServiceAccount());
assertEquals(rpcVersions, authContext.getPeerRpcVersions());
assertEquals(testPeerAttributes, authContext.getPeerAttributes());
assertEquals(TEST_PEER_ATTRIBUTES_VALUE, authContext.getPeerAttributes()
public void testAltsInternalContext() {
AltsInternalContext context = new AltsInternalContext(handshakerResult);
assertEquals(TEST_APPLICATION_PROTOCOL, context.getApplicationProtocol());
assertEquals(TEST_RECORD_PROTOCOL, context.getRecordProtocol());
assertEquals(TEST_SECURITY_LEVEL, context.getSecurityLevel());
assertEquals(TEST_PEER_SERVICE_ACCOUNT, context.getPeerServiceAccount());
assertEquals(TEST_LOCAL_SERVICE_ACCOUNT, context.getLocalServiceAccount());
assertEquals(rpcVersions, context.getPeerRpcVersions());
assertEquals(testPeerAttributes, context.getPeerAttributes());
assertEquals(TEST_PEER_ATTRIBUTES_VALUE, context.getPeerAttributes()
.get(TEST_PEER_ATTRIBUTES_KEY));
}
}

View File

@ -26,6 +26,7 @@ import static org.junit.Assert.assertTrue;
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.alts.internal.TsiPeer.Property;
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;
@ -96,8 +98,8 @@ public class AltsProtocolNegotiatorTest {
private Throwable caughtException;
private TsiPeer mockedTsiPeer = new TsiPeer(Collections.<Property<?>>emptyList());
private AltsAuthContext mockedAltsContext =
new AltsAuthContext(
private AltsInternalContext mockedAltsContext =
new AltsInternalContext(
HandshakerResult.newBuilder()
.setPeerRpcVersions(RpcProtocolVersionsUtil.getRpcProtocolVersions())
.build());
@ -130,8 +132,8 @@ public class AltsProtocolNegotiatorTest {
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;
@ -352,6 +354,29 @@ public class AltsProtocolNegotiatorTest {
.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 +429,7 @@ public class AltsProtocolNegotiatorTest {
Http2ConnectionDecoder decoder,
Http2ConnectionEncoder encoder,
Http2Settings initialSettings) {
super(null, decoder, encoder, initialSettings);
super(null, decoder, encoder, initialSettings, new NoopChannelLogger());
}
@Override
@ -426,8 +451,8 @@ public class AltsProtocolNegotiatorTest {
}
@Override
public TsiHandshaker newHandshaker(String authority) {
return delegate.newHandshaker(authority);
public TsiHandshaker newHandshaker(String authority, ChannelLogger logger) {
return delegate.newHandshaker(authority, logger);
}
}

View File

@ -26,6 +26,7 @@ import static org.mockito.Mockito.verify;
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) {
@ -232,7 +234,7 @@ public class AltsTsiHandshakerTest {
TEST_SERVER_SERVICE_ACCOUNT,
clientPeer.getProperty(AltsTsiHandshaker.TSI_SERVICE_ACCOUNT_PEER_PROPERTY).getValue());
AltsAuthContext clientContext = (AltsAuthContext) handshakerClient.extractPeerObject();
AltsInternalContext clientContext = (AltsInternalContext) handshakerClient.extractPeerObject();
assertEquals(TEST_APPLICATION_PROTOCOL, clientContext.getApplicationProtocol());
assertEquals(TEST_RECORD_PROTOCOL, clientContext.getRecordProtocol());
assertEquals(TEST_SERVER_SERVICE_ACCOUNT, clientContext.getPeerServiceAccount());
@ -258,7 +260,7 @@ public class AltsTsiHandshakerTest {
TEST_CLIENT_SERVICE_ACCOUNT,
serverPeer.getProperty(AltsTsiHandshaker.TSI_SERVICE_ACCOUNT_PEER_PROPERTY).getValue());
AltsAuthContext serverContext = (AltsAuthContext) handshakerServer.extractPeerObject();
AltsInternalContext serverContext = (AltsInternalContext) handshakerServer.extractPeerObject();
assertEquals(TEST_APPLICATION_PROTOCOL, serverContext.getApplicationProtocol());
assertEquals(TEST_RECORD_PROTOCOL, serverContext.getRecordProtocol());
assertEquals(TEST_CLIENT_SERVICE_ACCOUNT, serverContext.getPeerServiceAccount());

View File

@ -21,6 +21,7 @@ import static org.junit.Assert.assertEquals;
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 class AltsTsiTest {
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 class AltsTsiTest {
}
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);
}

View File

@ -19,7 +19,9 @@ package io.grpc.alts.internal;
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 class FakeTsiHandshaker implements TsiHandshaker {
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 @@ public class FakeTsiHandshaker implements TsiHandshaker {
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 class FakeTsiHandshaker implements TsiHandshaker {
}
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 class FakeTsiHandshaker implements TsiHandshaker {
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.
@ -210,7 +215,7 @@ public class FakeTsiHandshaker implements TsiHandshaker {
@Override
public Object extractPeerObject() {
return AltsAuthContext.getDefaultInstance();
return AltsInternalContext.getDefaultInstance();
}
@Override

View File

@ -17,12 +17,17 @@
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;
@ -37,84 +42,190 @@ import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.ssl.SslContext;
import java.util.concurrent.atomic.AtomicReference;
import javax.annotation.Nullable;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
@RunWith(Enclosed.class)
public final class GoogleDefaultProtocolNegotiatorTest {
private ProtocolNegotiator googleProtocolNegotiator;
private final ObjectPool<Channel> handshakerChannelPool = new ObjectPool<Channel>() {
@RunWith(JUnit4.class)
public abstract static class HandlerSelectionTest {
private ProtocolNegotiator googleProtocolNegotiator;
private Attributes.Key<String> originalClusterNameAttrKey;
private final ObjectPool<Channel> handshakerChannelPool = new ObjectPool<Channel>() {
@Override
public Channel getObject() {
return InProcessChannelBuilder.forName("test").build();
}
@Override
public Channel returnObject(Object object) {
((ManagedChannel) object).shutdownNow();
return null;
}
};
@Before
public void setUp() throws Exception {
SslContext sslContext = GrpcSslContexts.forClient().build();
googleProtocolNegotiator = new AltsProtocolNegotiator.GoogleDefaultProtocolNegotiatorFactory(
ImmutableList.<String>of(),
handshakerChannelPool,
sslContext)
.newNegotiator();
}
@After
public void tearDown() {
googleProtocolNegotiator.close();
}
@Test
public void altsHandler() {
Attributes eagAttributes =
Attributes.newBuilder().set(GrpclbConstants.ATTR_LB_PROVIDED_BACKEND, true).build();
GrpcHttp2ConnectionHandler mockHandler = mock(GrpcHttp2ConnectionHandler.class);
when(mockHandler.getEagAttributes()).thenReturn(eagAttributes);
final AtomicReference<Throwable> failure = new AtomicReference<>();
ChannelHandler exceptionCaught = new ChannelInboundHandlerAdapter() {
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
failure.set(cause);
super.exceptionCaught(ctx, cause);
public Channel getObject() {
return InProcessChannelBuilder.forName("test").build();
}
@Override
public Channel returnObject(Object object) {
((ManagedChannel) object).shutdownNow();
return null;
}
};
ChannelHandler h = googleProtocolNegotiator.newHandler(mockHandler);
EmbeddedChannel chan = new EmbeddedChannel(exceptionCaught);
// Add the negotiator handler last, but to the front. Putting this in ctor above would make it
// throw early.
chan.pipeline().addFirst(h);
chan.pipeline().fireUserEventTriggered(InternalProtocolNegotiationEvent.getDefault());
// Check that the message complained about the ALTS code, rather than SSL. ALTS throws on
// being added, so it's hard to catch it at the right time to make this assertion.
assertThat(failure.get()).hasMessageThat().contains("TsiHandshakeHandler");
@Before
public void setUp() throws Exception {
SslContext sslContext = GrpcSslContexts.forClient().build();
originalClusterNameAttrKey =
AltsProtocolNegotiator.GoogleDefaultProtocolNegotiatorFactory.clusterNameAttrKey;
AltsProtocolNegotiator.GoogleDefaultProtocolNegotiatorFactory.clusterNameAttrKey =
getClusterNameAttrKey();
googleProtocolNegotiator = new AltsProtocolNegotiator.GoogleDefaultProtocolNegotiatorFactory(
ImmutableList.<String>of(),
handshakerChannelPool,
sslContext)
.newNegotiator();
}
@After
public void tearDown() {
googleProtocolNegotiator.close();
AltsProtocolNegotiator.GoogleDefaultProtocolNegotiatorFactory.clusterNameAttrKey =
originalClusterNameAttrKey;
}
@Nullable
abstract Attributes.Key<String> 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);
}
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<Throwable> failure = new AtomicReference<>();
ChannelHandler exceptionCaught = new ChannelInboundHandlerAdapter() {
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
failure.set(cause);
super.exceptionCaught(ctx, cause);
}
};
ChannelHandler h = googleProtocolNegotiator.newHandler(mockHandler);
EmbeddedChannel chan = new EmbeddedChannel(exceptionCaught);
// Add the negotiator handler last, but to the front. Putting this in ctor above would make
// it throw early.
chan.pipeline().addFirst(h);
chan.pipeline().fireUserEventTriggered(InternalProtocolNegotiationEvent.getDefault());
// Check that the message complained about the ALTS code, rather than SSL. ALTS throws on
// being added, so it's hard to catch it at the right time to make this assertion.
assertThat(failure.get()).hasMessageThat().contains("TsiHandshakeHandler");
}
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);
chan.pipeline().fireUserEventTriggered(InternalProtocolNegotiationEvent.getDefault());
assertThat(chan.pipeline().first().getClass().getSimpleName()).isEqualTo("SslHandler");
}
}
@Test
public void tlsHandler() {
Attributes eagAttributes = Attributes.EMPTY;
GrpcHttp2ConnectionHandler mockHandler = mock(GrpcHttp2ConnectionHandler.class);
when(mockHandler.getEagAttributes()).thenReturn(eagAttributes);
when(mockHandler.getAuthority()).thenReturn("authority");
@RunWith(JUnit4.class)
public static class WithoutXdsInClasspath extends HandlerSelectionTest {
ChannelHandler h = googleProtocolNegotiator.newHandler(mockHandler);
EmbeddedChannel chan = new EmbeddedChannel(h);
chan.pipeline().fireUserEventTriggered(InternalProtocolNegotiationEvent.getDefault());
@Nullable
@Override
Attributes.Key<String> getClusterNameAttrKey() {
return null;
}
}
assertThat(chan.pipeline().first().getClass().getSimpleName()).isEqualTo("SslHandler");
@RunWith(JUnit4.class)
public static class WithXdsInClasspath extends HandlerSelectionTest {
// Same as io.grpc.xds.InternalXdsAttributes.ATTR_CLUSTER_NAME
private static final Attributes.Key<String> XDS_CLUSTER_NAME_ATTR_KEY =
Attributes.Key.create("io.grpc.xds.InternalXdsAttributes.clusterName");
@Nullable
@Override
Attributes.Key<String> getClusterNameAttrKey() {
return XDS_CLUSTER_NAME_ATTR_KEY;
}
@Test
public void altsHandler_xdsCluster() {
Attributes attrs =
Attributes.newBuilder().set(XDS_CLUSTER_NAME_ATTR_KEY, "api.googleapis.com").build();
subtest_altsHandler(attrs);
}
@Test
public void tlsHandler_googleCfe() {
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);
}
}
}

View File

@ -34,13 +34,13 @@ import java.util.Collections;
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;

View File

@ -7,10 +7,10 @@ description = 'gRPC: Android Integration Testing'
repositories {
google()
jcenter()
}
android {
namespace = 'io.grpc.android.integrationtest'
sourceSets {
main {
java {
@ -25,16 +25,23 @@ 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
// Held back to 20 as Gradle fails to build at the 21 level. This is
// presumably a Gradle bug that can be revisited later.
// Maybe this issue: https://github.com/gradle/gradle/issues/20778
minSdkVersion 20
targetSdkVersion 33
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
multiDexEnabled true
multiDexEnabled = true
}
buildTypes {
debug { minifyEnabled false }
@ -43,33 +50,43 @@ 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:27.1.1'
implementation 'com.google.android.gms:play-services-base:15.0.1'
implementation 'androidx.appcompat:appcompat:1.3.0'
implementation 'androidx.multidex:multidex:2.0.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-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.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
compileOnly libraries.javax.annotation
androidTestImplementation 'androidx.test:rules:1.1.0-alpha1'
androidTestImplementation 'androidx.test:runner:1.1.0-alpha1'
androidTestImplementation 'androidx.test.ext:junit:1.1.3',
'androidx.test:runner:1.4.0'
}
// Checkstyle doesn't run automatically with android
@ -89,12 +106,27 @@ 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",
]
// 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, ".*/R.java", "|")
appendToProperty(
it.options.errorprone.excludedPaths,
".*/src/generated/.*",
"|")
}
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()

View File

@ -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$* {
*;
}

View File

@ -1,13 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="io.grpc.android.integrationtest.test" >
<manifest xmlns:android="http://schemas.android.com/apk/res/android" >
<instrumentation
android:name="androidx.test.runner.AndroidJUnitRunner"
android:targetPackage="io.grpc.android.integrationtest" />
<application android:debuggable="true" >
<uses-library android:name="android.test.runner" />
<application
android:name="android.support.multidex.MultiDexApplication" >
</application>
</manifest>

View File

@ -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<TesterActivity> activityRule =
new ActivityTestRule<TesterActivity>(TesterActivity.class);
private ExecutorService executor = Executors.newSingleThreadExecutor();
@Before
public void setUp() throws Exception {
@ -67,7 +63,7 @@ public class InteropInstrumentationTest {
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 class InteropInstrumentationTest {
}
private void runTest(String testCase) throws Exception {
final SettableFuture<String> 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);
}
}

View File

@ -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.InstrumentationRegistry;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.rule.ActivityTestRule;
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 ActivityTestRule<TesterActivity> activityRule =
new ActivityTestRule<TesterActivity>(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();
}
}
}

View File

@ -1,33 +1,18 @@
package io.grpc.testing.integration;
import static io.grpc.MethodDescriptor.generateFullMethodName;
import static io.grpc.stub.ClientCalls.asyncBidiStreamingCall;
import static io.grpc.stub.ClientCalls.asyncClientStreamingCall;
import static io.grpc.stub.ClientCalls.asyncServerStreamingCall;
import static io.grpc.stub.ClientCalls.asyncUnaryCall;
import static io.grpc.stub.ClientCalls.blockingServerStreamingCall;
import static io.grpc.stub.ClientCalls.blockingUnaryCall;
import static io.grpc.stub.ClientCalls.futureUnaryCall;
import static io.grpc.stub.ServerCalls.asyncBidiStreamingCall;
import static io.grpc.stub.ServerCalls.asyncClientStreamingCall;
import static io.grpc.stub.ServerCalls.asyncServerStreamingCall;
import static io.grpc.stub.ServerCalls.asyncUnaryCall;
import static io.grpc.stub.ServerCalls.asyncUnimplementedStreamingCall;
import static io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall;
/**
* <pre>
* A service used to obtain stats for verifying LB behavior.
* </pre>
*/
@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<io.grpc.testing.integration.Messages.LoadBalancerStatsRequest,
@ -60,6 +45,36 @@ public final class LoadBalancerStatsServiceGrpc {
return getGetClientStatsMethod;
}
private static volatile io.grpc.MethodDescriptor<io.grpc.testing.integration.Messages.LoadBalancerAccumulatedStatsRequest,
io.grpc.testing.integration.Messages.LoadBalancerAccumulatedStatsResponse> getGetClientAccumulatedStatsMethod;
@io.grpc.stub.annotations.RpcMethod(
fullMethodName = SERVICE_NAME + '/' + "GetClientAccumulatedStats",
requestType = io.grpc.testing.integration.Messages.LoadBalancerAccumulatedStatsRequest.class,
responseType = io.grpc.testing.integration.Messages.LoadBalancerAccumulatedStatsResponse.class,
methodType = io.grpc.MethodDescriptor.MethodType.UNARY)
public static io.grpc.MethodDescriptor<io.grpc.testing.integration.Messages.LoadBalancerAccumulatedStatsRequest,
io.grpc.testing.integration.Messages.LoadBalancerAccumulatedStatsResponse> getGetClientAccumulatedStatsMethod() {
io.grpc.MethodDescriptor<io.grpc.testing.integration.Messages.LoadBalancerAccumulatedStatsRequest, io.grpc.testing.integration.Messages.LoadBalancerAccumulatedStatsResponse> getGetClientAccumulatedStatsMethod;
if ((getGetClientAccumulatedStatsMethod = LoadBalancerStatsServiceGrpc.getGetClientAccumulatedStatsMethod) == null) {
synchronized (LoadBalancerStatsServiceGrpc.class) {
if ((getGetClientAccumulatedStatsMethod = LoadBalancerStatsServiceGrpc.getGetClientAccumulatedStatsMethod) == null) {
LoadBalancerStatsServiceGrpc.getGetClientAccumulatedStatsMethod = getGetClientAccumulatedStatsMethod =
io.grpc.MethodDescriptor.<io.grpc.testing.integration.Messages.LoadBalancerAccumulatedStatsRequest, io.grpc.testing.integration.Messages.LoadBalancerAccumulatedStatsResponse>newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName(generateFullMethodName(SERVICE_NAME, "GetClientAccumulatedStats"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(io.grpc.protobuf.lite.ProtoLiteUtils.marshaller(
io.grpc.testing.integration.Messages.LoadBalancerAccumulatedStatsRequest.getDefaultInstance()))
.setResponseMarshaller(io.grpc.protobuf.lite.ProtoLiteUtils.marshaller(
io.grpc.testing.integration.Messages.LoadBalancerAccumulatedStatsResponse.getDefaultInstance()))
.build();
}
}
}
return getGetClientAccumulatedStatsMethod;
}
/**
* Creates a new async stub that supports all call types for the service
*/
@ -74,6 +89,21 @@ public final class LoadBalancerStatsServiceGrpc {
return LoadBalancerStatsServiceStub.newStub(factory, channel);
}
/**
* Creates a new blocking-style stub that supports all types of calls on the service
*/
public static LoadBalancerStatsServiceBlockingV2Stub newBlockingV2Stub(
io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<LoadBalancerStatsServiceBlockingV2Stub> factory =
new io.grpc.stub.AbstractStub.StubFactory<LoadBalancerStatsServiceBlockingV2Stub>() {
@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
*/
@ -109,37 +139,51 @@ public final class LoadBalancerStatsServiceGrpc {
* A service used to obtain stats for verifying LB behavior.
* </pre>
*/
public static abstract class LoadBalancerStatsServiceImplBase implements io.grpc.BindableService {
public interface AsyncService {
/**
* <pre>
* Gets the backend distribution for RPCs sent by a test client.
* </pre>
*/
public void getClientStats(io.grpc.testing.integration.Messages.LoadBalancerStatsRequest request,
default void getClientStats(io.grpc.testing.integration.Messages.LoadBalancerStatsRequest request,
io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.LoadBalancerStatsResponse> responseObserver) {
asyncUnimplementedUnaryCall(getGetClientStatsMethod(), responseObserver);
io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getGetClientStatsMethod(), responseObserver);
}
@java.lang.Override public final io.grpc.ServerServiceDefinition bindService() {
return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor())
.addMethod(
getGetClientStatsMethod(),
asyncUnaryCall(
new MethodHandlers<
io.grpc.testing.integration.Messages.LoadBalancerStatsRequest,
io.grpc.testing.integration.Messages.LoadBalancerStatsResponse>(
this, METHODID_GET_CLIENT_STATS)))
.build();
/**
* <pre>
* Gets the accumulated stats for RPCs sent by a test client.
* </pre>
*/
default void getClientAccumulatedStats(io.grpc.testing.integration.Messages.LoadBalancerAccumulatedStatsRequest request,
io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.LoadBalancerAccumulatedStatsResponse> responseObserver) {
io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getGetClientAccumulatedStatsMethod(), responseObserver);
}
}
/**
* Base class for the server implementation of the service LoadBalancerStatsService.
* <pre>
* A service used to obtain stats for verifying LB behavior.
* </pre>
*/
public static final class LoadBalancerStatsServiceStub extends io.grpc.stub.AbstractAsyncStub<LoadBalancerStatsServiceStub> {
public static abstract class LoadBalancerStatsServiceImplBase
implements io.grpc.BindableService, AsyncService {
@java.lang.Override public final io.grpc.ServerServiceDefinition bindService() {
return LoadBalancerStatsServiceGrpc.bindService(this);
}
}
/**
* A stub to allow clients to do asynchronous rpc calls to service LoadBalancerStatsService.
* <pre>
* A service used to obtain stats for verifying LB behavior.
* </pre>
*/
public static final class LoadBalancerStatsServiceStub
extends io.grpc.stub.AbstractAsyncStub<LoadBalancerStatsServiceStub> {
private LoadBalancerStatsServiceStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
@ -158,17 +202,70 @@ public final class LoadBalancerStatsServiceGrpc {
*/
public void getClientStats(io.grpc.testing.integration.Messages.LoadBalancerStatsRequest request,
io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.LoadBalancerStatsResponse> responseObserver) {
asyncUnaryCall(
io.grpc.stub.ClientCalls.asyncUnaryCall(
getChannel().newCall(getGetClientStatsMethod(), getCallOptions()), request, responseObserver);
}
/**
* <pre>
* Gets the accumulated stats for RPCs sent by a test client.
* </pre>
*/
public void getClientAccumulatedStats(io.grpc.testing.integration.Messages.LoadBalancerAccumulatedStatsRequest request,
io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.LoadBalancerAccumulatedStatsResponse> responseObserver) {
io.grpc.stub.ClientCalls.asyncUnaryCall(
getChannel().newCall(getGetClientAccumulatedStatsMethod(), getCallOptions()), request, responseObserver);
}
}
/**
* A stub to allow clients to do synchronous rpc calls to service LoadBalancerStatsService.
* <pre>
* A service used to obtain stats for verifying LB behavior.
* </pre>
*/
public static final class LoadBalancerStatsServiceBlockingStub extends io.grpc.stub.AbstractBlockingStub<LoadBalancerStatsServiceBlockingStub> {
public static final class LoadBalancerStatsServiceBlockingV2Stub
extends io.grpc.stub.AbstractBlockingStub<LoadBalancerStatsServiceBlockingV2Stub> {
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);
}
/**
* <pre>
* Gets the backend distribution for RPCs sent by a test client.
* </pre>
*/
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);
}
/**
* <pre>
* Gets the accumulated stats for RPCs sent by a test client.
* </pre>
*/
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.
* <pre>
* A service used to obtain stats for verifying LB behavior.
* </pre>
*/
public static final class LoadBalancerStatsServiceBlockingStub
extends io.grpc.stub.AbstractBlockingStub<LoadBalancerStatsServiceBlockingStub> {
private LoadBalancerStatsServiceBlockingStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
@ -186,17 +283,29 @@ public final class LoadBalancerStatsServiceGrpc {
* </pre>
*/
public io.grpc.testing.integration.Messages.LoadBalancerStatsResponse getClientStats(io.grpc.testing.integration.Messages.LoadBalancerStatsRequest request) {
return blockingUnaryCall(
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getGetClientStatsMethod(), getCallOptions(), request);
}
/**
* <pre>
* Gets the accumulated stats for RPCs sent by a test client.
* </pre>
*/
public io.grpc.testing.integration.Messages.LoadBalancerAccumulatedStatsResponse getClientAccumulatedStats(io.grpc.testing.integration.Messages.LoadBalancerAccumulatedStatsRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getGetClientAccumulatedStatsMethod(), getCallOptions(), request);
}
}
/**
* A stub to allow clients to do ListenableFuture-style rpc calls to service LoadBalancerStatsService.
* <pre>
* A service used to obtain stats for verifying LB behavior.
* </pre>
*/
public static final class LoadBalancerStatsServiceFutureStub extends io.grpc.stub.AbstractFutureStub<LoadBalancerStatsServiceFutureStub> {
public static final class LoadBalancerStatsServiceFutureStub
extends io.grpc.stub.AbstractFutureStub<LoadBalancerStatsServiceFutureStub> {
private LoadBalancerStatsServiceFutureStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
@ -215,22 +324,34 @@ public final class LoadBalancerStatsServiceGrpc {
*/
public com.google.common.util.concurrent.ListenableFuture<io.grpc.testing.integration.Messages.LoadBalancerStatsResponse> getClientStats(
io.grpc.testing.integration.Messages.LoadBalancerStatsRequest request) {
return futureUnaryCall(
return io.grpc.stub.ClientCalls.futureUnaryCall(
getChannel().newCall(getGetClientStatsMethod(), getCallOptions()), request);
}
/**
* <pre>
* Gets the accumulated stats for RPCs sent by a test client.
* </pre>
*/
public com.google.common.util.concurrent.ListenableFuture<io.grpc.testing.integration.Messages.LoadBalancerAccumulatedStatsResponse> getClientAccumulatedStats(
io.grpc.testing.integration.Messages.LoadBalancerAccumulatedStatsRequest request) {
return io.grpc.stub.ClientCalls.futureUnaryCall(
getChannel().newCall(getGetClientAccumulatedStatsMethod(), getCallOptions()), request);
}
}
private static final int METHODID_GET_CLIENT_STATS = 0;
private static final int METHODID_GET_CLIENT_ACCUMULATED_STATS = 1;
private static final class MethodHandlers<Req, Resp> implements
io.grpc.stub.ServerCalls.UnaryMethod<Req, Resp>,
io.grpc.stub.ServerCalls.ServerStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.ClientStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.BidiStreamingMethod<Req, Resp> {
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;
}
@ -243,6 +364,10 @@ public final class LoadBalancerStatsServiceGrpc {
serviceImpl.getClientStats((io.grpc.testing.integration.Messages.LoadBalancerStatsRequest) request,
(io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.LoadBalancerStatsResponse>) responseObserver);
break;
case METHODID_GET_CLIENT_ACCUMULATED_STATS:
serviceImpl.getClientAccumulatedStats((io.grpc.testing.integration.Messages.LoadBalancerAccumulatedStatsRequest) request,
(io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.LoadBalancerAccumulatedStatsResponse>) responseObserver);
break;
default:
throw new AssertionError();
}
@ -259,6 +384,25 @@ public final class LoadBalancerStatsServiceGrpc {
}
}
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() {
@ -269,6 +413,7 @@ public final class LoadBalancerStatsServiceGrpc {
if (result == null) {
serviceDescriptor = result = io.grpc.ServiceDescriptor.newBuilder(SERVICE_NAME)
.addMethod(getGetClientStatsMethod())
.addMethod(getGetClientAccumulatedStatsMethod())
.build();
}
}

View File

@ -1,30 +1,15 @@
package io.grpc.testing.integration;
import static io.grpc.MethodDescriptor.generateFullMethodName;
import static io.grpc.stub.ClientCalls.asyncBidiStreamingCall;
import static io.grpc.stub.ClientCalls.asyncClientStreamingCall;
import static io.grpc.stub.ClientCalls.asyncServerStreamingCall;
import static io.grpc.stub.ClientCalls.asyncUnaryCall;
import static io.grpc.stub.ClientCalls.blockingServerStreamingCall;
import static io.grpc.stub.ClientCalls.blockingUnaryCall;
import static io.grpc.stub.ClientCalls.futureUnaryCall;
import static io.grpc.stub.ServerCalls.asyncBidiStreamingCall;
import static io.grpc.stub.ServerCalls.asyncClientStreamingCall;
import static io.grpc.stub.ServerCalls.asyncServerStreamingCall;
import static io.grpc.stub.ServerCalls.asyncUnaryCall;
import static io.grpc.stub.ServerCalls.asyncUnimplementedStreamingCall;
import static io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall;
/**
*/
@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<io.grpc.testing.integration.Metrics.EmptyMessage,
@ -101,6 +86,21 @@ public final class MetricsServiceGrpc {
return MetricsServiceStub.newStub(factory, channel);
}
/**
* Creates a new blocking-style stub that supports all types of calls on the service
*/
public static MetricsServiceBlockingV2Stub newBlockingV2Stub(
io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<MetricsServiceBlockingV2Stub> factory =
new io.grpc.stub.AbstractStub.StubFactory<MetricsServiceBlockingV2Stub>() {
@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
*/
@ -133,7 +133,7 @@ public final class MetricsServiceGrpc {
/**
*/
public static abstract class MetricsServiceImplBase implements io.grpc.BindableService {
public interface AsyncService {
/**
* <pre>
@ -141,9 +141,9 @@ public final class MetricsServiceGrpc {
* the service
* </pre>
*/
public void getAllGauges(io.grpc.testing.integration.Metrics.EmptyMessage request,
default void getAllGauges(io.grpc.testing.integration.Metrics.EmptyMessage request,
io.grpc.stub.StreamObserver<io.grpc.testing.integration.Metrics.GaugeResponse> responseObserver) {
asyncUnimplementedUnaryCall(getGetAllGaugesMethod(), responseObserver);
io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getGetAllGaugesMethod(), responseObserver);
}
/**
@ -151,34 +151,28 @@ public final class MetricsServiceGrpc {
* Returns the value of one gauge
* </pre>
*/
public void getGauge(io.grpc.testing.integration.Metrics.GaugeRequest request,
default void getGauge(io.grpc.testing.integration.Metrics.GaugeRequest request,
io.grpc.stub.StreamObserver<io.grpc.testing.integration.Metrics.GaugeResponse> responseObserver) {
asyncUnimplementedUnaryCall(getGetGaugeMethod(), responseObserver);
}
@java.lang.Override public final io.grpc.ServerServiceDefinition bindService() {
return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor())
.addMethod(
getGetAllGaugesMethod(),
asyncServerStreamingCall(
new MethodHandlers<
io.grpc.testing.integration.Metrics.EmptyMessage,
io.grpc.testing.integration.Metrics.GaugeResponse>(
this, METHODID_GET_ALL_GAUGES)))
.addMethod(
getGetGaugeMethod(),
asyncUnaryCall(
new MethodHandlers<
io.grpc.testing.integration.Metrics.GaugeRequest,
io.grpc.testing.integration.Metrics.GaugeResponse>(
this, METHODID_GET_GAUGE)))
.build();
io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getGetGaugeMethod(), responseObserver);
}
}
/**
* Base class for the server implementation of the service MetricsService.
*/
public static final class MetricsServiceStub extends io.grpc.stub.AbstractAsyncStub<MetricsServiceStub> {
public static abstract class MetricsServiceImplBase
implements io.grpc.BindableService, AsyncService {
@java.lang.Override public final io.grpc.ServerServiceDefinition bindService() {
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<MetricsServiceStub> {
private MetricsServiceStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
@ -198,7 +192,7 @@ public final class MetricsServiceGrpc {
*/
public void getAllGauges(io.grpc.testing.integration.Metrics.EmptyMessage request,
io.grpc.stub.StreamObserver<io.grpc.testing.integration.Metrics.GaugeResponse> responseObserver) {
asyncServerStreamingCall(
io.grpc.stub.ClientCalls.asyncServerStreamingCall(
getChannel().newCall(getGetAllGaugesMethod(), getCallOptions()), request, responseObserver);
}
@ -209,14 +203,56 @@ public final class MetricsServiceGrpc {
*/
public void getGauge(io.grpc.testing.integration.Metrics.GaugeRequest request,
io.grpc.stub.StreamObserver<io.grpc.testing.integration.Metrics.GaugeResponse> responseObserver) {
asyncUnaryCall(
io.grpc.stub.ClientCalls.asyncUnaryCall(
getChannel().newCall(getGetGaugeMethod(), getCallOptions()), request, responseObserver);
}
}
/**
* A stub to allow clients to do synchronous rpc calls to service MetricsService.
*/
public static final class MetricsServiceBlockingStub extends io.grpc.stub.AbstractBlockingStub<MetricsServiceBlockingStub> {
public static final class MetricsServiceBlockingV2Stub
extends io.grpc.stub.AbstractBlockingStub<MetricsServiceBlockingV2Stub> {
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);
}
/**
* <pre>
* Returns the values of all the gauges that are currently being maintained by
* the service
* </pre>
*/
@io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/10918")
public io.grpc.stub.BlockingClientCall<?, io.grpc.testing.integration.Metrics.GaugeResponse>
getAllGauges(io.grpc.testing.integration.Metrics.EmptyMessage request) {
return io.grpc.stub.ClientCalls.blockingV2ServerStreamingCall(
getChannel(), getGetAllGaugesMethod(), getCallOptions(), request);
}
/**
* <pre>
* Returns the value of one gauge
* </pre>
*/
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<MetricsServiceBlockingStub> {
private MetricsServiceBlockingStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
@ -236,7 +272,7 @@ public final class MetricsServiceGrpc {
*/
public java.util.Iterator<io.grpc.testing.integration.Metrics.GaugeResponse> getAllGauges(
io.grpc.testing.integration.Metrics.EmptyMessage request) {
return blockingServerStreamingCall(
return io.grpc.stub.ClientCalls.blockingServerStreamingCall(
getChannel(), getGetAllGaugesMethod(), getCallOptions(), request);
}
@ -246,14 +282,16 @@ public final class MetricsServiceGrpc {
* </pre>
*/
public io.grpc.testing.integration.Metrics.GaugeResponse getGauge(io.grpc.testing.integration.Metrics.GaugeRequest request) {
return blockingUnaryCall(
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getGetGaugeMethod(), getCallOptions(), request);
}
}
/**
* A stub to allow clients to do ListenableFuture-style rpc calls to service MetricsService.
*/
public static final class MetricsServiceFutureStub extends io.grpc.stub.AbstractFutureStub<MetricsServiceFutureStub> {
public static final class MetricsServiceFutureStub
extends io.grpc.stub.AbstractFutureStub<MetricsServiceFutureStub> {
private MetricsServiceFutureStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
@ -272,7 +310,7 @@ public final class MetricsServiceGrpc {
*/
public com.google.common.util.concurrent.ListenableFuture<io.grpc.testing.integration.Metrics.GaugeResponse> getGauge(
io.grpc.testing.integration.Metrics.GaugeRequest request) {
return futureUnaryCall(
return io.grpc.stub.ClientCalls.futureUnaryCall(
getChannel().newCall(getGetGaugeMethod(), getCallOptions()), request);
}
}
@ -285,10 +323,10 @@ public final class MetricsServiceGrpc {
io.grpc.stub.ServerCalls.ServerStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.ClientStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.BidiStreamingMethod<Req, Resp> {
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;
}
@ -321,6 +359,25 @@ public final class MetricsServiceGrpc {
}
}
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() {

View File

@ -1,56 +1,41 @@
package io.grpc.testing.integration;
import static io.grpc.MethodDescriptor.generateFullMethodName;
import static io.grpc.stub.ClientCalls.asyncBidiStreamingCall;
import static io.grpc.stub.ClientCalls.asyncClientStreamingCall;
import static io.grpc.stub.ClientCalls.asyncServerStreamingCall;
import static io.grpc.stub.ClientCalls.asyncUnaryCall;
import static io.grpc.stub.ClientCalls.blockingServerStreamingCall;
import static io.grpc.stub.ClientCalls.blockingUnaryCall;
import static io.grpc.stub.ClientCalls.futureUnaryCall;
import static io.grpc.stub.ServerCalls.asyncBidiStreamingCall;
import static io.grpc.stub.ServerCalls.asyncClientStreamingCall;
import static io.grpc.stub.ServerCalls.asyncServerStreamingCall;
import static io.grpc.stub.ServerCalls.asyncUnaryCall;
import static io.grpc.stub.ServerCalls.asyncUnimplementedStreamingCall;
import static io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall;
/**
* <pre>
* A service used to control reconnect server.
* </pre>
*/
@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<io.grpc.testing.integration.EmptyProtos.Empty,
private static volatile io.grpc.MethodDescriptor<io.grpc.testing.integration.Messages.ReconnectParams,
io.grpc.testing.integration.EmptyProtos.Empty> 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<io.grpc.testing.integration.EmptyProtos.Empty,
public static io.grpc.MethodDescriptor<io.grpc.testing.integration.Messages.ReconnectParams,
io.grpc.testing.integration.EmptyProtos.Empty> getStartMethod() {
io.grpc.MethodDescriptor<io.grpc.testing.integration.EmptyProtos.Empty, io.grpc.testing.integration.EmptyProtos.Empty> getStartMethod;
io.grpc.MethodDescriptor<io.grpc.testing.integration.Messages.ReconnectParams, io.grpc.testing.integration.EmptyProtos.Empty> getStartMethod;
if ((getStartMethod = ReconnectServiceGrpc.getStartMethod) == null) {
synchronized (ReconnectServiceGrpc.class) {
if ((getStartMethod = ReconnectServiceGrpc.getStartMethod) == null) {
ReconnectServiceGrpc.getStartMethod = getStartMethod =
io.grpc.MethodDescriptor.<io.grpc.testing.integration.EmptyProtos.Empty, io.grpc.testing.integration.EmptyProtos.Empty>newBuilder()
io.grpc.MethodDescriptor.<io.grpc.testing.integration.Messages.ReconnectParams, io.grpc.testing.integration.EmptyProtos.Empty>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();
@ -104,6 +89,21 @@ public final class ReconnectServiceGrpc {
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<ReconnectServiceBlockingV2Stub> factory =
new io.grpc.stub.AbstractStub.StubFactory<ReconnectServiceBlockingV2Stub>() {
@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
*/
@ -139,48 +139,45 @@ public final class ReconnectServiceGrpc {
* A service used to control reconnect server.
* </pre>
*/
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<io.grpc.testing.integration.EmptyProtos.Empty> responseObserver) {
asyncUnimplementedUnaryCall(getStartMethod(), 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<io.grpc.testing.integration.Messages.ReconnectInfo> responseObserver) {
asyncUnimplementedUnaryCall(getStopMethod(), responseObserver);
}
@java.lang.Override public final io.grpc.ServerServiceDefinition bindService() {
return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor())
.addMethod(
getStartMethod(),
asyncUnaryCall(
new MethodHandlers<
io.grpc.testing.integration.EmptyProtos.Empty,
io.grpc.testing.integration.EmptyProtos.Empty>(
this, METHODID_START)))
.addMethod(
getStopMethod(),
asyncUnaryCall(
new MethodHandlers<
io.grpc.testing.integration.EmptyProtos.Empty,
io.grpc.testing.integration.Messages.ReconnectInfo>(
this, METHODID_STOP)))
.build();
io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getStopMethod(), responseObserver);
}
}
/**
* Base class for the server implementation of the service ReconnectService.
* <pre>
* A service used to control reconnect server.
* </pre>
*/
public static final class ReconnectServiceStub extends io.grpc.stub.AbstractAsyncStub<ReconnectServiceStub> {
public static abstract class ReconnectServiceImplBase
implements io.grpc.BindableService, AsyncService {
@java.lang.Override public final io.grpc.ServerServiceDefinition bindService() {
return ReconnectServiceGrpc.bindService(this);
}
}
/**
* A stub to allow clients to do asynchronous rpc calls to service ReconnectService.
* <pre>
* A service used to control reconnect server.
* </pre>
*/
public static final class ReconnectServiceStub
extends io.grpc.stub.AbstractAsyncStub<ReconnectServiceStub> {
private ReconnectServiceStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
@ -194,9 +191,9 @@ public final class ReconnectServiceGrpc {
/**
*/
public void start(io.grpc.testing.integration.EmptyProtos.Empty request,
public void start(io.grpc.testing.integration.Messages.ReconnectParams request,
io.grpc.stub.StreamObserver<io.grpc.testing.integration.EmptyProtos.Empty> responseObserver) {
asyncUnaryCall(
io.grpc.stub.ClientCalls.asyncUnaryCall(
getChannel().newCall(getStartMethod(), getCallOptions()), request, responseObserver);
}
@ -204,17 +201,53 @@ public final class ReconnectServiceGrpc {
*/
public void stop(io.grpc.testing.integration.EmptyProtos.Empty request,
io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.ReconnectInfo> responseObserver) {
asyncUnaryCall(
io.grpc.stub.ClientCalls.asyncUnaryCall(
getChannel().newCall(getStopMethod(), getCallOptions()), request, responseObserver);
}
}
/**
* A stub to allow clients to do synchronous rpc calls to service ReconnectService.
* <pre>
* A service used to control reconnect server.
* </pre>
*/
public static final class ReconnectServiceBlockingStub extends io.grpc.stub.AbstractBlockingStub<ReconnectServiceBlockingStub> {
public static final class ReconnectServiceBlockingV2Stub
extends io.grpc.stub.AbstractBlockingStub<ReconnectServiceBlockingV2Stub> {
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.
* <pre>
* A service used to control reconnect server.
* </pre>
*/
public static final class ReconnectServiceBlockingStub
extends io.grpc.stub.AbstractBlockingStub<ReconnectServiceBlockingStub> {
private ReconnectServiceBlockingStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
@ -228,25 +261,27 @@ public final class ReconnectServiceGrpc {
/**
*/
public io.grpc.testing.integration.EmptyProtos.Empty start(io.grpc.testing.integration.EmptyProtos.Empty request) {
return blockingUnaryCall(
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);
}
/**
*/
public io.grpc.testing.integration.Messages.ReconnectInfo stop(io.grpc.testing.integration.EmptyProtos.Empty request) {
return blockingUnaryCall(
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getStopMethod(), getCallOptions(), request);
}
}
/**
* A stub to allow clients to do ListenableFuture-style rpc calls to service ReconnectService.
* <pre>
* A service used to control reconnect server.
* </pre>
*/
public static final class ReconnectServiceFutureStub extends io.grpc.stub.AbstractFutureStub<ReconnectServiceFutureStub> {
public static final class ReconnectServiceFutureStub
extends io.grpc.stub.AbstractFutureStub<ReconnectServiceFutureStub> {
private ReconnectServiceFutureStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
@ -261,8 +296,8 @@ public final class ReconnectServiceGrpc {
/**
*/
public com.google.common.util.concurrent.ListenableFuture<io.grpc.testing.integration.EmptyProtos.Empty> start(
io.grpc.testing.integration.EmptyProtos.Empty request) {
return futureUnaryCall(
io.grpc.testing.integration.Messages.ReconnectParams request) {
return io.grpc.stub.ClientCalls.futureUnaryCall(
getChannel().newCall(getStartMethod(), getCallOptions()), request);
}
@ -270,7 +305,7 @@ public final class ReconnectServiceGrpc {
*/
public com.google.common.util.concurrent.ListenableFuture<io.grpc.testing.integration.Messages.ReconnectInfo> stop(
io.grpc.testing.integration.EmptyProtos.Empty request) {
return futureUnaryCall(
return io.grpc.stub.ClientCalls.futureUnaryCall(
getChannel().newCall(getStopMethod(), getCallOptions()), request);
}
}
@ -283,10 +318,10 @@ public final class ReconnectServiceGrpc {
io.grpc.stub.ServerCalls.ServerStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.ClientStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.BidiStreamingMethod<Req, Resp> {
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;
}
@ -296,7 +331,7 @@ public final class ReconnectServiceGrpc {
public void invoke(Req request, io.grpc.stub.StreamObserver<Resp> 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<io.grpc.testing.integration.EmptyProtos.Empty>) responseObserver);
break;
case METHODID_STOP:
@ -319,6 +354,25 @@ public final class ReconnectServiceGrpc {
}
}
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() {

View File

@ -1,19 +1,6 @@
package io.grpc.testing.integration;
import static io.grpc.MethodDescriptor.generateFullMethodName;
import static io.grpc.stub.ClientCalls.asyncBidiStreamingCall;
import static io.grpc.stub.ClientCalls.asyncClientStreamingCall;
import static io.grpc.stub.ClientCalls.asyncServerStreamingCall;
import static io.grpc.stub.ClientCalls.asyncUnaryCall;
import static io.grpc.stub.ClientCalls.blockingServerStreamingCall;
import static io.grpc.stub.ClientCalls.blockingUnaryCall;
import static io.grpc.stub.ClientCalls.futureUnaryCall;
import static io.grpc.stub.ServerCalls.asyncBidiStreamingCall;
import static io.grpc.stub.ServerCalls.asyncClientStreamingCall;
import static io.grpc.stub.ServerCalls.asyncServerStreamingCall;
import static io.grpc.stub.ServerCalls.asyncUnaryCall;
import static io.grpc.stub.ServerCalls.asyncUnimplementedStreamingCall;
import static io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall;
/**
* <pre>
@ -21,14 +8,12 @@ import static io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall;
* performance with various types of payload.
* </pre>
*/
@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<io.grpc.testing.integration.EmptyProtos.Empty,
@ -285,6 +270,21 @@ public final class TestServiceGrpc {
return TestServiceStub.newStub(factory, channel);
}
/**
* Creates a new blocking-style stub that supports all types of calls on the service
*/
public static TestServiceBlockingV2Stub newBlockingV2Stub(
io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<TestServiceBlockingV2Stub> factory =
new io.grpc.stub.AbstractStub.StubFactory<TestServiceBlockingV2Stub>() {
@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
*/
@ -321,16 +321,16 @@ public final class TestServiceGrpc {
* performance with various types of payload.
* </pre>
*/
public static abstract class TestServiceImplBase implements io.grpc.BindableService {
public interface AsyncService {
/**
* <pre>
* One empty request followed by one empty response.
* </pre>
*/
public void emptyCall(io.grpc.testing.integration.EmptyProtos.Empty request,
default void emptyCall(io.grpc.testing.integration.EmptyProtos.Empty request,
io.grpc.stub.StreamObserver<io.grpc.testing.integration.EmptyProtos.Empty> responseObserver) {
asyncUnimplementedUnaryCall(getEmptyCallMethod(), responseObserver);
io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getEmptyCallMethod(), responseObserver);
}
/**
@ -338,9 +338,9 @@ public final class TestServiceGrpc {
* One request followed by one response.
* </pre>
*/
public void unaryCall(io.grpc.testing.integration.Messages.SimpleRequest request,
default void unaryCall(io.grpc.testing.integration.Messages.SimpleRequest request,
io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.SimpleResponse> responseObserver) {
asyncUnimplementedUnaryCall(getUnaryCallMethod(), responseObserver);
io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getUnaryCallMethod(), responseObserver);
}
/**
@ -350,9 +350,9 @@ public final class TestServiceGrpc {
* satisfy subsequent requests.
* </pre>
*/
public void cacheableUnaryCall(io.grpc.testing.integration.Messages.SimpleRequest request,
default void cacheableUnaryCall(io.grpc.testing.integration.Messages.SimpleRequest request,
io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.SimpleResponse> responseObserver) {
asyncUnimplementedUnaryCall(getCacheableUnaryCallMethod(), responseObserver);
io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getCacheableUnaryCallMethod(), responseObserver);
}
/**
@ -361,9 +361,9 @@ public final class TestServiceGrpc {
* The server returns the payload with client desired type and sizes.
* </pre>
*/
public void streamingOutputCall(io.grpc.testing.integration.Messages.StreamingOutputCallRequest request,
default void streamingOutputCall(io.grpc.testing.integration.Messages.StreamingOutputCallRequest request,
io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.StreamingOutputCallResponse> responseObserver) {
asyncUnimplementedUnaryCall(getStreamingOutputCallMethod(), responseObserver);
io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getStreamingOutputCallMethod(), responseObserver);
}
/**
@ -372,9 +372,9 @@ public final class TestServiceGrpc {
* The server returns the aggregated size of client payload as the result.
* </pre>
*/
public io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.StreamingInputCallRequest> streamingInputCall(
default io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.StreamingInputCallRequest> streamingInputCall(
io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.StreamingInputCallResponse> responseObserver) {
return asyncUnimplementedStreamingCall(getStreamingInputCallMethod(), responseObserver);
return io.grpc.stub.ServerCalls.asyncUnimplementedStreamingCall(getStreamingInputCallMethod(), responseObserver);
}
/**
@ -384,9 +384,9 @@ public final class TestServiceGrpc {
* demonstrates the idea of full duplexing.
* </pre>
*/
public io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.StreamingOutputCallRequest> fullDuplexCall(
default io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.StreamingOutputCallRequest> fullDuplexCall(
io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.StreamingOutputCallResponse> responseObserver) {
return asyncUnimplementedStreamingCall(getFullDuplexCallMethod(), responseObserver);
return io.grpc.stub.ServerCalls.asyncUnimplementedStreamingCall(getFullDuplexCallMethod(), responseObserver);
}
/**
@ -397,9 +397,9 @@ public final class TestServiceGrpc {
* first request.
* </pre>
*/
public io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.StreamingOutputCallRequest> halfDuplexCall(
default io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.StreamingOutputCallRequest> halfDuplexCall(
io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.StreamingOutputCallResponse> responseObserver) {
return asyncUnimplementedStreamingCall(getHalfDuplexCallMethod(), responseObserver);
return io.grpc.stub.ServerCalls.asyncUnimplementedStreamingCall(getHalfDuplexCallMethod(), responseObserver);
}
/**
@ -408,80 +408,36 @@ public final class TestServiceGrpc {
* to test the behavior when clients call unimplemented methods.
* </pre>
*/
public void unimplementedCall(io.grpc.testing.integration.EmptyProtos.Empty request,
default void unimplementedCall(io.grpc.testing.integration.EmptyProtos.Empty request,
io.grpc.stub.StreamObserver<io.grpc.testing.integration.EmptyProtos.Empty> responseObserver) {
asyncUnimplementedUnaryCall(getUnimplementedCallMethod(), responseObserver);
}
@java.lang.Override public final io.grpc.ServerServiceDefinition bindService() {
return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor())
.addMethod(
getEmptyCallMethod(),
asyncUnaryCall(
new MethodHandlers<
io.grpc.testing.integration.EmptyProtos.Empty,
io.grpc.testing.integration.EmptyProtos.Empty>(
this, METHODID_EMPTY_CALL)))
.addMethod(
getUnaryCallMethod(),
asyncUnaryCall(
new MethodHandlers<
io.grpc.testing.integration.Messages.SimpleRequest,
io.grpc.testing.integration.Messages.SimpleResponse>(
this, METHODID_UNARY_CALL)))
.addMethod(
getCacheableUnaryCallMethod(),
asyncUnaryCall(
new MethodHandlers<
io.grpc.testing.integration.Messages.SimpleRequest,
io.grpc.testing.integration.Messages.SimpleResponse>(
this, METHODID_CACHEABLE_UNARY_CALL)))
.addMethod(
getStreamingOutputCallMethod(),
asyncServerStreamingCall(
new MethodHandlers<
io.grpc.testing.integration.Messages.StreamingOutputCallRequest,
io.grpc.testing.integration.Messages.StreamingOutputCallResponse>(
this, METHODID_STREAMING_OUTPUT_CALL)))
.addMethod(
getStreamingInputCallMethod(),
asyncClientStreamingCall(
new MethodHandlers<
io.grpc.testing.integration.Messages.StreamingInputCallRequest,
io.grpc.testing.integration.Messages.StreamingInputCallResponse>(
this, METHODID_STREAMING_INPUT_CALL)))
.addMethod(
getFullDuplexCallMethod(),
asyncBidiStreamingCall(
new MethodHandlers<
io.grpc.testing.integration.Messages.StreamingOutputCallRequest,
io.grpc.testing.integration.Messages.StreamingOutputCallResponse>(
this, METHODID_FULL_DUPLEX_CALL)))
.addMethod(
getHalfDuplexCallMethod(),
asyncBidiStreamingCall(
new MethodHandlers<
io.grpc.testing.integration.Messages.StreamingOutputCallRequest,
io.grpc.testing.integration.Messages.StreamingOutputCallResponse>(
this, METHODID_HALF_DUPLEX_CALL)))
.addMethod(
getUnimplementedCallMethod(),
asyncUnaryCall(
new MethodHandlers<
io.grpc.testing.integration.EmptyProtos.Empty,
io.grpc.testing.integration.EmptyProtos.Empty>(
this, METHODID_UNIMPLEMENTED_CALL)))
.build();
io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getUnimplementedCallMethod(), responseObserver);
}
}
/**
* Base class for the server implementation of the service TestService.
* <pre>
* A simple service to test the various types of RPCs and experiment with
* performance with various types of payload.
* </pre>
*/
public static final class TestServiceStub extends io.grpc.stub.AbstractAsyncStub<TestServiceStub> {
public static abstract class TestServiceImplBase
implements io.grpc.BindableService, AsyncService {
@java.lang.Override public final io.grpc.ServerServiceDefinition bindService() {
return TestServiceGrpc.bindService(this);
}
}
/**
* A stub to allow clients to do asynchronous rpc calls to service TestService.
* <pre>
* A simple service to test the various types of RPCs and experiment with
* performance with various types of payload.
* </pre>
*/
public static final class TestServiceStub
extends io.grpc.stub.AbstractAsyncStub<TestServiceStub> {
private TestServiceStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
@ -500,7 +456,7 @@ public final class TestServiceGrpc {
*/
public void emptyCall(io.grpc.testing.integration.EmptyProtos.Empty request,
io.grpc.stub.StreamObserver<io.grpc.testing.integration.EmptyProtos.Empty> responseObserver) {
asyncUnaryCall(
io.grpc.stub.ClientCalls.asyncUnaryCall(
getChannel().newCall(getEmptyCallMethod(), getCallOptions()), request, responseObserver);
}
@ -511,7 +467,7 @@ public final class TestServiceGrpc {
*/
public void unaryCall(io.grpc.testing.integration.Messages.SimpleRequest request,
io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.SimpleResponse> responseObserver) {
asyncUnaryCall(
io.grpc.stub.ClientCalls.asyncUnaryCall(
getChannel().newCall(getUnaryCallMethod(), getCallOptions()), request, responseObserver);
}
@ -524,7 +480,7 @@ public final class TestServiceGrpc {
*/
public void cacheableUnaryCall(io.grpc.testing.integration.Messages.SimpleRequest request,
io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.SimpleResponse> responseObserver) {
asyncUnaryCall(
io.grpc.stub.ClientCalls.asyncUnaryCall(
getChannel().newCall(getCacheableUnaryCallMethod(), getCallOptions()), request, responseObserver);
}
@ -536,7 +492,7 @@ public final class TestServiceGrpc {
*/
public void streamingOutputCall(io.grpc.testing.integration.Messages.StreamingOutputCallRequest request,
io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.StreamingOutputCallResponse> responseObserver) {
asyncServerStreamingCall(
io.grpc.stub.ClientCalls.asyncServerStreamingCall(
getChannel().newCall(getStreamingOutputCallMethod(), getCallOptions()), request, responseObserver);
}
@ -548,7 +504,7 @@ public final class TestServiceGrpc {
*/
public io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.StreamingInputCallRequest> streamingInputCall(
io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.StreamingInputCallResponse> responseObserver) {
return asyncClientStreamingCall(
return io.grpc.stub.ClientCalls.asyncClientStreamingCall(
getChannel().newCall(getStreamingInputCallMethod(), getCallOptions()), responseObserver);
}
@ -561,7 +517,7 @@ public final class TestServiceGrpc {
*/
public io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.StreamingOutputCallRequest> fullDuplexCall(
io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.StreamingOutputCallResponse> responseObserver) {
return asyncBidiStreamingCall(
return io.grpc.stub.ClientCalls.asyncBidiStreamingCall(
getChannel().newCall(getFullDuplexCallMethod(), getCallOptions()), responseObserver);
}
@ -575,7 +531,7 @@ public final class TestServiceGrpc {
*/
public io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.StreamingOutputCallRequest> halfDuplexCall(
io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.StreamingOutputCallResponse> responseObserver) {
return asyncBidiStreamingCall(
return io.grpc.stub.ClientCalls.asyncBidiStreamingCall(
getChannel().newCall(getHalfDuplexCallMethod(), getCallOptions()), responseObserver);
}
@ -587,18 +543,139 @@ public final class TestServiceGrpc {
*/
public void unimplementedCall(io.grpc.testing.integration.EmptyProtos.Empty request,
io.grpc.stub.StreamObserver<io.grpc.testing.integration.EmptyProtos.Empty> responseObserver) {
asyncUnaryCall(
io.grpc.stub.ClientCalls.asyncUnaryCall(
getChannel().newCall(getUnimplementedCallMethod(), getCallOptions()), request, responseObserver);
}
}
/**
* A stub to allow clients to do synchronous rpc calls to service TestService.
* <pre>
* A simple service to test the various types of RPCs and experiment with
* performance with various types of payload.
* </pre>
*/
public static final class TestServiceBlockingStub extends io.grpc.stub.AbstractBlockingStub<TestServiceBlockingStub> {
public static final class TestServiceBlockingV2Stub
extends io.grpc.stub.AbstractBlockingStub<TestServiceBlockingV2Stub> {
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);
}
/**
* <pre>
* One empty request followed by one empty response.
* </pre>
*/
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);
}
/**
* <pre>
* One request followed by one response.
* </pre>
*/
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);
}
/**
* <pre>
* 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.
* </pre>
*/
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);
}
/**
* <pre>
* One request followed by a sequence of responses (streamed download).
* The server returns the payload with client desired type and sizes.
* </pre>
*/
@io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/10918")
public io.grpc.stub.BlockingClientCall<?, io.grpc.testing.integration.Messages.StreamingOutputCallResponse>
streamingOutputCall(io.grpc.testing.integration.Messages.StreamingOutputCallRequest request) {
return io.grpc.stub.ClientCalls.blockingV2ServerStreamingCall(
getChannel(), getStreamingOutputCallMethod(), getCallOptions(), request);
}
/**
* <pre>
* A sequence of requests followed by one response (streamed upload).
* The server returns the aggregated size of client payload as the result.
* </pre>
*/
@io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/10918")
public io.grpc.stub.BlockingClientCall<io.grpc.testing.integration.Messages.StreamingInputCallRequest, io.grpc.testing.integration.Messages.StreamingInputCallResponse>
streamingInputCall() {
return io.grpc.stub.ClientCalls.blockingClientStreamingCall(
getChannel(), getStreamingInputCallMethod(), getCallOptions());
}
/**
* <pre>
* 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.
* </pre>
*/
@io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/10918")
public io.grpc.stub.BlockingClientCall<io.grpc.testing.integration.Messages.StreamingOutputCallRequest, io.grpc.testing.integration.Messages.StreamingOutputCallResponse>
fullDuplexCall() {
return io.grpc.stub.ClientCalls.blockingBidiStreamingCall(
getChannel(), getFullDuplexCallMethod(), getCallOptions());
}
/**
* <pre>
* 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.
* </pre>
*/
@io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/10918")
public io.grpc.stub.BlockingClientCall<io.grpc.testing.integration.Messages.StreamingOutputCallRequest, io.grpc.testing.integration.Messages.StreamingOutputCallResponse>
halfDuplexCall() {
return io.grpc.stub.ClientCalls.blockingBidiStreamingCall(
getChannel(), getHalfDuplexCallMethod(), getCallOptions());
}
/**
* <pre>
* The test server will not implement this method. It will be used
* to test the behavior when clients call unimplemented methods.
* </pre>
*/
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.
* <pre>
* A simple service to test the various types of RPCs and experiment with
* performance with various types of payload.
* </pre>
*/
public static final class TestServiceBlockingStub
extends io.grpc.stub.AbstractBlockingStub<TestServiceBlockingStub> {
private TestServiceBlockingStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
@ -616,7 +693,7 @@ public final class TestServiceGrpc {
* </pre>
*/
public io.grpc.testing.integration.EmptyProtos.Empty emptyCall(io.grpc.testing.integration.EmptyProtos.Empty request) {
return blockingUnaryCall(
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getEmptyCallMethod(), getCallOptions(), request);
}
@ -626,7 +703,7 @@ public final class TestServiceGrpc {
* </pre>
*/
public io.grpc.testing.integration.Messages.SimpleResponse unaryCall(io.grpc.testing.integration.Messages.SimpleRequest request) {
return blockingUnaryCall(
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getUnaryCallMethod(), getCallOptions(), request);
}
@ -638,7 +715,7 @@ public final class TestServiceGrpc {
* </pre>
*/
public io.grpc.testing.integration.Messages.SimpleResponse cacheableUnaryCall(io.grpc.testing.integration.Messages.SimpleRequest request) {
return blockingUnaryCall(
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getCacheableUnaryCallMethod(), getCallOptions(), request);
}
@ -650,7 +727,7 @@ public final class TestServiceGrpc {
*/
public java.util.Iterator<io.grpc.testing.integration.Messages.StreamingOutputCallResponse> streamingOutputCall(
io.grpc.testing.integration.Messages.StreamingOutputCallRequest request) {
return blockingServerStreamingCall(
return io.grpc.stub.ClientCalls.blockingServerStreamingCall(
getChannel(), getStreamingOutputCallMethod(), getCallOptions(), request);
}
@ -661,18 +738,20 @@ public final class TestServiceGrpc {
* </pre>
*/
public io.grpc.testing.integration.EmptyProtos.Empty unimplementedCall(io.grpc.testing.integration.EmptyProtos.Empty request) {
return blockingUnaryCall(
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getUnimplementedCallMethod(), getCallOptions(), request);
}
}
/**
* A stub to allow clients to do ListenableFuture-style rpc calls to service TestService.
* <pre>
* A simple service to test the various types of RPCs and experiment with
* performance with various types of payload.
* </pre>
*/
public static final class TestServiceFutureStub extends io.grpc.stub.AbstractFutureStub<TestServiceFutureStub> {
public static final class TestServiceFutureStub
extends io.grpc.stub.AbstractFutureStub<TestServiceFutureStub> {
private TestServiceFutureStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
@ -691,7 +770,7 @@ public final class TestServiceGrpc {
*/
public com.google.common.util.concurrent.ListenableFuture<io.grpc.testing.integration.EmptyProtos.Empty> emptyCall(
io.grpc.testing.integration.EmptyProtos.Empty request) {
return futureUnaryCall(
return io.grpc.stub.ClientCalls.futureUnaryCall(
getChannel().newCall(getEmptyCallMethod(), getCallOptions()), request);
}
@ -702,7 +781,7 @@ public final class TestServiceGrpc {
*/
public com.google.common.util.concurrent.ListenableFuture<io.grpc.testing.integration.Messages.SimpleResponse> unaryCall(
io.grpc.testing.integration.Messages.SimpleRequest request) {
return futureUnaryCall(
return io.grpc.stub.ClientCalls.futureUnaryCall(
getChannel().newCall(getUnaryCallMethod(), getCallOptions()), request);
}
@ -715,7 +794,7 @@ public final class TestServiceGrpc {
*/
public com.google.common.util.concurrent.ListenableFuture<io.grpc.testing.integration.Messages.SimpleResponse> cacheableUnaryCall(
io.grpc.testing.integration.Messages.SimpleRequest request) {
return futureUnaryCall(
return io.grpc.stub.ClientCalls.futureUnaryCall(
getChannel().newCall(getCacheableUnaryCallMethod(), getCallOptions()), request);
}
@ -727,7 +806,7 @@ public final class TestServiceGrpc {
*/
public com.google.common.util.concurrent.ListenableFuture<io.grpc.testing.integration.EmptyProtos.Empty> unimplementedCall(
io.grpc.testing.integration.EmptyProtos.Empty request) {
return futureUnaryCall(
return io.grpc.stub.ClientCalls.futureUnaryCall(
getChannel().newCall(getUnimplementedCallMethod(), getCallOptions()), request);
}
}
@ -746,10 +825,10 @@ public final class TestServiceGrpc {
io.grpc.stub.ServerCalls.ServerStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.ClientStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.BidiStreamingMethod<Req, Resp> {
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;
}
@ -803,6 +882,67 @@ public final class TestServiceGrpc {
}
}
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() {

View File

@ -1,19 +1,6 @@
package io.grpc.testing.integration;
import static io.grpc.MethodDescriptor.generateFullMethodName;
import static io.grpc.stub.ClientCalls.asyncBidiStreamingCall;
import static io.grpc.stub.ClientCalls.asyncClientStreamingCall;
import static io.grpc.stub.ClientCalls.asyncServerStreamingCall;
import static io.grpc.stub.ClientCalls.asyncUnaryCall;
import static io.grpc.stub.ClientCalls.blockingServerStreamingCall;
import static io.grpc.stub.ClientCalls.blockingUnaryCall;
import static io.grpc.stub.ClientCalls.futureUnaryCall;
import static io.grpc.stub.ServerCalls.asyncBidiStreamingCall;
import static io.grpc.stub.ServerCalls.asyncClientStreamingCall;
import static io.grpc.stub.ServerCalls.asyncServerStreamingCall;
import static io.grpc.stub.ServerCalls.asyncUnaryCall;
import static io.grpc.stub.ServerCalls.asyncUnimplementedStreamingCall;
import static io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall;
/**
* <pre>
@ -21,14 +8,12 @@ import static io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall;
* that case.
* </pre>
*/
@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<io.grpc.testing.integration.EmptyProtos.Empty,
@ -75,6 +60,21 @@ public final class UnimplementedServiceGrpc {
return UnimplementedServiceStub.newStub(factory, channel);
}
/**
* Creates a new blocking-style stub that supports all types of calls on the service
*/
public static UnimplementedServiceBlockingV2Stub newBlockingV2Stub(
io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<UnimplementedServiceBlockingV2Stub> factory =
new io.grpc.stub.AbstractStub.StubFactory<UnimplementedServiceBlockingV2Stub>() {
@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
*/
@ -111,38 +111,43 @@ public final class UnimplementedServiceGrpc {
* that case.
* </pre>
*/
public static abstract class UnimplementedServiceImplBase implements io.grpc.BindableService {
public interface AsyncService {
/**
* <pre>
* A call that no server should implement
* </pre>
*/
public void unimplementedCall(io.grpc.testing.integration.EmptyProtos.Empty request,
default void unimplementedCall(io.grpc.testing.integration.EmptyProtos.Empty request,
io.grpc.stub.StreamObserver<io.grpc.testing.integration.EmptyProtos.Empty> responseObserver) {
asyncUnimplementedUnaryCall(getUnimplementedCallMethod(), responseObserver);
}
@java.lang.Override public final io.grpc.ServerServiceDefinition bindService() {
return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor())
.addMethod(
getUnimplementedCallMethod(),
asyncUnaryCall(
new MethodHandlers<
io.grpc.testing.integration.EmptyProtos.Empty,
io.grpc.testing.integration.EmptyProtos.Empty>(
this, METHODID_UNIMPLEMENTED_CALL)))
.build();
io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getUnimplementedCallMethod(), responseObserver);
}
}
/**
* Base class for the server implementation of the service UnimplementedService.
* <pre>
* A simple service NOT implemented at servers so clients can test for
* that case.
* </pre>
*/
public static final class UnimplementedServiceStub extends io.grpc.stub.AbstractAsyncStub<UnimplementedServiceStub> {
public static abstract class UnimplementedServiceImplBase
implements io.grpc.BindableService, AsyncService {
@java.lang.Override public final io.grpc.ServerServiceDefinition bindService() {
return UnimplementedServiceGrpc.bindService(this);
}
}
/**
* A stub to allow clients to do asynchronous rpc calls to service UnimplementedService.
* <pre>
* A simple service NOT implemented at servers so clients can test for
* that case.
* </pre>
*/
public static final class UnimplementedServiceStub
extends io.grpc.stub.AbstractAsyncStub<UnimplementedServiceStub> {
private UnimplementedServiceStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
@ -161,18 +166,51 @@ public final class UnimplementedServiceGrpc {
*/
public void unimplementedCall(io.grpc.testing.integration.EmptyProtos.Empty request,
io.grpc.stub.StreamObserver<io.grpc.testing.integration.EmptyProtos.Empty> responseObserver) {
asyncUnaryCall(
io.grpc.stub.ClientCalls.asyncUnaryCall(
getChannel().newCall(getUnimplementedCallMethod(), getCallOptions()), request, responseObserver);
}
}
/**
* A stub to allow clients to do synchronous rpc calls to service UnimplementedService.
* <pre>
* A simple service NOT implemented at servers so clients can test for
* that case.
* </pre>
*/
public static final class UnimplementedServiceBlockingStub extends io.grpc.stub.AbstractBlockingStub<UnimplementedServiceBlockingStub> {
public static final class UnimplementedServiceBlockingV2Stub
extends io.grpc.stub.AbstractBlockingStub<UnimplementedServiceBlockingV2Stub> {
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);
}
/**
* <pre>
* A call that no server should implement
* </pre>
*/
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.
* <pre>
* A simple service NOT implemented at servers so clients can test for
* that case.
* </pre>
*/
public static final class UnimplementedServiceBlockingStub
extends io.grpc.stub.AbstractBlockingStub<UnimplementedServiceBlockingStub> {
private UnimplementedServiceBlockingStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
@ -190,18 +228,20 @@ public final class UnimplementedServiceGrpc {
* </pre>
*/
public io.grpc.testing.integration.EmptyProtos.Empty unimplementedCall(io.grpc.testing.integration.EmptyProtos.Empty request) {
return blockingUnaryCall(
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getUnimplementedCallMethod(), getCallOptions(), request);
}
}
/**
* A stub to allow clients to do ListenableFuture-style rpc calls to service UnimplementedService.
* <pre>
* A simple service NOT implemented at servers so clients can test for
* that case.
* </pre>
*/
public static final class UnimplementedServiceFutureStub extends io.grpc.stub.AbstractFutureStub<UnimplementedServiceFutureStub> {
public static final class UnimplementedServiceFutureStub
extends io.grpc.stub.AbstractFutureStub<UnimplementedServiceFutureStub> {
private UnimplementedServiceFutureStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
@ -220,7 +260,7 @@ public final class UnimplementedServiceGrpc {
*/
public com.google.common.util.concurrent.ListenableFuture<io.grpc.testing.integration.EmptyProtos.Empty> unimplementedCall(
io.grpc.testing.integration.EmptyProtos.Empty request) {
return futureUnaryCall(
return io.grpc.stub.ClientCalls.futureUnaryCall(
getChannel().newCall(getUnimplementedCallMethod(), getCallOptions()), request);
}
}
@ -232,10 +272,10 @@ public final class UnimplementedServiceGrpc {
io.grpc.stub.ServerCalls.ServerStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.ClientStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.BidiStreamingMethod<Req, Resp> {
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;
}
@ -264,6 +304,18 @@ public final class UnimplementedServiceGrpc {
}
}
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() {

View File

@ -0,0 +1,328 @@
package io.grpc.testing.integration;
import static io.grpc.MethodDescriptor.generateFullMethodName;
/**
* <pre>
* A service to dynamically update the configuration of an xDS test client.
* </pre>
*/
@io.grpc.stub.annotations.GrpcGenerated
public final class XdsUpdateClientConfigureServiceGrpc {
private XdsUpdateClientConfigureServiceGrpc() {}
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<io.grpc.testing.integration.Messages.ClientConfigureRequest,
io.grpc.testing.integration.Messages.ClientConfigureResponse> getConfigureMethod;
@io.grpc.stub.annotations.RpcMethod(
fullMethodName = SERVICE_NAME + '/' + "Configure",
requestType = io.grpc.testing.integration.Messages.ClientConfigureRequest.class,
responseType = io.grpc.testing.integration.Messages.ClientConfigureResponse.class,
methodType = io.grpc.MethodDescriptor.MethodType.UNARY)
public static io.grpc.MethodDescriptor<io.grpc.testing.integration.Messages.ClientConfigureRequest,
io.grpc.testing.integration.Messages.ClientConfigureResponse> getConfigureMethod() {
io.grpc.MethodDescriptor<io.grpc.testing.integration.Messages.ClientConfigureRequest, io.grpc.testing.integration.Messages.ClientConfigureResponse> getConfigureMethod;
if ((getConfigureMethod = XdsUpdateClientConfigureServiceGrpc.getConfigureMethod) == null) {
synchronized (XdsUpdateClientConfigureServiceGrpc.class) {
if ((getConfigureMethod = XdsUpdateClientConfigureServiceGrpc.getConfigureMethod) == null) {
XdsUpdateClientConfigureServiceGrpc.getConfigureMethod = getConfigureMethod =
io.grpc.MethodDescriptor.<io.grpc.testing.integration.Messages.ClientConfigureRequest, io.grpc.testing.integration.Messages.ClientConfigureResponse>newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName(generateFullMethodName(SERVICE_NAME, "Configure"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(io.grpc.protobuf.lite.ProtoLiteUtils.marshaller(
io.grpc.testing.integration.Messages.ClientConfigureRequest.getDefaultInstance()))
.setResponseMarshaller(io.grpc.protobuf.lite.ProtoLiteUtils.marshaller(
io.grpc.testing.integration.Messages.ClientConfigureResponse.getDefaultInstance()))
.build();
}
}
}
return getConfigureMethod;
}
/**
* Creates a new async stub that supports all call types for the service
*/
public static XdsUpdateClientConfigureServiceStub newStub(io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<XdsUpdateClientConfigureServiceStub> factory =
new io.grpc.stub.AbstractStub.StubFactory<XdsUpdateClientConfigureServiceStub>() {
@java.lang.Override
public XdsUpdateClientConfigureServiceStub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new XdsUpdateClientConfigureServiceStub(channel, callOptions);
}
};
return XdsUpdateClientConfigureServiceStub.newStub(factory, channel);
}
/**
* Creates a new blocking-style stub that supports all types of calls on the service
*/
public static XdsUpdateClientConfigureServiceBlockingV2Stub newBlockingV2Stub(
io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<XdsUpdateClientConfigureServiceBlockingV2Stub> factory =
new io.grpc.stub.AbstractStub.StubFactory<XdsUpdateClientConfigureServiceBlockingV2Stub>() {
@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
*/
public static XdsUpdateClientConfigureServiceBlockingStub newBlockingStub(
io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<XdsUpdateClientConfigureServiceBlockingStub> factory =
new io.grpc.stub.AbstractStub.StubFactory<XdsUpdateClientConfigureServiceBlockingStub>() {
@java.lang.Override
public XdsUpdateClientConfigureServiceBlockingStub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new XdsUpdateClientConfigureServiceBlockingStub(channel, callOptions);
}
};
return XdsUpdateClientConfigureServiceBlockingStub.newStub(factory, channel);
}
/**
* Creates a new ListenableFuture-style stub that supports unary calls on the service
*/
public static XdsUpdateClientConfigureServiceFutureStub newFutureStub(
io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<XdsUpdateClientConfigureServiceFutureStub> factory =
new io.grpc.stub.AbstractStub.StubFactory<XdsUpdateClientConfigureServiceFutureStub>() {
@java.lang.Override
public XdsUpdateClientConfigureServiceFutureStub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new XdsUpdateClientConfigureServiceFutureStub(channel, callOptions);
}
};
return XdsUpdateClientConfigureServiceFutureStub.newStub(factory, channel);
}
/**
* <pre>
* A service to dynamically update the configuration of an xDS test client.
* </pre>
*/
public interface AsyncService {
/**
* <pre>
* Update the tes client's configuration.
* </pre>
*/
default void configure(io.grpc.testing.integration.Messages.ClientConfigureRequest request,
io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.ClientConfigureResponse> responseObserver) {
io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getConfigureMethod(), responseObserver);
}
}
/**
* Base class for the server implementation of the service XdsUpdateClientConfigureService.
* <pre>
* A service to dynamically update the configuration of an xDS test client.
* </pre>
*/
public static abstract class XdsUpdateClientConfigureServiceImplBase
implements io.grpc.BindableService, AsyncService {
@java.lang.Override public final io.grpc.ServerServiceDefinition bindService() {
return XdsUpdateClientConfigureServiceGrpc.bindService(this);
}
}
/**
* A stub to allow clients to do asynchronous rpc calls to service XdsUpdateClientConfigureService.
* <pre>
* A service to dynamically update the configuration of an xDS test client.
* </pre>
*/
public static final class XdsUpdateClientConfigureServiceStub
extends io.grpc.stub.AbstractAsyncStub<XdsUpdateClientConfigureServiceStub> {
private XdsUpdateClientConfigureServiceStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected XdsUpdateClientConfigureServiceStub build(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new XdsUpdateClientConfigureServiceStub(channel, callOptions);
}
/**
* <pre>
* Update the tes client's configuration.
* </pre>
*/
public void configure(io.grpc.testing.integration.Messages.ClientConfigureRequest request,
io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.ClientConfigureResponse> responseObserver) {
io.grpc.stub.ClientCalls.asyncUnaryCall(
getChannel().newCall(getConfigureMethod(), getCallOptions()), request, responseObserver);
}
}
/**
* A stub to allow clients to do synchronous rpc calls to service XdsUpdateClientConfigureService.
* <pre>
* A service to dynamically update the configuration of an xDS test client.
* </pre>
*/
public static final class XdsUpdateClientConfigureServiceBlockingV2Stub
extends io.grpc.stub.AbstractBlockingStub<XdsUpdateClientConfigureServiceBlockingV2Stub> {
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);
}
/**
* <pre>
* Update the tes client's configuration.
* </pre>
*/
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.
* <pre>
* A service to dynamically update the configuration of an xDS test client.
* </pre>
*/
public static final class XdsUpdateClientConfigureServiceBlockingStub
extends io.grpc.stub.AbstractBlockingStub<XdsUpdateClientConfigureServiceBlockingStub> {
private XdsUpdateClientConfigureServiceBlockingStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected XdsUpdateClientConfigureServiceBlockingStub build(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new XdsUpdateClientConfigureServiceBlockingStub(channel, callOptions);
}
/**
* <pre>
* Update the tes client's configuration.
* </pre>
*/
public io.grpc.testing.integration.Messages.ClientConfigureResponse configure(io.grpc.testing.integration.Messages.ClientConfigureRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getConfigureMethod(), getCallOptions(), request);
}
}
/**
* A stub to allow clients to do ListenableFuture-style rpc calls to service XdsUpdateClientConfigureService.
* <pre>
* A service to dynamically update the configuration of an xDS test client.
* </pre>
*/
public static final class XdsUpdateClientConfigureServiceFutureStub
extends io.grpc.stub.AbstractFutureStub<XdsUpdateClientConfigureServiceFutureStub> {
private XdsUpdateClientConfigureServiceFutureStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected XdsUpdateClientConfigureServiceFutureStub build(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new XdsUpdateClientConfigureServiceFutureStub(channel, callOptions);
}
/**
* <pre>
* Update the tes client's configuration.
* </pre>
*/
public com.google.common.util.concurrent.ListenableFuture<io.grpc.testing.integration.Messages.ClientConfigureResponse> configure(
io.grpc.testing.integration.Messages.ClientConfigureRequest request) {
return io.grpc.stub.ClientCalls.futureUnaryCall(
getChannel().newCall(getConfigureMethod(), getCallOptions()), request);
}
}
private static final int METHODID_CONFIGURE = 0;
private static final class MethodHandlers<Req, Resp> implements
io.grpc.stub.ServerCalls.UnaryMethod<Req, Resp>,
io.grpc.stub.ServerCalls.ServerStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.ClientStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.BidiStreamingMethod<Req, Resp> {
private final AsyncService serviceImpl;
private final int methodId;
MethodHandlers(AsyncService serviceImpl, int methodId) {
this.serviceImpl = serviceImpl;
this.methodId = methodId;
}
@java.lang.Override
@java.lang.SuppressWarnings("unchecked")
public void invoke(Req request, io.grpc.stub.StreamObserver<Resp> responseObserver) {
switch (methodId) {
case METHODID_CONFIGURE:
serviceImpl.configure((io.grpc.testing.integration.Messages.ClientConfigureRequest) request,
(io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.ClientConfigureResponse>) responseObserver);
break;
default:
throw new AssertionError();
}
}
@java.lang.Override
@java.lang.SuppressWarnings("unchecked")
public io.grpc.stub.StreamObserver<Req> invoke(
io.grpc.stub.StreamObserver<Resp> responseObserver) {
switch (methodId) {
default:
throw new AssertionError();
}
}
}
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() {
io.grpc.ServiceDescriptor result = serviceDescriptor;
if (result == null) {
synchronized (XdsUpdateClientConfigureServiceGrpc.class) {
result = serviceDescriptor;
if (result == null) {
serviceDescriptor = result = io.grpc.ServiceDescriptor.newBuilder(SERVICE_NAME)
.addMethod(getConfigureMethod())
.build();
}
}
}
return result;
}
}

View File

@ -0,0 +1,393 @@
package io.grpc.testing.integration;
import static io.grpc.MethodDescriptor.generateFullMethodName;
/**
* <pre>
* A service to remotely control health status of an xDS test server.
* </pre>
*/
@io.grpc.stub.annotations.GrpcGenerated
public final class XdsUpdateHealthServiceGrpc {
private XdsUpdateHealthServiceGrpc() {}
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<io.grpc.testing.integration.EmptyProtos.Empty,
io.grpc.testing.integration.EmptyProtos.Empty> getSetServingMethod;
@io.grpc.stub.annotations.RpcMethod(
fullMethodName = SERVICE_NAME + '/' + "SetServing",
requestType = io.grpc.testing.integration.EmptyProtos.Empty.class,
responseType = io.grpc.testing.integration.EmptyProtos.Empty.class,
methodType = io.grpc.MethodDescriptor.MethodType.UNARY)
public static io.grpc.MethodDescriptor<io.grpc.testing.integration.EmptyProtos.Empty,
io.grpc.testing.integration.EmptyProtos.Empty> getSetServingMethod() {
io.grpc.MethodDescriptor<io.grpc.testing.integration.EmptyProtos.Empty, io.grpc.testing.integration.EmptyProtos.Empty> getSetServingMethod;
if ((getSetServingMethod = XdsUpdateHealthServiceGrpc.getSetServingMethod) == null) {
synchronized (XdsUpdateHealthServiceGrpc.class) {
if ((getSetServingMethod = XdsUpdateHealthServiceGrpc.getSetServingMethod) == null) {
XdsUpdateHealthServiceGrpc.getSetServingMethod = getSetServingMethod =
io.grpc.MethodDescriptor.<io.grpc.testing.integration.EmptyProtos.Empty, io.grpc.testing.integration.EmptyProtos.Empty>newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName(generateFullMethodName(SERVICE_NAME, "SetServing"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(io.grpc.protobuf.lite.ProtoLiteUtils.marshaller(
io.grpc.testing.integration.EmptyProtos.Empty.getDefaultInstance()))
.setResponseMarshaller(io.grpc.protobuf.lite.ProtoLiteUtils.marshaller(
io.grpc.testing.integration.EmptyProtos.Empty.getDefaultInstance()))
.build();
}
}
}
return getSetServingMethod;
}
private static volatile io.grpc.MethodDescriptor<io.grpc.testing.integration.EmptyProtos.Empty,
io.grpc.testing.integration.EmptyProtos.Empty> getSetNotServingMethod;
@io.grpc.stub.annotations.RpcMethod(
fullMethodName = SERVICE_NAME + '/' + "SetNotServing",
requestType = io.grpc.testing.integration.EmptyProtos.Empty.class,
responseType = io.grpc.testing.integration.EmptyProtos.Empty.class,
methodType = io.grpc.MethodDescriptor.MethodType.UNARY)
public static io.grpc.MethodDescriptor<io.grpc.testing.integration.EmptyProtos.Empty,
io.grpc.testing.integration.EmptyProtos.Empty> getSetNotServingMethod() {
io.grpc.MethodDescriptor<io.grpc.testing.integration.EmptyProtos.Empty, io.grpc.testing.integration.EmptyProtos.Empty> getSetNotServingMethod;
if ((getSetNotServingMethod = XdsUpdateHealthServiceGrpc.getSetNotServingMethod) == null) {
synchronized (XdsUpdateHealthServiceGrpc.class) {
if ((getSetNotServingMethod = XdsUpdateHealthServiceGrpc.getSetNotServingMethod) == null) {
XdsUpdateHealthServiceGrpc.getSetNotServingMethod = getSetNotServingMethod =
io.grpc.MethodDescriptor.<io.grpc.testing.integration.EmptyProtos.Empty, io.grpc.testing.integration.EmptyProtos.Empty>newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName(generateFullMethodName(SERVICE_NAME, "SetNotServing"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(io.grpc.protobuf.lite.ProtoLiteUtils.marshaller(
io.grpc.testing.integration.EmptyProtos.Empty.getDefaultInstance()))
.setResponseMarshaller(io.grpc.protobuf.lite.ProtoLiteUtils.marshaller(
io.grpc.testing.integration.EmptyProtos.Empty.getDefaultInstance()))
.build();
}
}
}
return getSetNotServingMethod;
}
/**
* Creates a new async stub that supports all call types for the service
*/
public static XdsUpdateHealthServiceStub newStub(io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<XdsUpdateHealthServiceStub> factory =
new io.grpc.stub.AbstractStub.StubFactory<XdsUpdateHealthServiceStub>() {
@java.lang.Override
public XdsUpdateHealthServiceStub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new XdsUpdateHealthServiceStub(channel, callOptions);
}
};
return XdsUpdateHealthServiceStub.newStub(factory, channel);
}
/**
* Creates a new blocking-style stub that supports all types of calls on the service
*/
public static XdsUpdateHealthServiceBlockingV2Stub newBlockingV2Stub(
io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<XdsUpdateHealthServiceBlockingV2Stub> factory =
new io.grpc.stub.AbstractStub.StubFactory<XdsUpdateHealthServiceBlockingV2Stub>() {
@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
*/
public static XdsUpdateHealthServiceBlockingStub newBlockingStub(
io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<XdsUpdateHealthServiceBlockingStub> factory =
new io.grpc.stub.AbstractStub.StubFactory<XdsUpdateHealthServiceBlockingStub>() {
@java.lang.Override
public XdsUpdateHealthServiceBlockingStub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new XdsUpdateHealthServiceBlockingStub(channel, callOptions);
}
};
return XdsUpdateHealthServiceBlockingStub.newStub(factory, channel);
}
/**
* Creates a new ListenableFuture-style stub that supports unary calls on the service
*/
public static XdsUpdateHealthServiceFutureStub newFutureStub(
io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<XdsUpdateHealthServiceFutureStub> factory =
new io.grpc.stub.AbstractStub.StubFactory<XdsUpdateHealthServiceFutureStub>() {
@java.lang.Override
public XdsUpdateHealthServiceFutureStub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new XdsUpdateHealthServiceFutureStub(channel, callOptions);
}
};
return XdsUpdateHealthServiceFutureStub.newStub(factory, channel);
}
/**
* <pre>
* A service to remotely control health status of an xDS test server.
* </pre>
*/
public interface AsyncService {
/**
*/
default void setServing(io.grpc.testing.integration.EmptyProtos.Empty request,
io.grpc.stub.StreamObserver<io.grpc.testing.integration.EmptyProtos.Empty> responseObserver) {
io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getSetServingMethod(), responseObserver);
}
/**
*/
default void setNotServing(io.grpc.testing.integration.EmptyProtos.Empty request,
io.grpc.stub.StreamObserver<io.grpc.testing.integration.EmptyProtos.Empty> responseObserver) {
io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getSetNotServingMethod(), responseObserver);
}
}
/**
* Base class for the server implementation of the service XdsUpdateHealthService.
* <pre>
* A service to remotely control health status of an xDS test server.
* </pre>
*/
public static abstract class XdsUpdateHealthServiceImplBase
implements io.grpc.BindableService, AsyncService {
@java.lang.Override public final io.grpc.ServerServiceDefinition bindService() {
return XdsUpdateHealthServiceGrpc.bindService(this);
}
}
/**
* A stub to allow clients to do asynchronous rpc calls to service XdsUpdateHealthService.
* <pre>
* A service to remotely control health status of an xDS test server.
* </pre>
*/
public static final class XdsUpdateHealthServiceStub
extends io.grpc.stub.AbstractAsyncStub<XdsUpdateHealthServiceStub> {
private XdsUpdateHealthServiceStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected XdsUpdateHealthServiceStub build(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new XdsUpdateHealthServiceStub(channel, callOptions);
}
/**
*/
public void setServing(io.grpc.testing.integration.EmptyProtos.Empty request,
io.grpc.stub.StreamObserver<io.grpc.testing.integration.EmptyProtos.Empty> responseObserver) {
io.grpc.stub.ClientCalls.asyncUnaryCall(
getChannel().newCall(getSetServingMethod(), getCallOptions()), request, responseObserver);
}
/**
*/
public void setNotServing(io.grpc.testing.integration.EmptyProtos.Empty request,
io.grpc.stub.StreamObserver<io.grpc.testing.integration.EmptyProtos.Empty> responseObserver) {
io.grpc.stub.ClientCalls.asyncUnaryCall(
getChannel().newCall(getSetNotServingMethod(), getCallOptions()), request, responseObserver);
}
}
/**
* A stub to allow clients to do synchronous rpc calls to service XdsUpdateHealthService.
* <pre>
* A service to remotely control health status of an xDS test server.
* </pre>
*/
public static final class XdsUpdateHealthServiceBlockingV2Stub
extends io.grpc.stub.AbstractBlockingStub<XdsUpdateHealthServiceBlockingV2Stub> {
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.
* <pre>
* A service to remotely control health status of an xDS test server.
* </pre>
*/
public static final class XdsUpdateHealthServiceBlockingStub
extends io.grpc.stub.AbstractBlockingStub<XdsUpdateHealthServiceBlockingStub> {
private XdsUpdateHealthServiceBlockingStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected XdsUpdateHealthServiceBlockingStub build(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new XdsUpdateHealthServiceBlockingStub(channel, callOptions);
}
/**
*/
public io.grpc.testing.integration.EmptyProtos.Empty setServing(io.grpc.testing.integration.EmptyProtos.Empty request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getSetServingMethod(), getCallOptions(), request);
}
/**
*/
public io.grpc.testing.integration.EmptyProtos.Empty setNotServing(io.grpc.testing.integration.EmptyProtos.Empty request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getSetNotServingMethod(), getCallOptions(), request);
}
}
/**
* A stub to allow clients to do ListenableFuture-style rpc calls to service XdsUpdateHealthService.
* <pre>
* A service to remotely control health status of an xDS test server.
* </pre>
*/
public static final class XdsUpdateHealthServiceFutureStub
extends io.grpc.stub.AbstractFutureStub<XdsUpdateHealthServiceFutureStub> {
private XdsUpdateHealthServiceFutureStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected XdsUpdateHealthServiceFutureStub build(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new XdsUpdateHealthServiceFutureStub(channel, callOptions);
}
/**
*/
public com.google.common.util.concurrent.ListenableFuture<io.grpc.testing.integration.EmptyProtos.Empty> setServing(
io.grpc.testing.integration.EmptyProtos.Empty request) {
return io.grpc.stub.ClientCalls.futureUnaryCall(
getChannel().newCall(getSetServingMethod(), getCallOptions()), request);
}
/**
*/
public com.google.common.util.concurrent.ListenableFuture<io.grpc.testing.integration.EmptyProtos.Empty> setNotServing(
io.grpc.testing.integration.EmptyProtos.Empty request) {
return io.grpc.stub.ClientCalls.futureUnaryCall(
getChannel().newCall(getSetNotServingMethod(), getCallOptions()), request);
}
}
private static final int METHODID_SET_SERVING = 0;
private static final int METHODID_SET_NOT_SERVING = 1;
private static final class MethodHandlers<Req, Resp> implements
io.grpc.stub.ServerCalls.UnaryMethod<Req, Resp>,
io.grpc.stub.ServerCalls.ServerStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.ClientStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.BidiStreamingMethod<Req, Resp> {
private final AsyncService serviceImpl;
private final int methodId;
MethodHandlers(AsyncService serviceImpl, int methodId) {
this.serviceImpl = serviceImpl;
this.methodId = methodId;
}
@java.lang.Override
@java.lang.SuppressWarnings("unchecked")
public void invoke(Req request, io.grpc.stub.StreamObserver<Resp> responseObserver) {
switch (methodId) {
case METHODID_SET_SERVING:
serviceImpl.setServing((io.grpc.testing.integration.EmptyProtos.Empty) request,
(io.grpc.stub.StreamObserver<io.grpc.testing.integration.EmptyProtos.Empty>) responseObserver);
break;
case METHODID_SET_NOT_SERVING:
serviceImpl.setNotServing((io.grpc.testing.integration.EmptyProtos.Empty) request,
(io.grpc.stub.StreamObserver<io.grpc.testing.integration.EmptyProtos.Empty>) responseObserver);
break;
default:
throw new AssertionError();
}
}
@java.lang.Override
@java.lang.SuppressWarnings("unchecked")
public io.grpc.stub.StreamObserver<Req> invoke(
io.grpc.stub.StreamObserver<Resp> responseObserver) {
switch (methodId) {
default:
throw new AssertionError();
}
}
}
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() {
io.grpc.ServiceDescriptor result = serviceDescriptor;
if (result == null) {
synchronized (XdsUpdateHealthServiceGrpc.class) {
result = serviceDescriptor;
if (result == null) {
serviceDescriptor = result = io.grpc.ServiceDescriptor.newBuilder(SERVICE_NAME)
.addMethod(getSetServingMethod())
.addMethod(getSetNotServingMethod())
.build();
}
}
}
return result;
}
}

View File

@ -1,33 +1,18 @@
package io.grpc.testing.integration;
import static io.grpc.MethodDescriptor.generateFullMethodName;
import static io.grpc.stub.ClientCalls.asyncBidiStreamingCall;
import static io.grpc.stub.ClientCalls.asyncClientStreamingCall;
import static io.grpc.stub.ClientCalls.asyncServerStreamingCall;
import static io.grpc.stub.ClientCalls.asyncUnaryCall;
import static io.grpc.stub.ClientCalls.blockingServerStreamingCall;
import static io.grpc.stub.ClientCalls.blockingUnaryCall;
import static io.grpc.stub.ClientCalls.futureUnaryCall;
import static io.grpc.stub.ServerCalls.asyncBidiStreamingCall;
import static io.grpc.stub.ServerCalls.asyncClientStreamingCall;
import static io.grpc.stub.ServerCalls.asyncServerStreamingCall;
import static io.grpc.stub.ServerCalls.asyncUnaryCall;
import static io.grpc.stub.ServerCalls.asyncUnimplementedStreamingCall;
import static io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall;
/**
* <pre>
* A service used to obtain stats for verifying LB behavior.
* </pre>
*/
@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<io.grpc.testing.integration.Messages.LoadBalancerStatsRequest,
@ -60,6 +45,36 @@ public final class LoadBalancerStatsServiceGrpc {
return getGetClientStatsMethod;
}
private static volatile io.grpc.MethodDescriptor<io.grpc.testing.integration.Messages.LoadBalancerAccumulatedStatsRequest,
io.grpc.testing.integration.Messages.LoadBalancerAccumulatedStatsResponse> getGetClientAccumulatedStatsMethod;
@io.grpc.stub.annotations.RpcMethod(
fullMethodName = SERVICE_NAME + '/' + "GetClientAccumulatedStats",
requestType = io.grpc.testing.integration.Messages.LoadBalancerAccumulatedStatsRequest.class,
responseType = io.grpc.testing.integration.Messages.LoadBalancerAccumulatedStatsResponse.class,
methodType = io.grpc.MethodDescriptor.MethodType.UNARY)
public static io.grpc.MethodDescriptor<io.grpc.testing.integration.Messages.LoadBalancerAccumulatedStatsRequest,
io.grpc.testing.integration.Messages.LoadBalancerAccumulatedStatsResponse> getGetClientAccumulatedStatsMethod() {
io.grpc.MethodDescriptor<io.grpc.testing.integration.Messages.LoadBalancerAccumulatedStatsRequest, io.grpc.testing.integration.Messages.LoadBalancerAccumulatedStatsResponse> getGetClientAccumulatedStatsMethod;
if ((getGetClientAccumulatedStatsMethod = LoadBalancerStatsServiceGrpc.getGetClientAccumulatedStatsMethod) == null) {
synchronized (LoadBalancerStatsServiceGrpc.class) {
if ((getGetClientAccumulatedStatsMethod = LoadBalancerStatsServiceGrpc.getGetClientAccumulatedStatsMethod) == null) {
LoadBalancerStatsServiceGrpc.getGetClientAccumulatedStatsMethod = getGetClientAccumulatedStatsMethod =
io.grpc.MethodDescriptor.<io.grpc.testing.integration.Messages.LoadBalancerAccumulatedStatsRequest, io.grpc.testing.integration.Messages.LoadBalancerAccumulatedStatsResponse>newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName(generateFullMethodName(SERVICE_NAME, "GetClientAccumulatedStats"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(io.grpc.protobuf.lite.ProtoLiteUtils.marshaller(
io.grpc.testing.integration.Messages.LoadBalancerAccumulatedStatsRequest.getDefaultInstance()))
.setResponseMarshaller(io.grpc.protobuf.lite.ProtoLiteUtils.marshaller(
io.grpc.testing.integration.Messages.LoadBalancerAccumulatedStatsResponse.getDefaultInstance()))
.build();
}
}
}
return getGetClientAccumulatedStatsMethod;
}
/**
* Creates a new async stub that supports all call types for the service
*/
@ -74,6 +89,21 @@ public final class LoadBalancerStatsServiceGrpc {
return LoadBalancerStatsServiceStub.newStub(factory, channel);
}
/**
* Creates a new blocking-style stub that supports all types of calls on the service
*/
public static LoadBalancerStatsServiceBlockingV2Stub newBlockingV2Stub(
io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<LoadBalancerStatsServiceBlockingV2Stub> factory =
new io.grpc.stub.AbstractStub.StubFactory<LoadBalancerStatsServiceBlockingV2Stub>() {
@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
*/
@ -109,37 +139,51 @@ public final class LoadBalancerStatsServiceGrpc {
* A service used to obtain stats for verifying LB behavior.
* </pre>
*/
public static abstract class LoadBalancerStatsServiceImplBase implements io.grpc.BindableService {
public interface AsyncService {
/**
* <pre>
* Gets the backend distribution for RPCs sent by a test client.
* </pre>
*/
public void getClientStats(io.grpc.testing.integration.Messages.LoadBalancerStatsRequest request,
default void getClientStats(io.grpc.testing.integration.Messages.LoadBalancerStatsRequest request,
io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.LoadBalancerStatsResponse> responseObserver) {
asyncUnimplementedUnaryCall(getGetClientStatsMethod(), responseObserver);
io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getGetClientStatsMethod(), responseObserver);
}
@java.lang.Override public final io.grpc.ServerServiceDefinition bindService() {
return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor())
.addMethod(
getGetClientStatsMethod(),
asyncUnaryCall(
new MethodHandlers<
io.grpc.testing.integration.Messages.LoadBalancerStatsRequest,
io.grpc.testing.integration.Messages.LoadBalancerStatsResponse>(
this, METHODID_GET_CLIENT_STATS)))
.build();
/**
* <pre>
* Gets the accumulated stats for RPCs sent by a test client.
* </pre>
*/
default void getClientAccumulatedStats(io.grpc.testing.integration.Messages.LoadBalancerAccumulatedStatsRequest request,
io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.LoadBalancerAccumulatedStatsResponse> responseObserver) {
io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getGetClientAccumulatedStatsMethod(), responseObserver);
}
}
/**
* Base class for the server implementation of the service LoadBalancerStatsService.
* <pre>
* A service used to obtain stats for verifying LB behavior.
* </pre>
*/
public static final class LoadBalancerStatsServiceStub extends io.grpc.stub.AbstractAsyncStub<LoadBalancerStatsServiceStub> {
public static abstract class LoadBalancerStatsServiceImplBase
implements io.grpc.BindableService, AsyncService {
@java.lang.Override public final io.grpc.ServerServiceDefinition bindService() {
return LoadBalancerStatsServiceGrpc.bindService(this);
}
}
/**
* A stub to allow clients to do asynchronous rpc calls to service LoadBalancerStatsService.
* <pre>
* A service used to obtain stats for verifying LB behavior.
* </pre>
*/
public static final class LoadBalancerStatsServiceStub
extends io.grpc.stub.AbstractAsyncStub<LoadBalancerStatsServiceStub> {
private LoadBalancerStatsServiceStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
@ -158,17 +202,70 @@ public final class LoadBalancerStatsServiceGrpc {
*/
public void getClientStats(io.grpc.testing.integration.Messages.LoadBalancerStatsRequest request,
io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.LoadBalancerStatsResponse> responseObserver) {
asyncUnaryCall(
io.grpc.stub.ClientCalls.asyncUnaryCall(
getChannel().newCall(getGetClientStatsMethod(), getCallOptions()), request, responseObserver);
}
/**
* <pre>
* Gets the accumulated stats for RPCs sent by a test client.
* </pre>
*/
public void getClientAccumulatedStats(io.grpc.testing.integration.Messages.LoadBalancerAccumulatedStatsRequest request,
io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.LoadBalancerAccumulatedStatsResponse> responseObserver) {
io.grpc.stub.ClientCalls.asyncUnaryCall(
getChannel().newCall(getGetClientAccumulatedStatsMethod(), getCallOptions()), request, responseObserver);
}
}
/**
* A stub to allow clients to do synchronous rpc calls to service LoadBalancerStatsService.
* <pre>
* A service used to obtain stats for verifying LB behavior.
* </pre>
*/
public static final class LoadBalancerStatsServiceBlockingStub extends io.grpc.stub.AbstractBlockingStub<LoadBalancerStatsServiceBlockingStub> {
public static final class LoadBalancerStatsServiceBlockingV2Stub
extends io.grpc.stub.AbstractBlockingStub<LoadBalancerStatsServiceBlockingV2Stub> {
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);
}
/**
* <pre>
* Gets the backend distribution for RPCs sent by a test client.
* </pre>
*/
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);
}
/**
* <pre>
* Gets the accumulated stats for RPCs sent by a test client.
* </pre>
*/
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.
* <pre>
* A service used to obtain stats for verifying LB behavior.
* </pre>
*/
public static final class LoadBalancerStatsServiceBlockingStub
extends io.grpc.stub.AbstractBlockingStub<LoadBalancerStatsServiceBlockingStub> {
private LoadBalancerStatsServiceBlockingStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
@ -186,17 +283,29 @@ public final class LoadBalancerStatsServiceGrpc {
* </pre>
*/
public io.grpc.testing.integration.Messages.LoadBalancerStatsResponse getClientStats(io.grpc.testing.integration.Messages.LoadBalancerStatsRequest request) {
return blockingUnaryCall(
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getGetClientStatsMethod(), getCallOptions(), request);
}
/**
* <pre>
* Gets the accumulated stats for RPCs sent by a test client.
* </pre>
*/
public io.grpc.testing.integration.Messages.LoadBalancerAccumulatedStatsResponse getClientAccumulatedStats(io.grpc.testing.integration.Messages.LoadBalancerAccumulatedStatsRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getGetClientAccumulatedStatsMethod(), getCallOptions(), request);
}
}
/**
* A stub to allow clients to do ListenableFuture-style rpc calls to service LoadBalancerStatsService.
* <pre>
* A service used to obtain stats for verifying LB behavior.
* </pre>
*/
public static final class LoadBalancerStatsServiceFutureStub extends io.grpc.stub.AbstractFutureStub<LoadBalancerStatsServiceFutureStub> {
public static final class LoadBalancerStatsServiceFutureStub
extends io.grpc.stub.AbstractFutureStub<LoadBalancerStatsServiceFutureStub> {
private LoadBalancerStatsServiceFutureStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
@ -215,22 +324,34 @@ public final class LoadBalancerStatsServiceGrpc {
*/
public com.google.common.util.concurrent.ListenableFuture<io.grpc.testing.integration.Messages.LoadBalancerStatsResponse> getClientStats(
io.grpc.testing.integration.Messages.LoadBalancerStatsRequest request) {
return futureUnaryCall(
return io.grpc.stub.ClientCalls.futureUnaryCall(
getChannel().newCall(getGetClientStatsMethod(), getCallOptions()), request);
}
/**
* <pre>
* Gets the accumulated stats for RPCs sent by a test client.
* </pre>
*/
public com.google.common.util.concurrent.ListenableFuture<io.grpc.testing.integration.Messages.LoadBalancerAccumulatedStatsResponse> getClientAccumulatedStats(
io.grpc.testing.integration.Messages.LoadBalancerAccumulatedStatsRequest request) {
return io.grpc.stub.ClientCalls.futureUnaryCall(
getChannel().newCall(getGetClientAccumulatedStatsMethod(), getCallOptions()), request);
}
}
private static final int METHODID_GET_CLIENT_STATS = 0;
private static final int METHODID_GET_CLIENT_ACCUMULATED_STATS = 1;
private static final class MethodHandlers<Req, Resp> implements
io.grpc.stub.ServerCalls.UnaryMethod<Req, Resp>,
io.grpc.stub.ServerCalls.ServerStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.ClientStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.BidiStreamingMethod<Req, Resp> {
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;
}
@ -243,6 +364,10 @@ public final class LoadBalancerStatsServiceGrpc {
serviceImpl.getClientStats((io.grpc.testing.integration.Messages.LoadBalancerStatsRequest) request,
(io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.LoadBalancerStatsResponse>) responseObserver);
break;
case METHODID_GET_CLIENT_ACCUMULATED_STATS:
serviceImpl.getClientAccumulatedStats((io.grpc.testing.integration.Messages.LoadBalancerAccumulatedStatsRequest) request,
(io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.LoadBalancerAccumulatedStatsResponse>) responseObserver);
break;
default:
throw new AssertionError();
}
@ -259,6 +384,25 @@ public final class LoadBalancerStatsServiceGrpc {
}
}
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() {
@ -269,6 +413,7 @@ public final class LoadBalancerStatsServiceGrpc {
if (result == null) {
serviceDescriptor = result = io.grpc.ServiceDescriptor.newBuilder(SERVICE_NAME)
.addMethod(getGetClientStatsMethod())
.addMethod(getGetClientAccumulatedStatsMethod())
.build();
}
}

View File

@ -1,30 +1,15 @@
package io.grpc.testing.integration;
import static io.grpc.MethodDescriptor.generateFullMethodName;
import static io.grpc.stub.ClientCalls.asyncBidiStreamingCall;
import static io.grpc.stub.ClientCalls.asyncClientStreamingCall;
import static io.grpc.stub.ClientCalls.asyncServerStreamingCall;
import static io.grpc.stub.ClientCalls.asyncUnaryCall;
import static io.grpc.stub.ClientCalls.blockingServerStreamingCall;
import static io.grpc.stub.ClientCalls.blockingUnaryCall;
import static io.grpc.stub.ClientCalls.futureUnaryCall;
import static io.grpc.stub.ServerCalls.asyncBidiStreamingCall;
import static io.grpc.stub.ServerCalls.asyncClientStreamingCall;
import static io.grpc.stub.ServerCalls.asyncServerStreamingCall;
import static io.grpc.stub.ServerCalls.asyncUnaryCall;
import static io.grpc.stub.ServerCalls.asyncUnimplementedStreamingCall;
import static io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall;
/**
*/
@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<io.grpc.testing.integration.Metrics.EmptyMessage,
@ -101,6 +86,21 @@ public final class MetricsServiceGrpc {
return MetricsServiceStub.newStub(factory, channel);
}
/**
* Creates a new blocking-style stub that supports all types of calls on the service
*/
public static MetricsServiceBlockingV2Stub newBlockingV2Stub(
io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<MetricsServiceBlockingV2Stub> factory =
new io.grpc.stub.AbstractStub.StubFactory<MetricsServiceBlockingV2Stub>() {
@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
*/
@ -133,7 +133,7 @@ public final class MetricsServiceGrpc {
/**
*/
public static abstract class MetricsServiceImplBase implements io.grpc.BindableService {
public interface AsyncService {
/**
* <pre>
@ -141,9 +141,9 @@ public final class MetricsServiceGrpc {
* the service
* </pre>
*/
public void getAllGauges(io.grpc.testing.integration.Metrics.EmptyMessage request,
default void getAllGauges(io.grpc.testing.integration.Metrics.EmptyMessage request,
io.grpc.stub.StreamObserver<io.grpc.testing.integration.Metrics.GaugeResponse> responseObserver) {
asyncUnimplementedUnaryCall(getGetAllGaugesMethod(), responseObserver);
io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getGetAllGaugesMethod(), responseObserver);
}
/**
@ -151,34 +151,28 @@ public final class MetricsServiceGrpc {
* Returns the value of one gauge
* </pre>
*/
public void getGauge(io.grpc.testing.integration.Metrics.GaugeRequest request,
default void getGauge(io.grpc.testing.integration.Metrics.GaugeRequest request,
io.grpc.stub.StreamObserver<io.grpc.testing.integration.Metrics.GaugeResponse> responseObserver) {
asyncUnimplementedUnaryCall(getGetGaugeMethod(), responseObserver);
}
@java.lang.Override public final io.grpc.ServerServiceDefinition bindService() {
return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor())
.addMethod(
getGetAllGaugesMethod(),
asyncServerStreamingCall(
new MethodHandlers<
io.grpc.testing.integration.Metrics.EmptyMessage,
io.grpc.testing.integration.Metrics.GaugeResponse>(
this, METHODID_GET_ALL_GAUGES)))
.addMethod(
getGetGaugeMethod(),
asyncUnaryCall(
new MethodHandlers<
io.grpc.testing.integration.Metrics.GaugeRequest,
io.grpc.testing.integration.Metrics.GaugeResponse>(
this, METHODID_GET_GAUGE)))
.build();
io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getGetGaugeMethod(), responseObserver);
}
}
/**
* Base class for the server implementation of the service MetricsService.
*/
public static final class MetricsServiceStub extends io.grpc.stub.AbstractAsyncStub<MetricsServiceStub> {
public static abstract class MetricsServiceImplBase
implements io.grpc.BindableService, AsyncService {
@java.lang.Override public final io.grpc.ServerServiceDefinition bindService() {
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<MetricsServiceStub> {
private MetricsServiceStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
@ -198,7 +192,7 @@ public final class MetricsServiceGrpc {
*/
public void getAllGauges(io.grpc.testing.integration.Metrics.EmptyMessage request,
io.grpc.stub.StreamObserver<io.grpc.testing.integration.Metrics.GaugeResponse> responseObserver) {
asyncServerStreamingCall(
io.grpc.stub.ClientCalls.asyncServerStreamingCall(
getChannel().newCall(getGetAllGaugesMethod(), getCallOptions()), request, responseObserver);
}
@ -209,14 +203,56 @@ public final class MetricsServiceGrpc {
*/
public void getGauge(io.grpc.testing.integration.Metrics.GaugeRequest request,
io.grpc.stub.StreamObserver<io.grpc.testing.integration.Metrics.GaugeResponse> responseObserver) {
asyncUnaryCall(
io.grpc.stub.ClientCalls.asyncUnaryCall(
getChannel().newCall(getGetGaugeMethod(), getCallOptions()), request, responseObserver);
}
}
/**
* A stub to allow clients to do synchronous rpc calls to service MetricsService.
*/
public static final class MetricsServiceBlockingStub extends io.grpc.stub.AbstractBlockingStub<MetricsServiceBlockingStub> {
public static final class MetricsServiceBlockingV2Stub
extends io.grpc.stub.AbstractBlockingStub<MetricsServiceBlockingV2Stub> {
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);
}
/**
* <pre>
* Returns the values of all the gauges that are currently being maintained by
* the service
* </pre>
*/
@io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/10918")
public io.grpc.stub.BlockingClientCall<?, io.grpc.testing.integration.Metrics.GaugeResponse>
getAllGauges(io.grpc.testing.integration.Metrics.EmptyMessage request) {
return io.grpc.stub.ClientCalls.blockingV2ServerStreamingCall(
getChannel(), getGetAllGaugesMethod(), getCallOptions(), request);
}
/**
* <pre>
* Returns the value of one gauge
* </pre>
*/
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<MetricsServiceBlockingStub> {
private MetricsServiceBlockingStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
@ -236,7 +272,7 @@ public final class MetricsServiceGrpc {
*/
public java.util.Iterator<io.grpc.testing.integration.Metrics.GaugeResponse> getAllGauges(
io.grpc.testing.integration.Metrics.EmptyMessage request) {
return blockingServerStreamingCall(
return io.grpc.stub.ClientCalls.blockingServerStreamingCall(
getChannel(), getGetAllGaugesMethod(), getCallOptions(), request);
}
@ -246,14 +282,16 @@ public final class MetricsServiceGrpc {
* </pre>
*/
public io.grpc.testing.integration.Metrics.GaugeResponse getGauge(io.grpc.testing.integration.Metrics.GaugeRequest request) {
return blockingUnaryCall(
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getGetGaugeMethod(), getCallOptions(), request);
}
}
/**
* A stub to allow clients to do ListenableFuture-style rpc calls to service MetricsService.
*/
public static final class MetricsServiceFutureStub extends io.grpc.stub.AbstractFutureStub<MetricsServiceFutureStub> {
public static final class MetricsServiceFutureStub
extends io.grpc.stub.AbstractFutureStub<MetricsServiceFutureStub> {
private MetricsServiceFutureStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
@ -272,7 +310,7 @@ public final class MetricsServiceGrpc {
*/
public com.google.common.util.concurrent.ListenableFuture<io.grpc.testing.integration.Metrics.GaugeResponse> getGauge(
io.grpc.testing.integration.Metrics.GaugeRequest request) {
return futureUnaryCall(
return io.grpc.stub.ClientCalls.futureUnaryCall(
getChannel().newCall(getGetGaugeMethod(), getCallOptions()), request);
}
}
@ -285,10 +323,10 @@ public final class MetricsServiceGrpc {
io.grpc.stub.ServerCalls.ServerStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.ClientStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.BidiStreamingMethod<Req, Resp> {
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;
}
@ -321,6 +359,25 @@ public final class MetricsServiceGrpc {
}
}
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() {

View File

@ -1,56 +1,41 @@
package io.grpc.testing.integration;
import static io.grpc.MethodDescriptor.generateFullMethodName;
import static io.grpc.stub.ClientCalls.asyncBidiStreamingCall;
import static io.grpc.stub.ClientCalls.asyncClientStreamingCall;
import static io.grpc.stub.ClientCalls.asyncServerStreamingCall;
import static io.grpc.stub.ClientCalls.asyncUnaryCall;
import static io.grpc.stub.ClientCalls.blockingServerStreamingCall;
import static io.grpc.stub.ClientCalls.blockingUnaryCall;
import static io.grpc.stub.ClientCalls.futureUnaryCall;
import static io.grpc.stub.ServerCalls.asyncBidiStreamingCall;
import static io.grpc.stub.ServerCalls.asyncClientStreamingCall;
import static io.grpc.stub.ServerCalls.asyncServerStreamingCall;
import static io.grpc.stub.ServerCalls.asyncUnaryCall;
import static io.grpc.stub.ServerCalls.asyncUnimplementedStreamingCall;
import static io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall;
/**
* <pre>
* A service used to control reconnect server.
* </pre>
*/
@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<io.grpc.testing.integration.EmptyProtos.Empty,
private static volatile io.grpc.MethodDescriptor<io.grpc.testing.integration.Messages.ReconnectParams,
io.grpc.testing.integration.EmptyProtos.Empty> 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<io.grpc.testing.integration.EmptyProtos.Empty,
public static io.grpc.MethodDescriptor<io.grpc.testing.integration.Messages.ReconnectParams,
io.grpc.testing.integration.EmptyProtos.Empty> getStartMethod() {
io.grpc.MethodDescriptor<io.grpc.testing.integration.EmptyProtos.Empty, io.grpc.testing.integration.EmptyProtos.Empty> getStartMethod;
io.grpc.MethodDescriptor<io.grpc.testing.integration.Messages.ReconnectParams, io.grpc.testing.integration.EmptyProtos.Empty> getStartMethod;
if ((getStartMethod = ReconnectServiceGrpc.getStartMethod) == null) {
synchronized (ReconnectServiceGrpc.class) {
if ((getStartMethod = ReconnectServiceGrpc.getStartMethod) == null) {
ReconnectServiceGrpc.getStartMethod = getStartMethod =
io.grpc.MethodDescriptor.<io.grpc.testing.integration.EmptyProtos.Empty, io.grpc.testing.integration.EmptyProtos.Empty>newBuilder()
io.grpc.MethodDescriptor.<io.grpc.testing.integration.Messages.ReconnectParams, io.grpc.testing.integration.EmptyProtos.Empty>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();
@ -104,6 +89,21 @@ public final class ReconnectServiceGrpc {
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<ReconnectServiceBlockingV2Stub> factory =
new io.grpc.stub.AbstractStub.StubFactory<ReconnectServiceBlockingV2Stub>() {
@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
*/
@ -139,48 +139,45 @@ public final class ReconnectServiceGrpc {
* A service used to control reconnect server.
* </pre>
*/
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<io.grpc.testing.integration.EmptyProtos.Empty> responseObserver) {
asyncUnimplementedUnaryCall(getStartMethod(), 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<io.grpc.testing.integration.Messages.ReconnectInfo> responseObserver) {
asyncUnimplementedUnaryCall(getStopMethod(), responseObserver);
}
@java.lang.Override public final io.grpc.ServerServiceDefinition bindService() {
return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor())
.addMethod(
getStartMethod(),
asyncUnaryCall(
new MethodHandlers<
io.grpc.testing.integration.EmptyProtos.Empty,
io.grpc.testing.integration.EmptyProtos.Empty>(
this, METHODID_START)))
.addMethod(
getStopMethod(),
asyncUnaryCall(
new MethodHandlers<
io.grpc.testing.integration.EmptyProtos.Empty,
io.grpc.testing.integration.Messages.ReconnectInfo>(
this, METHODID_STOP)))
.build();
io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getStopMethod(), responseObserver);
}
}
/**
* Base class for the server implementation of the service ReconnectService.
* <pre>
* A service used to control reconnect server.
* </pre>
*/
public static final class ReconnectServiceStub extends io.grpc.stub.AbstractAsyncStub<ReconnectServiceStub> {
public static abstract class ReconnectServiceImplBase
implements io.grpc.BindableService, AsyncService {
@java.lang.Override public final io.grpc.ServerServiceDefinition bindService() {
return ReconnectServiceGrpc.bindService(this);
}
}
/**
* A stub to allow clients to do asynchronous rpc calls to service ReconnectService.
* <pre>
* A service used to control reconnect server.
* </pre>
*/
public static final class ReconnectServiceStub
extends io.grpc.stub.AbstractAsyncStub<ReconnectServiceStub> {
private ReconnectServiceStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
@ -194,9 +191,9 @@ public final class ReconnectServiceGrpc {
/**
*/
public void start(io.grpc.testing.integration.EmptyProtos.Empty request,
public void start(io.grpc.testing.integration.Messages.ReconnectParams request,
io.grpc.stub.StreamObserver<io.grpc.testing.integration.EmptyProtos.Empty> responseObserver) {
asyncUnaryCall(
io.grpc.stub.ClientCalls.asyncUnaryCall(
getChannel().newCall(getStartMethod(), getCallOptions()), request, responseObserver);
}
@ -204,17 +201,53 @@ public final class ReconnectServiceGrpc {
*/
public void stop(io.grpc.testing.integration.EmptyProtos.Empty request,
io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.ReconnectInfo> responseObserver) {
asyncUnaryCall(
io.grpc.stub.ClientCalls.asyncUnaryCall(
getChannel().newCall(getStopMethod(), getCallOptions()), request, responseObserver);
}
}
/**
* A stub to allow clients to do synchronous rpc calls to service ReconnectService.
* <pre>
* A service used to control reconnect server.
* </pre>
*/
public static final class ReconnectServiceBlockingStub extends io.grpc.stub.AbstractBlockingStub<ReconnectServiceBlockingStub> {
public static final class ReconnectServiceBlockingV2Stub
extends io.grpc.stub.AbstractBlockingStub<ReconnectServiceBlockingV2Stub> {
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.
* <pre>
* A service used to control reconnect server.
* </pre>
*/
public static final class ReconnectServiceBlockingStub
extends io.grpc.stub.AbstractBlockingStub<ReconnectServiceBlockingStub> {
private ReconnectServiceBlockingStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
@ -228,25 +261,27 @@ public final class ReconnectServiceGrpc {
/**
*/
public io.grpc.testing.integration.EmptyProtos.Empty start(io.grpc.testing.integration.EmptyProtos.Empty request) {
return blockingUnaryCall(
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);
}
/**
*/
public io.grpc.testing.integration.Messages.ReconnectInfo stop(io.grpc.testing.integration.EmptyProtos.Empty request) {
return blockingUnaryCall(
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getStopMethod(), getCallOptions(), request);
}
}
/**
* A stub to allow clients to do ListenableFuture-style rpc calls to service ReconnectService.
* <pre>
* A service used to control reconnect server.
* </pre>
*/
public static final class ReconnectServiceFutureStub extends io.grpc.stub.AbstractFutureStub<ReconnectServiceFutureStub> {
public static final class ReconnectServiceFutureStub
extends io.grpc.stub.AbstractFutureStub<ReconnectServiceFutureStub> {
private ReconnectServiceFutureStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
@ -261,8 +296,8 @@ public final class ReconnectServiceGrpc {
/**
*/
public com.google.common.util.concurrent.ListenableFuture<io.grpc.testing.integration.EmptyProtos.Empty> start(
io.grpc.testing.integration.EmptyProtos.Empty request) {
return futureUnaryCall(
io.grpc.testing.integration.Messages.ReconnectParams request) {
return io.grpc.stub.ClientCalls.futureUnaryCall(
getChannel().newCall(getStartMethod(), getCallOptions()), request);
}
@ -270,7 +305,7 @@ public final class ReconnectServiceGrpc {
*/
public com.google.common.util.concurrent.ListenableFuture<io.grpc.testing.integration.Messages.ReconnectInfo> stop(
io.grpc.testing.integration.EmptyProtos.Empty request) {
return futureUnaryCall(
return io.grpc.stub.ClientCalls.futureUnaryCall(
getChannel().newCall(getStopMethod(), getCallOptions()), request);
}
}
@ -283,10 +318,10 @@ public final class ReconnectServiceGrpc {
io.grpc.stub.ServerCalls.ServerStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.ClientStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.BidiStreamingMethod<Req, Resp> {
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;
}
@ -296,7 +331,7 @@ public final class ReconnectServiceGrpc {
public void invoke(Req request, io.grpc.stub.StreamObserver<Resp> 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<io.grpc.testing.integration.EmptyProtos.Empty>) responseObserver);
break;
case METHODID_STOP:
@ -319,6 +354,25 @@ public final class ReconnectServiceGrpc {
}
}
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() {

View File

@ -1,19 +1,6 @@
package io.grpc.testing.integration;
import static io.grpc.MethodDescriptor.generateFullMethodName;
import static io.grpc.stub.ClientCalls.asyncBidiStreamingCall;
import static io.grpc.stub.ClientCalls.asyncClientStreamingCall;
import static io.grpc.stub.ClientCalls.asyncServerStreamingCall;
import static io.grpc.stub.ClientCalls.asyncUnaryCall;
import static io.grpc.stub.ClientCalls.blockingServerStreamingCall;
import static io.grpc.stub.ClientCalls.blockingUnaryCall;
import static io.grpc.stub.ClientCalls.futureUnaryCall;
import static io.grpc.stub.ServerCalls.asyncBidiStreamingCall;
import static io.grpc.stub.ServerCalls.asyncClientStreamingCall;
import static io.grpc.stub.ServerCalls.asyncServerStreamingCall;
import static io.grpc.stub.ServerCalls.asyncUnaryCall;
import static io.grpc.stub.ServerCalls.asyncUnimplementedStreamingCall;
import static io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall;
/**
* <pre>
@ -21,14 +8,12 @@ import static io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall;
* performance with various types of payload.
* </pre>
*/
@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<io.grpc.testing.integration.EmptyProtos.Empty,
@ -285,6 +270,21 @@ public final class TestServiceGrpc {
return TestServiceStub.newStub(factory, channel);
}
/**
* Creates a new blocking-style stub that supports all types of calls on the service
*/
public static TestServiceBlockingV2Stub newBlockingV2Stub(
io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<TestServiceBlockingV2Stub> factory =
new io.grpc.stub.AbstractStub.StubFactory<TestServiceBlockingV2Stub>() {
@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
*/
@ -321,16 +321,16 @@ public final class TestServiceGrpc {
* performance with various types of payload.
* </pre>
*/
public static abstract class TestServiceImplBase implements io.grpc.BindableService {
public interface AsyncService {
/**
* <pre>
* One empty request followed by one empty response.
* </pre>
*/
public void emptyCall(io.grpc.testing.integration.EmptyProtos.Empty request,
default void emptyCall(io.grpc.testing.integration.EmptyProtos.Empty request,
io.grpc.stub.StreamObserver<io.grpc.testing.integration.EmptyProtos.Empty> responseObserver) {
asyncUnimplementedUnaryCall(getEmptyCallMethod(), responseObserver);
io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getEmptyCallMethod(), responseObserver);
}
/**
@ -338,9 +338,9 @@ public final class TestServiceGrpc {
* One request followed by one response.
* </pre>
*/
public void unaryCall(io.grpc.testing.integration.Messages.SimpleRequest request,
default void unaryCall(io.grpc.testing.integration.Messages.SimpleRequest request,
io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.SimpleResponse> responseObserver) {
asyncUnimplementedUnaryCall(getUnaryCallMethod(), responseObserver);
io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getUnaryCallMethod(), responseObserver);
}
/**
@ -350,9 +350,9 @@ public final class TestServiceGrpc {
* satisfy subsequent requests.
* </pre>
*/
public void cacheableUnaryCall(io.grpc.testing.integration.Messages.SimpleRequest request,
default void cacheableUnaryCall(io.grpc.testing.integration.Messages.SimpleRequest request,
io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.SimpleResponse> responseObserver) {
asyncUnimplementedUnaryCall(getCacheableUnaryCallMethod(), responseObserver);
io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getCacheableUnaryCallMethod(), responseObserver);
}
/**
@ -361,9 +361,9 @@ public final class TestServiceGrpc {
* The server returns the payload with client desired type and sizes.
* </pre>
*/
public void streamingOutputCall(io.grpc.testing.integration.Messages.StreamingOutputCallRequest request,
default void streamingOutputCall(io.grpc.testing.integration.Messages.StreamingOutputCallRequest request,
io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.StreamingOutputCallResponse> responseObserver) {
asyncUnimplementedUnaryCall(getStreamingOutputCallMethod(), responseObserver);
io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getStreamingOutputCallMethod(), responseObserver);
}
/**
@ -372,9 +372,9 @@ public final class TestServiceGrpc {
* The server returns the aggregated size of client payload as the result.
* </pre>
*/
public io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.StreamingInputCallRequest> streamingInputCall(
default io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.StreamingInputCallRequest> streamingInputCall(
io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.StreamingInputCallResponse> responseObserver) {
return asyncUnimplementedStreamingCall(getStreamingInputCallMethod(), responseObserver);
return io.grpc.stub.ServerCalls.asyncUnimplementedStreamingCall(getStreamingInputCallMethod(), responseObserver);
}
/**
@ -384,9 +384,9 @@ public final class TestServiceGrpc {
* demonstrates the idea of full duplexing.
* </pre>
*/
public io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.StreamingOutputCallRequest> fullDuplexCall(
default io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.StreamingOutputCallRequest> fullDuplexCall(
io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.StreamingOutputCallResponse> responseObserver) {
return asyncUnimplementedStreamingCall(getFullDuplexCallMethod(), responseObserver);
return io.grpc.stub.ServerCalls.asyncUnimplementedStreamingCall(getFullDuplexCallMethod(), responseObserver);
}
/**
@ -397,9 +397,9 @@ public final class TestServiceGrpc {
* first request.
* </pre>
*/
public io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.StreamingOutputCallRequest> halfDuplexCall(
default io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.StreamingOutputCallRequest> halfDuplexCall(
io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.StreamingOutputCallResponse> responseObserver) {
return asyncUnimplementedStreamingCall(getHalfDuplexCallMethod(), responseObserver);
return io.grpc.stub.ServerCalls.asyncUnimplementedStreamingCall(getHalfDuplexCallMethod(), responseObserver);
}
/**
@ -408,80 +408,36 @@ public final class TestServiceGrpc {
* to test the behavior when clients call unimplemented methods.
* </pre>
*/
public void unimplementedCall(io.grpc.testing.integration.EmptyProtos.Empty request,
default void unimplementedCall(io.grpc.testing.integration.EmptyProtos.Empty request,
io.grpc.stub.StreamObserver<io.grpc.testing.integration.EmptyProtos.Empty> responseObserver) {
asyncUnimplementedUnaryCall(getUnimplementedCallMethod(), responseObserver);
}
@java.lang.Override public final io.grpc.ServerServiceDefinition bindService() {
return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor())
.addMethod(
getEmptyCallMethod(),
asyncUnaryCall(
new MethodHandlers<
io.grpc.testing.integration.EmptyProtos.Empty,
io.grpc.testing.integration.EmptyProtos.Empty>(
this, METHODID_EMPTY_CALL)))
.addMethod(
getUnaryCallMethod(),
asyncUnaryCall(
new MethodHandlers<
io.grpc.testing.integration.Messages.SimpleRequest,
io.grpc.testing.integration.Messages.SimpleResponse>(
this, METHODID_UNARY_CALL)))
.addMethod(
getCacheableUnaryCallMethod(),
asyncUnaryCall(
new MethodHandlers<
io.grpc.testing.integration.Messages.SimpleRequest,
io.grpc.testing.integration.Messages.SimpleResponse>(
this, METHODID_CACHEABLE_UNARY_CALL)))
.addMethod(
getStreamingOutputCallMethod(),
asyncServerStreamingCall(
new MethodHandlers<
io.grpc.testing.integration.Messages.StreamingOutputCallRequest,
io.grpc.testing.integration.Messages.StreamingOutputCallResponse>(
this, METHODID_STREAMING_OUTPUT_CALL)))
.addMethod(
getStreamingInputCallMethod(),
asyncClientStreamingCall(
new MethodHandlers<
io.grpc.testing.integration.Messages.StreamingInputCallRequest,
io.grpc.testing.integration.Messages.StreamingInputCallResponse>(
this, METHODID_STREAMING_INPUT_CALL)))
.addMethod(
getFullDuplexCallMethod(),
asyncBidiStreamingCall(
new MethodHandlers<
io.grpc.testing.integration.Messages.StreamingOutputCallRequest,
io.grpc.testing.integration.Messages.StreamingOutputCallResponse>(
this, METHODID_FULL_DUPLEX_CALL)))
.addMethod(
getHalfDuplexCallMethod(),
asyncBidiStreamingCall(
new MethodHandlers<
io.grpc.testing.integration.Messages.StreamingOutputCallRequest,
io.grpc.testing.integration.Messages.StreamingOutputCallResponse>(
this, METHODID_HALF_DUPLEX_CALL)))
.addMethod(
getUnimplementedCallMethod(),
asyncUnaryCall(
new MethodHandlers<
io.grpc.testing.integration.EmptyProtos.Empty,
io.grpc.testing.integration.EmptyProtos.Empty>(
this, METHODID_UNIMPLEMENTED_CALL)))
.build();
io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getUnimplementedCallMethod(), responseObserver);
}
}
/**
* Base class for the server implementation of the service TestService.
* <pre>
* A simple service to test the various types of RPCs and experiment with
* performance with various types of payload.
* </pre>
*/
public static final class TestServiceStub extends io.grpc.stub.AbstractAsyncStub<TestServiceStub> {
public static abstract class TestServiceImplBase
implements io.grpc.BindableService, AsyncService {
@java.lang.Override public final io.grpc.ServerServiceDefinition bindService() {
return TestServiceGrpc.bindService(this);
}
}
/**
* A stub to allow clients to do asynchronous rpc calls to service TestService.
* <pre>
* A simple service to test the various types of RPCs and experiment with
* performance with various types of payload.
* </pre>
*/
public static final class TestServiceStub
extends io.grpc.stub.AbstractAsyncStub<TestServiceStub> {
private TestServiceStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
@ -500,7 +456,7 @@ public final class TestServiceGrpc {
*/
public void emptyCall(io.grpc.testing.integration.EmptyProtos.Empty request,
io.grpc.stub.StreamObserver<io.grpc.testing.integration.EmptyProtos.Empty> responseObserver) {
asyncUnaryCall(
io.grpc.stub.ClientCalls.asyncUnaryCall(
getChannel().newCall(getEmptyCallMethod(), getCallOptions()), request, responseObserver);
}
@ -511,7 +467,7 @@ public final class TestServiceGrpc {
*/
public void unaryCall(io.grpc.testing.integration.Messages.SimpleRequest request,
io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.SimpleResponse> responseObserver) {
asyncUnaryCall(
io.grpc.stub.ClientCalls.asyncUnaryCall(
getChannel().newCall(getUnaryCallMethod(), getCallOptions()), request, responseObserver);
}
@ -524,7 +480,7 @@ public final class TestServiceGrpc {
*/
public void cacheableUnaryCall(io.grpc.testing.integration.Messages.SimpleRequest request,
io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.SimpleResponse> responseObserver) {
asyncUnaryCall(
io.grpc.stub.ClientCalls.asyncUnaryCall(
getChannel().newCall(getCacheableUnaryCallMethod(), getCallOptions()), request, responseObserver);
}
@ -536,7 +492,7 @@ public final class TestServiceGrpc {
*/
public void streamingOutputCall(io.grpc.testing.integration.Messages.StreamingOutputCallRequest request,
io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.StreamingOutputCallResponse> responseObserver) {
asyncServerStreamingCall(
io.grpc.stub.ClientCalls.asyncServerStreamingCall(
getChannel().newCall(getStreamingOutputCallMethod(), getCallOptions()), request, responseObserver);
}
@ -548,7 +504,7 @@ public final class TestServiceGrpc {
*/
public io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.StreamingInputCallRequest> streamingInputCall(
io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.StreamingInputCallResponse> responseObserver) {
return asyncClientStreamingCall(
return io.grpc.stub.ClientCalls.asyncClientStreamingCall(
getChannel().newCall(getStreamingInputCallMethod(), getCallOptions()), responseObserver);
}
@ -561,7 +517,7 @@ public final class TestServiceGrpc {
*/
public io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.StreamingOutputCallRequest> fullDuplexCall(
io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.StreamingOutputCallResponse> responseObserver) {
return asyncBidiStreamingCall(
return io.grpc.stub.ClientCalls.asyncBidiStreamingCall(
getChannel().newCall(getFullDuplexCallMethod(), getCallOptions()), responseObserver);
}
@ -575,7 +531,7 @@ public final class TestServiceGrpc {
*/
public io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.StreamingOutputCallRequest> halfDuplexCall(
io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.StreamingOutputCallResponse> responseObserver) {
return asyncBidiStreamingCall(
return io.grpc.stub.ClientCalls.asyncBidiStreamingCall(
getChannel().newCall(getHalfDuplexCallMethod(), getCallOptions()), responseObserver);
}
@ -587,18 +543,139 @@ public final class TestServiceGrpc {
*/
public void unimplementedCall(io.grpc.testing.integration.EmptyProtos.Empty request,
io.grpc.stub.StreamObserver<io.grpc.testing.integration.EmptyProtos.Empty> responseObserver) {
asyncUnaryCall(
io.grpc.stub.ClientCalls.asyncUnaryCall(
getChannel().newCall(getUnimplementedCallMethod(), getCallOptions()), request, responseObserver);
}
}
/**
* A stub to allow clients to do synchronous rpc calls to service TestService.
* <pre>
* A simple service to test the various types of RPCs and experiment with
* performance with various types of payload.
* </pre>
*/
public static final class TestServiceBlockingStub extends io.grpc.stub.AbstractBlockingStub<TestServiceBlockingStub> {
public static final class TestServiceBlockingV2Stub
extends io.grpc.stub.AbstractBlockingStub<TestServiceBlockingV2Stub> {
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);
}
/**
* <pre>
* One empty request followed by one empty response.
* </pre>
*/
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);
}
/**
* <pre>
* One request followed by one response.
* </pre>
*/
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);
}
/**
* <pre>
* 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.
* </pre>
*/
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);
}
/**
* <pre>
* One request followed by a sequence of responses (streamed download).
* The server returns the payload with client desired type and sizes.
* </pre>
*/
@io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/10918")
public io.grpc.stub.BlockingClientCall<?, io.grpc.testing.integration.Messages.StreamingOutputCallResponse>
streamingOutputCall(io.grpc.testing.integration.Messages.StreamingOutputCallRequest request) {
return io.grpc.stub.ClientCalls.blockingV2ServerStreamingCall(
getChannel(), getStreamingOutputCallMethod(), getCallOptions(), request);
}
/**
* <pre>
* A sequence of requests followed by one response (streamed upload).
* The server returns the aggregated size of client payload as the result.
* </pre>
*/
@io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/10918")
public io.grpc.stub.BlockingClientCall<io.grpc.testing.integration.Messages.StreamingInputCallRequest, io.grpc.testing.integration.Messages.StreamingInputCallResponse>
streamingInputCall() {
return io.grpc.stub.ClientCalls.blockingClientStreamingCall(
getChannel(), getStreamingInputCallMethod(), getCallOptions());
}
/**
* <pre>
* 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.
* </pre>
*/
@io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/10918")
public io.grpc.stub.BlockingClientCall<io.grpc.testing.integration.Messages.StreamingOutputCallRequest, io.grpc.testing.integration.Messages.StreamingOutputCallResponse>
fullDuplexCall() {
return io.grpc.stub.ClientCalls.blockingBidiStreamingCall(
getChannel(), getFullDuplexCallMethod(), getCallOptions());
}
/**
* <pre>
* 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.
* </pre>
*/
@io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/10918")
public io.grpc.stub.BlockingClientCall<io.grpc.testing.integration.Messages.StreamingOutputCallRequest, io.grpc.testing.integration.Messages.StreamingOutputCallResponse>
halfDuplexCall() {
return io.grpc.stub.ClientCalls.blockingBidiStreamingCall(
getChannel(), getHalfDuplexCallMethod(), getCallOptions());
}
/**
* <pre>
* The test server will not implement this method. It will be used
* to test the behavior when clients call unimplemented methods.
* </pre>
*/
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.
* <pre>
* A simple service to test the various types of RPCs and experiment with
* performance with various types of payload.
* </pre>
*/
public static final class TestServiceBlockingStub
extends io.grpc.stub.AbstractBlockingStub<TestServiceBlockingStub> {
private TestServiceBlockingStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
@ -616,7 +693,7 @@ public final class TestServiceGrpc {
* </pre>
*/
public io.grpc.testing.integration.EmptyProtos.Empty emptyCall(io.grpc.testing.integration.EmptyProtos.Empty request) {
return blockingUnaryCall(
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getEmptyCallMethod(), getCallOptions(), request);
}
@ -626,7 +703,7 @@ public final class TestServiceGrpc {
* </pre>
*/
public io.grpc.testing.integration.Messages.SimpleResponse unaryCall(io.grpc.testing.integration.Messages.SimpleRequest request) {
return blockingUnaryCall(
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getUnaryCallMethod(), getCallOptions(), request);
}
@ -638,7 +715,7 @@ public final class TestServiceGrpc {
* </pre>
*/
public io.grpc.testing.integration.Messages.SimpleResponse cacheableUnaryCall(io.grpc.testing.integration.Messages.SimpleRequest request) {
return blockingUnaryCall(
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getCacheableUnaryCallMethod(), getCallOptions(), request);
}
@ -650,7 +727,7 @@ public final class TestServiceGrpc {
*/
public java.util.Iterator<io.grpc.testing.integration.Messages.StreamingOutputCallResponse> streamingOutputCall(
io.grpc.testing.integration.Messages.StreamingOutputCallRequest request) {
return blockingServerStreamingCall(
return io.grpc.stub.ClientCalls.blockingServerStreamingCall(
getChannel(), getStreamingOutputCallMethod(), getCallOptions(), request);
}
@ -661,18 +738,20 @@ public final class TestServiceGrpc {
* </pre>
*/
public io.grpc.testing.integration.EmptyProtos.Empty unimplementedCall(io.grpc.testing.integration.EmptyProtos.Empty request) {
return blockingUnaryCall(
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getUnimplementedCallMethod(), getCallOptions(), request);
}
}
/**
* A stub to allow clients to do ListenableFuture-style rpc calls to service TestService.
* <pre>
* A simple service to test the various types of RPCs and experiment with
* performance with various types of payload.
* </pre>
*/
public static final class TestServiceFutureStub extends io.grpc.stub.AbstractFutureStub<TestServiceFutureStub> {
public static final class TestServiceFutureStub
extends io.grpc.stub.AbstractFutureStub<TestServiceFutureStub> {
private TestServiceFutureStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
@ -691,7 +770,7 @@ public final class TestServiceGrpc {
*/
public com.google.common.util.concurrent.ListenableFuture<io.grpc.testing.integration.EmptyProtos.Empty> emptyCall(
io.grpc.testing.integration.EmptyProtos.Empty request) {
return futureUnaryCall(
return io.grpc.stub.ClientCalls.futureUnaryCall(
getChannel().newCall(getEmptyCallMethod(), getCallOptions()), request);
}
@ -702,7 +781,7 @@ public final class TestServiceGrpc {
*/
public com.google.common.util.concurrent.ListenableFuture<io.grpc.testing.integration.Messages.SimpleResponse> unaryCall(
io.grpc.testing.integration.Messages.SimpleRequest request) {
return futureUnaryCall(
return io.grpc.stub.ClientCalls.futureUnaryCall(
getChannel().newCall(getUnaryCallMethod(), getCallOptions()), request);
}
@ -715,7 +794,7 @@ public final class TestServiceGrpc {
*/
public com.google.common.util.concurrent.ListenableFuture<io.grpc.testing.integration.Messages.SimpleResponse> cacheableUnaryCall(
io.grpc.testing.integration.Messages.SimpleRequest request) {
return futureUnaryCall(
return io.grpc.stub.ClientCalls.futureUnaryCall(
getChannel().newCall(getCacheableUnaryCallMethod(), getCallOptions()), request);
}
@ -727,7 +806,7 @@ public final class TestServiceGrpc {
*/
public com.google.common.util.concurrent.ListenableFuture<io.grpc.testing.integration.EmptyProtos.Empty> unimplementedCall(
io.grpc.testing.integration.EmptyProtos.Empty request) {
return futureUnaryCall(
return io.grpc.stub.ClientCalls.futureUnaryCall(
getChannel().newCall(getUnimplementedCallMethod(), getCallOptions()), request);
}
}
@ -746,10 +825,10 @@ public final class TestServiceGrpc {
io.grpc.stub.ServerCalls.ServerStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.ClientStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.BidiStreamingMethod<Req, Resp> {
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;
}
@ -803,6 +882,67 @@ public final class TestServiceGrpc {
}
}
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() {

View File

@ -1,19 +1,6 @@
package io.grpc.testing.integration;
import static io.grpc.MethodDescriptor.generateFullMethodName;
import static io.grpc.stub.ClientCalls.asyncBidiStreamingCall;
import static io.grpc.stub.ClientCalls.asyncClientStreamingCall;
import static io.grpc.stub.ClientCalls.asyncServerStreamingCall;
import static io.grpc.stub.ClientCalls.asyncUnaryCall;
import static io.grpc.stub.ClientCalls.blockingServerStreamingCall;
import static io.grpc.stub.ClientCalls.blockingUnaryCall;
import static io.grpc.stub.ClientCalls.futureUnaryCall;
import static io.grpc.stub.ServerCalls.asyncBidiStreamingCall;
import static io.grpc.stub.ServerCalls.asyncClientStreamingCall;
import static io.grpc.stub.ServerCalls.asyncServerStreamingCall;
import static io.grpc.stub.ServerCalls.asyncUnaryCall;
import static io.grpc.stub.ServerCalls.asyncUnimplementedStreamingCall;
import static io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall;
/**
* <pre>
@ -21,14 +8,12 @@ import static io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall;
* that case.
* </pre>
*/
@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<io.grpc.testing.integration.EmptyProtos.Empty,
@ -75,6 +60,21 @@ public final class UnimplementedServiceGrpc {
return UnimplementedServiceStub.newStub(factory, channel);
}
/**
* Creates a new blocking-style stub that supports all types of calls on the service
*/
public static UnimplementedServiceBlockingV2Stub newBlockingV2Stub(
io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<UnimplementedServiceBlockingV2Stub> factory =
new io.grpc.stub.AbstractStub.StubFactory<UnimplementedServiceBlockingV2Stub>() {
@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
*/
@ -111,38 +111,43 @@ public final class UnimplementedServiceGrpc {
* that case.
* </pre>
*/
public static abstract class UnimplementedServiceImplBase implements io.grpc.BindableService {
public interface AsyncService {
/**
* <pre>
* A call that no server should implement
* </pre>
*/
public void unimplementedCall(io.grpc.testing.integration.EmptyProtos.Empty request,
default void unimplementedCall(io.grpc.testing.integration.EmptyProtos.Empty request,
io.grpc.stub.StreamObserver<io.grpc.testing.integration.EmptyProtos.Empty> responseObserver) {
asyncUnimplementedUnaryCall(getUnimplementedCallMethod(), responseObserver);
}
@java.lang.Override public final io.grpc.ServerServiceDefinition bindService() {
return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor())
.addMethod(
getUnimplementedCallMethod(),
asyncUnaryCall(
new MethodHandlers<
io.grpc.testing.integration.EmptyProtos.Empty,
io.grpc.testing.integration.EmptyProtos.Empty>(
this, METHODID_UNIMPLEMENTED_CALL)))
.build();
io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getUnimplementedCallMethod(), responseObserver);
}
}
/**
* Base class for the server implementation of the service UnimplementedService.
* <pre>
* A simple service NOT implemented at servers so clients can test for
* that case.
* </pre>
*/
public static final class UnimplementedServiceStub extends io.grpc.stub.AbstractAsyncStub<UnimplementedServiceStub> {
public static abstract class UnimplementedServiceImplBase
implements io.grpc.BindableService, AsyncService {
@java.lang.Override public final io.grpc.ServerServiceDefinition bindService() {
return UnimplementedServiceGrpc.bindService(this);
}
}
/**
* A stub to allow clients to do asynchronous rpc calls to service UnimplementedService.
* <pre>
* A simple service NOT implemented at servers so clients can test for
* that case.
* </pre>
*/
public static final class UnimplementedServiceStub
extends io.grpc.stub.AbstractAsyncStub<UnimplementedServiceStub> {
private UnimplementedServiceStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
@ -161,18 +166,51 @@ public final class UnimplementedServiceGrpc {
*/
public void unimplementedCall(io.grpc.testing.integration.EmptyProtos.Empty request,
io.grpc.stub.StreamObserver<io.grpc.testing.integration.EmptyProtos.Empty> responseObserver) {
asyncUnaryCall(
io.grpc.stub.ClientCalls.asyncUnaryCall(
getChannel().newCall(getUnimplementedCallMethod(), getCallOptions()), request, responseObserver);
}
}
/**
* A stub to allow clients to do synchronous rpc calls to service UnimplementedService.
* <pre>
* A simple service NOT implemented at servers so clients can test for
* that case.
* </pre>
*/
public static final class UnimplementedServiceBlockingStub extends io.grpc.stub.AbstractBlockingStub<UnimplementedServiceBlockingStub> {
public static final class UnimplementedServiceBlockingV2Stub
extends io.grpc.stub.AbstractBlockingStub<UnimplementedServiceBlockingV2Stub> {
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);
}
/**
* <pre>
* A call that no server should implement
* </pre>
*/
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.
* <pre>
* A simple service NOT implemented at servers so clients can test for
* that case.
* </pre>
*/
public static final class UnimplementedServiceBlockingStub
extends io.grpc.stub.AbstractBlockingStub<UnimplementedServiceBlockingStub> {
private UnimplementedServiceBlockingStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
@ -190,18 +228,20 @@ public final class UnimplementedServiceGrpc {
* </pre>
*/
public io.grpc.testing.integration.EmptyProtos.Empty unimplementedCall(io.grpc.testing.integration.EmptyProtos.Empty request) {
return blockingUnaryCall(
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getUnimplementedCallMethod(), getCallOptions(), request);
}
}
/**
* A stub to allow clients to do ListenableFuture-style rpc calls to service UnimplementedService.
* <pre>
* A simple service NOT implemented at servers so clients can test for
* that case.
* </pre>
*/
public static final class UnimplementedServiceFutureStub extends io.grpc.stub.AbstractFutureStub<UnimplementedServiceFutureStub> {
public static final class UnimplementedServiceFutureStub
extends io.grpc.stub.AbstractFutureStub<UnimplementedServiceFutureStub> {
private UnimplementedServiceFutureStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
@ -220,7 +260,7 @@ public final class UnimplementedServiceGrpc {
*/
public com.google.common.util.concurrent.ListenableFuture<io.grpc.testing.integration.EmptyProtos.Empty> unimplementedCall(
io.grpc.testing.integration.EmptyProtos.Empty request) {
return futureUnaryCall(
return io.grpc.stub.ClientCalls.futureUnaryCall(
getChannel().newCall(getUnimplementedCallMethod(), getCallOptions()), request);
}
}
@ -232,10 +272,10 @@ public final class UnimplementedServiceGrpc {
io.grpc.stub.ServerCalls.ServerStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.ClientStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.BidiStreamingMethod<Req, Resp> {
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;
}
@ -264,6 +304,18 @@ public final class UnimplementedServiceGrpc {
}
}
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() {

View File

@ -0,0 +1,328 @@
package io.grpc.testing.integration;
import static io.grpc.MethodDescriptor.generateFullMethodName;
/**
* <pre>
* A service to dynamically update the configuration of an xDS test client.
* </pre>
*/
@io.grpc.stub.annotations.GrpcGenerated
public final class XdsUpdateClientConfigureServiceGrpc {
private XdsUpdateClientConfigureServiceGrpc() {}
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<io.grpc.testing.integration.Messages.ClientConfigureRequest,
io.grpc.testing.integration.Messages.ClientConfigureResponse> getConfigureMethod;
@io.grpc.stub.annotations.RpcMethod(
fullMethodName = SERVICE_NAME + '/' + "Configure",
requestType = io.grpc.testing.integration.Messages.ClientConfigureRequest.class,
responseType = io.grpc.testing.integration.Messages.ClientConfigureResponse.class,
methodType = io.grpc.MethodDescriptor.MethodType.UNARY)
public static io.grpc.MethodDescriptor<io.grpc.testing.integration.Messages.ClientConfigureRequest,
io.grpc.testing.integration.Messages.ClientConfigureResponse> getConfigureMethod() {
io.grpc.MethodDescriptor<io.grpc.testing.integration.Messages.ClientConfigureRequest, io.grpc.testing.integration.Messages.ClientConfigureResponse> getConfigureMethod;
if ((getConfigureMethod = XdsUpdateClientConfigureServiceGrpc.getConfigureMethod) == null) {
synchronized (XdsUpdateClientConfigureServiceGrpc.class) {
if ((getConfigureMethod = XdsUpdateClientConfigureServiceGrpc.getConfigureMethod) == null) {
XdsUpdateClientConfigureServiceGrpc.getConfigureMethod = getConfigureMethod =
io.grpc.MethodDescriptor.<io.grpc.testing.integration.Messages.ClientConfigureRequest, io.grpc.testing.integration.Messages.ClientConfigureResponse>newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName(generateFullMethodName(SERVICE_NAME, "Configure"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(io.grpc.protobuf.lite.ProtoLiteUtils.marshaller(
io.grpc.testing.integration.Messages.ClientConfigureRequest.getDefaultInstance()))
.setResponseMarshaller(io.grpc.protobuf.lite.ProtoLiteUtils.marshaller(
io.grpc.testing.integration.Messages.ClientConfigureResponse.getDefaultInstance()))
.build();
}
}
}
return getConfigureMethod;
}
/**
* Creates a new async stub that supports all call types for the service
*/
public static XdsUpdateClientConfigureServiceStub newStub(io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<XdsUpdateClientConfigureServiceStub> factory =
new io.grpc.stub.AbstractStub.StubFactory<XdsUpdateClientConfigureServiceStub>() {
@java.lang.Override
public XdsUpdateClientConfigureServiceStub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new XdsUpdateClientConfigureServiceStub(channel, callOptions);
}
};
return XdsUpdateClientConfigureServiceStub.newStub(factory, channel);
}
/**
* Creates a new blocking-style stub that supports all types of calls on the service
*/
public static XdsUpdateClientConfigureServiceBlockingV2Stub newBlockingV2Stub(
io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<XdsUpdateClientConfigureServiceBlockingV2Stub> factory =
new io.grpc.stub.AbstractStub.StubFactory<XdsUpdateClientConfigureServiceBlockingV2Stub>() {
@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
*/
public static XdsUpdateClientConfigureServiceBlockingStub newBlockingStub(
io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<XdsUpdateClientConfigureServiceBlockingStub> factory =
new io.grpc.stub.AbstractStub.StubFactory<XdsUpdateClientConfigureServiceBlockingStub>() {
@java.lang.Override
public XdsUpdateClientConfigureServiceBlockingStub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new XdsUpdateClientConfigureServiceBlockingStub(channel, callOptions);
}
};
return XdsUpdateClientConfigureServiceBlockingStub.newStub(factory, channel);
}
/**
* Creates a new ListenableFuture-style stub that supports unary calls on the service
*/
public static XdsUpdateClientConfigureServiceFutureStub newFutureStub(
io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<XdsUpdateClientConfigureServiceFutureStub> factory =
new io.grpc.stub.AbstractStub.StubFactory<XdsUpdateClientConfigureServiceFutureStub>() {
@java.lang.Override
public XdsUpdateClientConfigureServiceFutureStub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new XdsUpdateClientConfigureServiceFutureStub(channel, callOptions);
}
};
return XdsUpdateClientConfigureServiceFutureStub.newStub(factory, channel);
}
/**
* <pre>
* A service to dynamically update the configuration of an xDS test client.
* </pre>
*/
public interface AsyncService {
/**
* <pre>
* Update the tes client's configuration.
* </pre>
*/
default void configure(io.grpc.testing.integration.Messages.ClientConfigureRequest request,
io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.ClientConfigureResponse> responseObserver) {
io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getConfigureMethod(), responseObserver);
}
}
/**
* Base class for the server implementation of the service XdsUpdateClientConfigureService.
* <pre>
* A service to dynamically update the configuration of an xDS test client.
* </pre>
*/
public static abstract class XdsUpdateClientConfigureServiceImplBase
implements io.grpc.BindableService, AsyncService {
@java.lang.Override public final io.grpc.ServerServiceDefinition bindService() {
return XdsUpdateClientConfigureServiceGrpc.bindService(this);
}
}
/**
* A stub to allow clients to do asynchronous rpc calls to service XdsUpdateClientConfigureService.
* <pre>
* A service to dynamically update the configuration of an xDS test client.
* </pre>
*/
public static final class XdsUpdateClientConfigureServiceStub
extends io.grpc.stub.AbstractAsyncStub<XdsUpdateClientConfigureServiceStub> {
private XdsUpdateClientConfigureServiceStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected XdsUpdateClientConfigureServiceStub build(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new XdsUpdateClientConfigureServiceStub(channel, callOptions);
}
/**
* <pre>
* Update the tes client's configuration.
* </pre>
*/
public void configure(io.grpc.testing.integration.Messages.ClientConfigureRequest request,
io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.ClientConfigureResponse> responseObserver) {
io.grpc.stub.ClientCalls.asyncUnaryCall(
getChannel().newCall(getConfigureMethod(), getCallOptions()), request, responseObserver);
}
}
/**
* A stub to allow clients to do synchronous rpc calls to service XdsUpdateClientConfigureService.
* <pre>
* A service to dynamically update the configuration of an xDS test client.
* </pre>
*/
public static final class XdsUpdateClientConfigureServiceBlockingV2Stub
extends io.grpc.stub.AbstractBlockingStub<XdsUpdateClientConfigureServiceBlockingV2Stub> {
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);
}
/**
* <pre>
* Update the tes client's configuration.
* </pre>
*/
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.
* <pre>
* A service to dynamically update the configuration of an xDS test client.
* </pre>
*/
public static final class XdsUpdateClientConfigureServiceBlockingStub
extends io.grpc.stub.AbstractBlockingStub<XdsUpdateClientConfigureServiceBlockingStub> {
private XdsUpdateClientConfigureServiceBlockingStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected XdsUpdateClientConfigureServiceBlockingStub build(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new XdsUpdateClientConfigureServiceBlockingStub(channel, callOptions);
}
/**
* <pre>
* Update the tes client's configuration.
* </pre>
*/
public io.grpc.testing.integration.Messages.ClientConfigureResponse configure(io.grpc.testing.integration.Messages.ClientConfigureRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getConfigureMethod(), getCallOptions(), request);
}
}
/**
* A stub to allow clients to do ListenableFuture-style rpc calls to service XdsUpdateClientConfigureService.
* <pre>
* A service to dynamically update the configuration of an xDS test client.
* </pre>
*/
public static final class XdsUpdateClientConfigureServiceFutureStub
extends io.grpc.stub.AbstractFutureStub<XdsUpdateClientConfigureServiceFutureStub> {
private XdsUpdateClientConfigureServiceFutureStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected XdsUpdateClientConfigureServiceFutureStub build(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new XdsUpdateClientConfigureServiceFutureStub(channel, callOptions);
}
/**
* <pre>
* Update the tes client's configuration.
* </pre>
*/
public com.google.common.util.concurrent.ListenableFuture<io.grpc.testing.integration.Messages.ClientConfigureResponse> configure(
io.grpc.testing.integration.Messages.ClientConfigureRequest request) {
return io.grpc.stub.ClientCalls.futureUnaryCall(
getChannel().newCall(getConfigureMethod(), getCallOptions()), request);
}
}
private static final int METHODID_CONFIGURE = 0;
private static final class MethodHandlers<Req, Resp> implements
io.grpc.stub.ServerCalls.UnaryMethod<Req, Resp>,
io.grpc.stub.ServerCalls.ServerStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.ClientStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.BidiStreamingMethod<Req, Resp> {
private final AsyncService serviceImpl;
private final int methodId;
MethodHandlers(AsyncService serviceImpl, int methodId) {
this.serviceImpl = serviceImpl;
this.methodId = methodId;
}
@java.lang.Override
@java.lang.SuppressWarnings("unchecked")
public void invoke(Req request, io.grpc.stub.StreamObserver<Resp> responseObserver) {
switch (methodId) {
case METHODID_CONFIGURE:
serviceImpl.configure((io.grpc.testing.integration.Messages.ClientConfigureRequest) request,
(io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.ClientConfigureResponse>) responseObserver);
break;
default:
throw new AssertionError();
}
}
@java.lang.Override
@java.lang.SuppressWarnings("unchecked")
public io.grpc.stub.StreamObserver<Req> invoke(
io.grpc.stub.StreamObserver<Resp> responseObserver) {
switch (methodId) {
default:
throw new AssertionError();
}
}
}
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() {
io.grpc.ServiceDescriptor result = serviceDescriptor;
if (result == null) {
synchronized (XdsUpdateClientConfigureServiceGrpc.class) {
result = serviceDescriptor;
if (result == null) {
serviceDescriptor = result = io.grpc.ServiceDescriptor.newBuilder(SERVICE_NAME)
.addMethod(getConfigureMethod())
.build();
}
}
}
return result;
}
}

View File

@ -0,0 +1,393 @@
package io.grpc.testing.integration;
import static io.grpc.MethodDescriptor.generateFullMethodName;
/**
* <pre>
* A service to remotely control health status of an xDS test server.
* </pre>
*/
@io.grpc.stub.annotations.GrpcGenerated
public final class XdsUpdateHealthServiceGrpc {
private XdsUpdateHealthServiceGrpc() {}
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<io.grpc.testing.integration.EmptyProtos.Empty,
io.grpc.testing.integration.EmptyProtos.Empty> getSetServingMethod;
@io.grpc.stub.annotations.RpcMethod(
fullMethodName = SERVICE_NAME + '/' + "SetServing",
requestType = io.grpc.testing.integration.EmptyProtos.Empty.class,
responseType = io.grpc.testing.integration.EmptyProtos.Empty.class,
methodType = io.grpc.MethodDescriptor.MethodType.UNARY)
public static io.grpc.MethodDescriptor<io.grpc.testing.integration.EmptyProtos.Empty,
io.grpc.testing.integration.EmptyProtos.Empty> getSetServingMethod() {
io.grpc.MethodDescriptor<io.grpc.testing.integration.EmptyProtos.Empty, io.grpc.testing.integration.EmptyProtos.Empty> getSetServingMethod;
if ((getSetServingMethod = XdsUpdateHealthServiceGrpc.getSetServingMethod) == null) {
synchronized (XdsUpdateHealthServiceGrpc.class) {
if ((getSetServingMethod = XdsUpdateHealthServiceGrpc.getSetServingMethod) == null) {
XdsUpdateHealthServiceGrpc.getSetServingMethod = getSetServingMethod =
io.grpc.MethodDescriptor.<io.grpc.testing.integration.EmptyProtos.Empty, io.grpc.testing.integration.EmptyProtos.Empty>newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName(generateFullMethodName(SERVICE_NAME, "SetServing"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(io.grpc.protobuf.lite.ProtoLiteUtils.marshaller(
io.grpc.testing.integration.EmptyProtos.Empty.getDefaultInstance()))
.setResponseMarshaller(io.grpc.protobuf.lite.ProtoLiteUtils.marshaller(
io.grpc.testing.integration.EmptyProtos.Empty.getDefaultInstance()))
.build();
}
}
}
return getSetServingMethod;
}
private static volatile io.grpc.MethodDescriptor<io.grpc.testing.integration.EmptyProtos.Empty,
io.grpc.testing.integration.EmptyProtos.Empty> getSetNotServingMethod;
@io.grpc.stub.annotations.RpcMethod(
fullMethodName = SERVICE_NAME + '/' + "SetNotServing",
requestType = io.grpc.testing.integration.EmptyProtos.Empty.class,
responseType = io.grpc.testing.integration.EmptyProtos.Empty.class,
methodType = io.grpc.MethodDescriptor.MethodType.UNARY)
public static io.grpc.MethodDescriptor<io.grpc.testing.integration.EmptyProtos.Empty,
io.grpc.testing.integration.EmptyProtos.Empty> getSetNotServingMethod() {
io.grpc.MethodDescriptor<io.grpc.testing.integration.EmptyProtos.Empty, io.grpc.testing.integration.EmptyProtos.Empty> getSetNotServingMethod;
if ((getSetNotServingMethod = XdsUpdateHealthServiceGrpc.getSetNotServingMethod) == null) {
synchronized (XdsUpdateHealthServiceGrpc.class) {
if ((getSetNotServingMethod = XdsUpdateHealthServiceGrpc.getSetNotServingMethod) == null) {
XdsUpdateHealthServiceGrpc.getSetNotServingMethod = getSetNotServingMethod =
io.grpc.MethodDescriptor.<io.grpc.testing.integration.EmptyProtos.Empty, io.grpc.testing.integration.EmptyProtos.Empty>newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName(generateFullMethodName(SERVICE_NAME, "SetNotServing"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(io.grpc.protobuf.lite.ProtoLiteUtils.marshaller(
io.grpc.testing.integration.EmptyProtos.Empty.getDefaultInstance()))
.setResponseMarshaller(io.grpc.protobuf.lite.ProtoLiteUtils.marshaller(
io.grpc.testing.integration.EmptyProtos.Empty.getDefaultInstance()))
.build();
}
}
}
return getSetNotServingMethod;
}
/**
* Creates a new async stub that supports all call types for the service
*/
public static XdsUpdateHealthServiceStub newStub(io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<XdsUpdateHealthServiceStub> factory =
new io.grpc.stub.AbstractStub.StubFactory<XdsUpdateHealthServiceStub>() {
@java.lang.Override
public XdsUpdateHealthServiceStub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new XdsUpdateHealthServiceStub(channel, callOptions);
}
};
return XdsUpdateHealthServiceStub.newStub(factory, channel);
}
/**
* Creates a new blocking-style stub that supports all types of calls on the service
*/
public static XdsUpdateHealthServiceBlockingV2Stub newBlockingV2Stub(
io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<XdsUpdateHealthServiceBlockingV2Stub> factory =
new io.grpc.stub.AbstractStub.StubFactory<XdsUpdateHealthServiceBlockingV2Stub>() {
@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
*/
public static XdsUpdateHealthServiceBlockingStub newBlockingStub(
io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<XdsUpdateHealthServiceBlockingStub> factory =
new io.grpc.stub.AbstractStub.StubFactory<XdsUpdateHealthServiceBlockingStub>() {
@java.lang.Override
public XdsUpdateHealthServiceBlockingStub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new XdsUpdateHealthServiceBlockingStub(channel, callOptions);
}
};
return XdsUpdateHealthServiceBlockingStub.newStub(factory, channel);
}
/**
* Creates a new ListenableFuture-style stub that supports unary calls on the service
*/
public static XdsUpdateHealthServiceFutureStub newFutureStub(
io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<XdsUpdateHealthServiceFutureStub> factory =
new io.grpc.stub.AbstractStub.StubFactory<XdsUpdateHealthServiceFutureStub>() {
@java.lang.Override
public XdsUpdateHealthServiceFutureStub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new XdsUpdateHealthServiceFutureStub(channel, callOptions);
}
};
return XdsUpdateHealthServiceFutureStub.newStub(factory, channel);
}
/**
* <pre>
* A service to remotely control health status of an xDS test server.
* </pre>
*/
public interface AsyncService {
/**
*/
default void setServing(io.grpc.testing.integration.EmptyProtos.Empty request,
io.grpc.stub.StreamObserver<io.grpc.testing.integration.EmptyProtos.Empty> responseObserver) {
io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getSetServingMethod(), responseObserver);
}
/**
*/
default void setNotServing(io.grpc.testing.integration.EmptyProtos.Empty request,
io.grpc.stub.StreamObserver<io.grpc.testing.integration.EmptyProtos.Empty> responseObserver) {
io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getSetNotServingMethod(), responseObserver);
}
}
/**
* Base class for the server implementation of the service XdsUpdateHealthService.
* <pre>
* A service to remotely control health status of an xDS test server.
* </pre>
*/
public static abstract class XdsUpdateHealthServiceImplBase
implements io.grpc.BindableService, AsyncService {
@java.lang.Override public final io.grpc.ServerServiceDefinition bindService() {
return XdsUpdateHealthServiceGrpc.bindService(this);
}
}
/**
* A stub to allow clients to do asynchronous rpc calls to service XdsUpdateHealthService.
* <pre>
* A service to remotely control health status of an xDS test server.
* </pre>
*/
public static final class XdsUpdateHealthServiceStub
extends io.grpc.stub.AbstractAsyncStub<XdsUpdateHealthServiceStub> {
private XdsUpdateHealthServiceStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected XdsUpdateHealthServiceStub build(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new XdsUpdateHealthServiceStub(channel, callOptions);
}
/**
*/
public void setServing(io.grpc.testing.integration.EmptyProtos.Empty request,
io.grpc.stub.StreamObserver<io.grpc.testing.integration.EmptyProtos.Empty> responseObserver) {
io.grpc.stub.ClientCalls.asyncUnaryCall(
getChannel().newCall(getSetServingMethod(), getCallOptions()), request, responseObserver);
}
/**
*/
public void setNotServing(io.grpc.testing.integration.EmptyProtos.Empty request,
io.grpc.stub.StreamObserver<io.grpc.testing.integration.EmptyProtos.Empty> responseObserver) {
io.grpc.stub.ClientCalls.asyncUnaryCall(
getChannel().newCall(getSetNotServingMethod(), getCallOptions()), request, responseObserver);
}
}
/**
* A stub to allow clients to do synchronous rpc calls to service XdsUpdateHealthService.
* <pre>
* A service to remotely control health status of an xDS test server.
* </pre>
*/
public static final class XdsUpdateHealthServiceBlockingV2Stub
extends io.grpc.stub.AbstractBlockingStub<XdsUpdateHealthServiceBlockingV2Stub> {
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.
* <pre>
* A service to remotely control health status of an xDS test server.
* </pre>
*/
public static final class XdsUpdateHealthServiceBlockingStub
extends io.grpc.stub.AbstractBlockingStub<XdsUpdateHealthServiceBlockingStub> {
private XdsUpdateHealthServiceBlockingStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected XdsUpdateHealthServiceBlockingStub build(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new XdsUpdateHealthServiceBlockingStub(channel, callOptions);
}
/**
*/
public io.grpc.testing.integration.EmptyProtos.Empty setServing(io.grpc.testing.integration.EmptyProtos.Empty request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getSetServingMethod(), getCallOptions(), request);
}
/**
*/
public io.grpc.testing.integration.EmptyProtos.Empty setNotServing(io.grpc.testing.integration.EmptyProtos.Empty request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getSetNotServingMethod(), getCallOptions(), request);
}
}
/**
* A stub to allow clients to do ListenableFuture-style rpc calls to service XdsUpdateHealthService.
* <pre>
* A service to remotely control health status of an xDS test server.
* </pre>
*/
public static final class XdsUpdateHealthServiceFutureStub
extends io.grpc.stub.AbstractFutureStub<XdsUpdateHealthServiceFutureStub> {
private XdsUpdateHealthServiceFutureStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected XdsUpdateHealthServiceFutureStub build(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new XdsUpdateHealthServiceFutureStub(channel, callOptions);
}
/**
*/
public com.google.common.util.concurrent.ListenableFuture<io.grpc.testing.integration.EmptyProtos.Empty> setServing(
io.grpc.testing.integration.EmptyProtos.Empty request) {
return io.grpc.stub.ClientCalls.futureUnaryCall(
getChannel().newCall(getSetServingMethod(), getCallOptions()), request);
}
/**
*/
public com.google.common.util.concurrent.ListenableFuture<io.grpc.testing.integration.EmptyProtos.Empty> setNotServing(
io.grpc.testing.integration.EmptyProtos.Empty request) {
return io.grpc.stub.ClientCalls.futureUnaryCall(
getChannel().newCall(getSetNotServingMethod(), getCallOptions()), request);
}
}
private static final int METHODID_SET_SERVING = 0;
private static final int METHODID_SET_NOT_SERVING = 1;
private static final class MethodHandlers<Req, Resp> implements
io.grpc.stub.ServerCalls.UnaryMethod<Req, Resp>,
io.grpc.stub.ServerCalls.ServerStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.ClientStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.BidiStreamingMethod<Req, Resp> {
private final AsyncService serviceImpl;
private final int methodId;
MethodHandlers(AsyncService serviceImpl, int methodId) {
this.serviceImpl = serviceImpl;
this.methodId = methodId;
}
@java.lang.Override
@java.lang.SuppressWarnings("unchecked")
public void invoke(Req request, io.grpc.stub.StreamObserver<Resp> responseObserver) {
switch (methodId) {
case METHODID_SET_SERVING:
serviceImpl.setServing((io.grpc.testing.integration.EmptyProtos.Empty) request,
(io.grpc.stub.StreamObserver<io.grpc.testing.integration.EmptyProtos.Empty>) responseObserver);
break;
case METHODID_SET_NOT_SERVING:
serviceImpl.setNotServing((io.grpc.testing.integration.EmptyProtos.Empty) request,
(io.grpc.stub.StreamObserver<io.grpc.testing.integration.EmptyProtos.Empty>) responseObserver);
break;
default:
throw new AssertionError();
}
}
@java.lang.Override
@java.lang.SuppressWarnings("unchecked")
public io.grpc.stub.StreamObserver<Req> invoke(
io.grpc.stub.StreamObserver<Resp> responseObserver) {
switch (methodId) {
default:
throw new AssertionError();
}
}
}
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() {
io.grpc.ServiceDescriptor result = serviceDescriptor;
if (result == null) {
synchronized (XdsUpdateHealthServiceGrpc.class) {
result = serviceDescriptor;
if (result == null) {
serviceDescriptor = result = io.grpc.ServiceDescriptor.newBuilder(SERVICE_NAME)
.addMethod(getSetServingMethod())
.addMethod(getSetNotServingMethod())
.build();
}
}
}
return result;
}
}

View File

@ -1,17 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="io.grpc.android.integrationtest" >
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.INTERNET" />
<!-- For UDS -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-sdk tools:overrideLibrary="io.grpc.android"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/Base.V7.Theme.AppCompat.Light"
android:name="android.support.multidex.MultiDexApplication" >
android:name="androidx.multidex.MultiDexApplication">
<activity
android:name=".TesterActivity"
android:exported="true"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
@ -19,6 +24,9 @@
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- To support tests under binder, which need Android services -->
<service android:name="io.grpc.binder.HostServices$HostService1"/>
<service android:name="io.grpc.binder.HostServices$HostService2"/>
</application>
</manifest>

View File

@ -1,5 +1,5 @@
/*
* Copyright 2018 The gRPC Authors
* 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.
@ -16,49 +16,36 @@
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 java.util.concurrent.Callable;
import org.junit.AssumptionViolatedException;
/** AsyncTask for interop test cases. */
final class InteropTask extends AsyncTask<Void, Void, String> {
/**
* Used to run a single test case against a channel in a separate thread.
*/
public class TestCallable implements Callable<String> {
private final ManagedChannel channel;
private final String testCase;
private static final String LOG_TAG = "GrpcInteropTask";
interface Listener {
void onComplete(String result);
}
static final String SUCCESS_MESSAGE = "Success!";
private final WeakReference<Listener> listenerReference;
private final String testCase;
private final Tester tester;
InteropTask(
Listener listener,
ManagedChannel channel,
String testCase) {
this.listenerReference = new WeakReference<Listener>(listener);
public TestCallable(ManagedChannel channel, String testCase) {
this.channel = channel;
this.testCase = testCase;
this.tester = new Tester(channel);
}
@Override
protected void onPreExecute() {
public String call() {
Tester tester = new Tester(channel);
tester.setUp();
}
@SuppressWarnings("Finally")
@Override
protected String doInBackground(Void... ignored) {
try {
runTest(testCase);
runTest(tester, testCase);
return SUCCESS_MESSAGE;
} catch (Throwable t) {
// Print the stack trace to logcat.
@ -78,7 +65,7 @@ final class InteropTask extends AsyncTask<Void, Void, String> {
}
}
private void runTest(String testCase) throws Exception {
private void runTest(Tester tester, String testCase) throws Exception {
Log.i(LOG_TAG, "Running test case: " + testCase);
if ("empty_unary".equals(testCase)) {
tester.emptyUnary();
@ -138,14 +125,6 @@ final class InteropTask extends AsyncTask<Void, Void, String> {
}
}
@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) {

View File

@ -18,8 +18,8 @@ package io.grpc.android.integrationtest;
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.Button;
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<Button> buttons;
private EditText hostEdit;
private EditText portEdit;
private CheckBox useUdsCheckBox;
private EditText udsEdit;
private TextView resultText;
private CheckBox testCertCheckBox;
private UdsTcpEndpointConnector endpointConnector;
private ExecutorService executor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@ -57,12 +69,26 @@ public class TesterActivity extends AppCompatActivity
hostEdit = (EditText) findViewById(R.id.host_edit_text);
portEdit = (EditText) findViewById(R.id.port_edit_text);
useUdsCheckBox = (CheckBox) findViewById(R.id.use_uds_checkbox);
udsEdit = (EditText) findViewById(R.id.uds_proxy_edit_text);
resultText = (TextView) findViewById(R.id.grpc_response_text);
testCertCheckBox = (CheckBox) findViewById(R.id.test_cert_checkbox);
ProviderInstaller.installIfNeededAsync(this, this);
// Disable buttons until the security provider installing finishes.
enableButtons(false);
executor = Executors.newSingleThreadExecutor();
}
/** Click handler for unix domain socket. */
public void enableUds(View view) {
boolean enabled = ((CheckBox) view).isChecked();
udsEdit.setEnabled(enabled);
testCertCheckBox.setEnabled(!enabled);
if (enabled) {
testCertCheckBox.setChecked(false);
}
}
public void startEmptyUnary(View view) {
@ -91,12 +117,6 @@ public class TesterActivity extends AppCompatActivity
}
}
@Override
public void onComplete(String result) {
resultText.setText(result);
enableButtons(true);
}
private void startTest(String testCase) {
((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(
hostEdit.getWindowToken(), 0);
@ -106,6 +126,9 @@ public class TesterActivity extends AppCompatActivity
String host = hostEdit.getText().toString();
String portStr = portEdit.getText().toString();
int port = TextUtils.isEmpty(portStr) ? 8080 : Integer.valueOf(portStr);
boolean udsEnabled = useUdsCheckBox.isChecked();
String udsPath =
TextUtils.isEmpty(udsEdit.getText()) ? "default" : udsEdit.getText().toString();
String serverHostOverride;
InputStream testCert;
@ -116,10 +139,39 @@ public class TesterActivity extends AppCompatActivity
serverHostOverride = null;
testCert = null;
}
ManagedChannel channel =
TesterOkHttpChannelBuilder.build(host, port, serverHostOverride, true, testCert);
new InteropTask(this, channel, testCase).execute();
// Create Channel
ManagedChannel channel;
if (udsEnabled) {
channel = UdsChannelBuilder.forPath(udsPath, Namespace.ABSTRACT).build();
} else {
channel = TesterOkHttpChannelBuilder.build(host, port, serverHostOverride, true, testCert);
}
// Port-forward uds local port to server exposing tcp endpoint.
if (udsEnabled) {
endpointConnector = new UdsTcpEndpointConnector(udsPath, host, port);
try {
endpointConnector.start();
} catch (IOException e) {
Log.e(LOG_TAG, "Failed to start UDS-TCP Endpoint Connector.");
}
}
// Start Test.
String result = null;
try {
result = executor.submit(new TestCallable(channel, testCase)).get();
} catch (ExecutionException | InterruptedException e) {
result = e.getMessage();
} finally {
if (endpointConnector != null) {
endpointConnector.shutDown();
endpointConnector = null;
}
resultText.setText(result);
enableButtons(true);
}
}
@Override

View File

@ -16,22 +16,15 @@
package io.grpc.android.integrationtest;
import android.support.annotation.Nullable;
import androidx.annotation.Nullable;
import io.grpc.ChannelCredentials;
import io.grpc.Grpc;
import io.grpc.InsecureChannelCredentials;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.okhttp.SslSocketFactoryChannelCredentials;
import io.grpc.TlsChannelCredentials;
import io.grpc.okhttp.OkHttpChannelBuilder;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.security.auth.x500.X500Principal;
/**
* A helper class to create a OkHttp based channel.
@ -45,10 +38,14 @@ class TesterOkHttpChannelBuilder {
@Nullable InputStream testCa) {
ChannelCredentials credentials;
if (useTls) {
try {
credentials = SslSocketFactoryChannelCredentials.create(getSslSocketFactory(testCa));
} catch (Exception e) {
throw new RuntimeException(e);
if (testCa == null) {
credentials = TlsChannelCredentials.create();
} else {
try {
credentials = TlsChannelCredentials.newBuilder().trustManager(testCa).build();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
} else {
credentials = InsecureChannelCredentials.create();
@ -57,36 +54,13 @@ class TesterOkHttpChannelBuilder {
ManagedChannelBuilder<?> channelBuilder = Grpc.newChannelBuilderForAddress(
host, port, credentials)
.maxInboundMessageSize(16 * 1024 * 1024);
if (!(channelBuilder instanceof OkHttpChannelBuilder)) {
throw new RuntimeException("Did not receive an OkHttpChannelBuilder");
}
if (serverHostOverride != null) {
// Force the hostname to match the cert the server uses.
channelBuilder.overrideAuthority(serverHostOverride);
}
return channelBuilder.build();
}
private static SSLSocketFactory getSslSocketFactory(@Nullable InputStream testCa)
throws Exception {
if (testCa == null) {
return (SSLSocketFactory) SSLSocketFactory.getDefault();
}
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, getTrustManagers(testCa) , null);
return context.getSocketFactory();
}
private static TrustManager[] getTrustManagers(InputStream testCa) throws Exception {
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(null);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate) cf.generateCertificate(testCa);
X500Principal principal = cert.getSubjectX500Principal();
ks.setCertificateEntry(principal.getName("RFC2253"), cert);
// Set up trust manager factory to use our key store.
TrustManagerFactory trustManagerFactory =
TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(ks);
return trustManagerFactory.getTrustManagers();
}
}

View File

@ -0,0 +1,198 @@
/*
* 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 java.util.concurrent.TimeUnit.SECONDS;
import android.net.LocalServerSocket;
import android.net.LocalSocket;
import android.util.Log;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Collection;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Funnels traffic between a given UDS endpoint and a local TCP endpoint. A client binds to the UDS
* endpoint, but effectively communicates with the TCP endpoint.
*/
public class UdsTcpEndpointConnector {
private static final String LOG_TAG = "EndpointConnector";
// Discard-policy, to allow dropping tasks that were received immediately after shutDown()
private final ThreadPoolExecutor executor =
new ThreadPoolExecutor(
5,
10,
1,
SECONDS,
new LinkedBlockingQueue<>(),
new ThreadPoolExecutor.DiscardOldestPolicy());
private final String udsPath;
private final String host;
private final int port;
private InetSocketAddress socketAddress;
private LocalServerSocket clientAcceptor;
private volatile boolean shutDownRequested = false;
private volatile boolean shutDownComplete = false;
/** Listen on udsPath and forward connections to host:port. */
public UdsTcpEndpointConnector(String udsPath, String host, int port) {
this.udsPath = udsPath;
this.host = host;
this.port = port;
}
/** Start listening and accept connections. */
public void start() throws IOException {
clientAcceptor = new LocalServerSocket(udsPath);
executor.execute(
new Runnable() {
@Override
public void run() {
Log.i(LOG_TAG, "Starting connection from " + udsPath + " to " + socketAddress);
socketAddress = new InetSocketAddress(host, port);
while (!shutDownRequested) {
try {
LocalSocket clientSocket = clientAcceptor.accept();
if (shutDownRequested) {
// Check if shut down during blocking accept().
clientSocket.close();
shutDownComplete = true;
break;
}
Socket serverSocket = new Socket();
serverSocket.connect(socketAddress);
startWorkers(clientSocket, serverSocket);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
});
}
/** Stop listening and release resources. */
public void shutDown() {
Log.i(LOG_TAG, "Shutting down connection from " + udsPath + " to " + socketAddress);
shutDownRequested = true;
try {
// Upon clientAcceptor.close(), clientAcceptor.accept() continues to block.
// Thus, once shutDownRequested=true, must send a connection request to unblock accept().
LocalSocket localSocket = new LocalSocket();
localSocket.connect(clientAcceptor.getLocalSocketAddress());
localSocket.close();
clientAcceptor.close();
} catch (IOException e) {
Log.w(LOG_TAG, "Failed to close LocalServerSocket", e);
}
executor.shutdownNow();
}
public boolean isShutdown() {
return shutDownComplete && executor.isShutdown();
}
private void startWorkers(LocalSocket clientSocket, Socket serverSocket) throws IOException {
DataInputStream clientIn = new DataInputStream(clientSocket.getInputStream());
DataOutputStream clientOut = new DataOutputStream(serverSocket.getOutputStream());
DataInputStream serverIn = new DataInputStream(serverSocket.getInputStream());
DataOutputStream serverOut = new DataOutputStream(clientSocket.getOutputStream());
AtomicInteger completionCount = new AtomicInteger(0);
StreamConnector.Listener cleanupListener =
new StreamConnector.Listener() {
@Override
public void onFinished() {
if (completionCount.incrementAndGet() == 2) {
try {
serverSocket.close();
clientSocket.close();
} catch (IOException e) {
Log.e(LOG_TAG, "Failed to clean up connected sockets.", e);
}
}
}
};
executor.execute(new StreamConnector(clientIn, clientOut).addListener(cleanupListener));
executor.execute(new StreamConnector(serverIn, serverOut).addListener(cleanupListener));
}
/**
* Funnels everything that comes in to a DataInputStream into an DataOutputStream, until the
* DataInputStream is closed. (detected by IOException).
*/
private static final class StreamConnector implements Runnable {
interface Listener {
void onFinished();
}
private static final int BUFFER_SIZE = 1000;
private final DataInputStream in;
private final DataOutputStream out;
private final byte[] buffer = new byte[BUFFER_SIZE];
private boolean finished = false;
private final Collection<Listener> listeners = new ArrayList<>();
StreamConnector(DataInputStream in, DataOutputStream out) {
this.in = in;
this.out = out;
}
StreamConnector addListener(Listener listener) {
listeners.add(listener);
return this;
}
@Override
public void run() {
while (!finished) {
int bytesRead;
try {
bytesRead = in.read(buffer);
if (bytesRead == -1) {
finished = true;
out.close();
continue;
}
out.write(buffer, 0, bytesRead);
} catch (IOException e) {
finished = true;
}
}
for (StreamConnector.Listener listener : listeners) {
listener.onFinished();
}
}
}
}

View File

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="#AAA" android:state_focused="false"/>
<item android:color="#000" android:state_focused="true"/>
</selector>

View File

@ -28,6 +28,28 @@
/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<CheckBox android:id="@+id/use_uds_checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="enableUds"
android:textColor="@color/focus"
android:text="Use UDS (SSL not supported)"
tools:ignore="OnClick"
/>
<EditText
android:id="@+id/uds_proxy_edit_text"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:enabled="false"
android:inputType="text"
android:hint="Enter Unix Domain Socket Abstract Namespace Address"
/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
@ -36,6 +58,7 @@
<CheckBox android:id="@+id/test_cert_checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/focus"
android:text="Use Test Cert"
/>
</LinearLayout>
@ -46,6 +69,7 @@
android:layout_height="wrap_content"
android:onClick="startEmptyUnary"
android:text="Empty Unary"
tools:ignore="OnClick"
/>
<Button
@ -54,6 +78,7 @@
android:layout_height="wrap_content"
android:onClick="startLargeUnary"
android:text="Large Unary"
tools:ignore="OnClick"
/>
<Button
@ -62,6 +87,7 @@
android:layout_height="wrap_content"
android:onClick="startClientStreaming"
android:text="Client Streaming"
tools:ignore="OnClick"
/>
<Button
@ -70,6 +96,7 @@
android:layout_height="wrap_content"
android:onClick="startServerStreaming"
android:text="Server Streaming"
tools:ignore="OnClick"
/>
<Button
@ -78,6 +105,7 @@
android:layout_height="wrap_content"
android:onClick="startPingPong"
android:text="Ping Pong"
tools:ignore="OnClick"
/>
<TextView

View File

@ -2,43 +2,49 @@ plugins {
id "maven-publish"
id "com.android.library"
id "digital.wup.android-maven-publish"
}
description = 'gRPC: Android'
android {
compileSdkVersion 28
namespace = 'io.grpc.android'
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
compileSdkVersion 34
defaultConfig {
consumerProguardFiles "proguard-rules.txt"
minSdkVersion 16
targetSdkVersion 28
minSdkVersion 22
targetSdkVersion 33
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
lintOptions { abortOnError = true }
publishing {
singleVariant('release') {
withSourcesJar()
withJavadocJar()
}
}
lintOptions { abortOnError false }
}
repositories {
google()
jcenter()
}
dependencies {
api project(':grpc-core')
guavaDependency 'implementation'
api project(':grpc-api')
implementation project(':grpc-core')
implementation libraries.guava
testImplementation project('::grpc-okhttp')
testImplementation libraries.androidx_test
testImplementation libraries.androidx.test.core
testImplementation libraries.junit
testImplementation (libraries.robolectric) {
// Unreleased change: https://github.com/robolectric/robolectric/pull/5432
exclude group: 'com.google.auto.service', module: 'auto-service'
}
testImplementation libraries.robolectric
testImplementation libraries.truth
}
task javadocs(type: Javadoc) {
tasks.register("javadocs", Javadoc) {
source = android.sourceSets.main.java.srcDirs
classpath += files(android.getBootClasspath())
classpath += files({
@ -54,23 +60,23 @@ task javadocs(type: Javadoc) {
}
}
task javadocJar(type: Jar, dependsOn: javadocs) {
classifier = 'javadoc'
tasks.register("javadocJar", Jar) {
dependsOn javadocs
archiveClassifier = 'javadoc'
from javadocs.destinationDir
}
task sourcesJar(type: Jar) {
classifier = 'sources'
tasks.register("sourcesJar", Jar) {
archiveClassifier = 'sources'
from android.sourceSets.main.java.srcDirs
}
publishing {
publications {
maven {
from components.android
artifact javadocJar
artifact sourcesJar
afterEvaluate {
from components.release
}
}
}
}

View File

@ -1,6 +0,0 @@
-keepclassmembers class io.grpc.okhttp.OkHttpChannelBuilder {
io.grpc.okhttp.OkHttpChannelBuilder forTarget(java.lang.String);
io.grpc.okhttp.OkHttpChannelBuilder scheduledExecutorService(java.util.concurrent.ScheduledExecutorService);
io.grpc.okhttp.OkHttpChannelBuilder sslSocketFactory(javax.net.ssl.SSLSocketFactory);
io.grpc.okhttp.OkHttpChannelBuilder transportExecutor(java.util.concurrent.Executor);
}

View File

@ -1,5 +1,4 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="io.grpc.android">
<manifest xmlns:android="http://schemas.android.com/apk/res/android" >
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

View File

@ -23,23 +23,25 @@ import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkInfo;
import android.os.Build;
import android.util.Log;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.errorprone.annotations.InlineMe;
import com.google.errorprone.annotations.concurrent.GuardedBy;
import io.grpc.CallOptions;
import io.grpc.ClientCall;
import io.grpc.ConnectivityState;
import io.grpc.ExperimentalApi;
import io.grpc.ForwardingChannelBuilder;
import io.grpc.InternalManagedChannelProvider;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.ManagedChannelProvider;
import io.grpc.MethodDescriptor;
import io.grpc.internal.GrpcUtil;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;
import javax.annotation.concurrent.GuardedBy;
/**
* Builds a {@link ManagedChannel} that, when provided with a {@link Context}, will automatically
@ -55,14 +57,35 @@ public final class AndroidChannelBuilder extends ForwardingChannelBuilder<Androi
private static final String LOG_TAG = "AndroidChannelBuilder";
@Nullable private static final Class<?> OKHTTP_CHANNEL_BUILDER_CLASS = findOkHttp();
@Nullable private static final ManagedChannelProvider OKHTTP_CHANNEL_PROVIDER = findOkHttp();
private static Class<?> findOkHttp() {
private static ManagedChannelProvider findOkHttp() {
Class<?> klassRaw;
try {
return Class.forName("io.grpc.okhttp.OkHttpChannelBuilder");
klassRaw = Class.forName("io.grpc.okhttp.OkHttpChannelProvider");
} catch (ClassNotFoundException e) {
Log.w(LOG_TAG, "Failed to find OkHttpChannelProvider", e);
return null;
}
Class<? extends ManagedChannelProvider> klass;
try {
klass = klassRaw.asSubclass(ManagedChannelProvider.class);
} catch (ClassCastException e) {
Log.w(LOG_TAG, "Couldn't cast OkHttpChannelProvider to ManagedChannelProvider", e);
return null;
}
ManagedChannelProvider provider;
try {
provider = klass.getConstructor().newInstance();
} catch (Exception e) {
Log.w(LOG_TAG, "Failed to construct OkHttpChannelProvider", e);
return null;
}
if (!InternalManagedChannelProvider.isAvailable(provider)) {
Log.w(LOG_TAG, "OkHttpChannelProvider.isAvailable() returned false");
return null;
}
return provider;
}
private final ManagedChannelBuilder<?> delegateBuilder;
@ -91,6 +114,9 @@ public final class AndroidChannelBuilder extends ForwardingChannelBuilder<Androi
*/
@ExperimentalApi("https://github.com/grpc/grpc-java/issues/6043")
@Deprecated
@InlineMe(
replacement = "AndroidChannelBuilder.usingBuilder(builder)",
imports = "io.grpc.android.AndroidChannelBuilder")
public static AndroidChannelBuilder fromBuilder(ManagedChannelBuilder<?> builder) {
return usingBuilder(builder);
}
@ -110,18 +136,11 @@ public final class AndroidChannelBuilder extends ForwardingChannelBuilder<Androi
}
private AndroidChannelBuilder(String target) {
if (OKHTTP_CHANNEL_BUILDER_CLASS == null) {
throw new UnsupportedOperationException("No ManagedChannelBuilder found on the classpath");
}
try {
delegateBuilder =
(ManagedChannelBuilder)
OKHTTP_CHANNEL_BUILDER_CLASS
.getMethod("forTarget", String.class)
.invoke(null, target);
} catch (Exception e) {
throw new RuntimeException("Failed to create ManagedChannelBuilder", e);
if (OKHTTP_CHANNEL_PROVIDER == null) {
throw new UnsupportedOperationException("Unable to load OkHttpChannelProvider");
}
delegateBuilder =
InternalManagedChannelProvider.builderForTarget(OKHTTP_CHANNEL_PROVIDER, target);
}
private AndroidChannelBuilder(ManagedChannelBuilder<?> delegateBuilder) {
@ -137,6 +156,7 @@ public final class AndroidChannelBuilder extends ForwardingChannelBuilder<Androi
}
@Override
@SuppressWarnings("deprecation") // Not extending ForwardingChannelBuilder2 to preserve ABI.
protected ManagedChannelBuilder<?> delegate() {
return delegateBuilder;
}
@ -151,7 +171,7 @@ public final class AndroidChannelBuilder extends ForwardingChannelBuilder<Androi
/**
* Wraps an OkHttp channel and handles invoking the appropriate methods (e.g., {@link
* ManagedChannel#enterIdle) when the device network state changes.
* ManagedChannel#enterIdle}) when the device network state changes.
*/
@VisibleForTesting
static final class AndroidChannel extends ManagedChannel {
@ -197,7 +217,6 @@ public final class AndroidChannelBuilder extends ForwardingChannelBuilder<Androi
connectivityManager.registerDefaultNetworkCallback(defaultNetworkCallback);
unregisterRunnable =
new Runnable() {
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public void run() {
connectivityManager.unregisterNetworkCallback(defaultNetworkCallback);
@ -211,7 +230,6 @@ public final class AndroidChannelBuilder extends ForwardingChannelBuilder<Androi
context.registerReceiver(networkReceiver, networkIntentFilter);
unregisterRunnable =
new Runnable() {
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public void run() {
context.unregisterReceiver(networkReceiver);
@ -294,17 +312,25 @@ public final class AndroidChannelBuilder extends ForwardingChannelBuilder<Androi
public void onAvailable(Network network) {
delegate.enterIdle();
}
@Override
public void onBlockedStatusChanged(Network network, boolean blocked) {
if (!blocked) {
delegate.enterIdle();
}
}
}
/** Respond to network changes. Only used on API levels < 24. */
private class NetworkReceiver extends BroadcastReceiver {
private boolean isConnected = false;
@SuppressWarnings("deprecation")
@Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager conn =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = conn.getActiveNetworkInfo();
android.net.NetworkInfo networkInfo = conn.getActiveNetworkInfo();
boolean wasConnected = isConnected;
isConnected = networkInfo != null && networkInfo.isConnected();
if (isConnected && !wasConnected) {

View File

@ -0,0 +1,95 @@
/*
* 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;
import android.net.LocalSocketAddress.Namespace;
import io.grpc.ChannelCredentials;
import io.grpc.ExperimentalApi;
import io.grpc.InsecureChannelCredentials;
import io.grpc.ManagedChannelBuilder;
import java.lang.reflect.InvocationTargetException;
import javax.annotation.Nullable;
import javax.net.SocketFactory;
/**
* Creates a UDS channel by passing in a specialized SocketFactory into an OkHttpChannelBuilder. The
* UdsSockets produced by this factory communicate over Android's LocalSockets.
*
* <p>Example Usage <code>
* Channel channel = UdsChannelBuilder.forPath("/data/data/my.app/app.socket",
* Namespace.FILESYSTEM).build();
* stub = MyService.newStub(channel);
* </code>
*
* <p>This class uses a safe-for-production hack to workaround NameResolver's inability to safely
* return non-IP SocketAddress types. The hack simply ignores the name resolver results and connects
* to the UDS name provided during construction instead. This class is expected to be replaced with
* a `unix:` name resolver when possible.
*/
@ExperimentalApi("A stopgap. Not intended to be stabilized")
public final class UdsChannelBuilder {
@Nullable
@SuppressWarnings("rawtypes")
private static final Class<? extends ManagedChannelBuilder> OKHTTP_CHANNEL_BUILDER_CLASS =
findOkHttp();
@SuppressWarnings("rawtypes")
private static Class<? extends ManagedChannelBuilder> findOkHttp() {
try {
return Class.forName("io.grpc.okhttp.OkHttpChannelBuilder")
.asSubclass(ManagedChannelBuilder.class);
} catch (ClassNotFoundException e) {
return null;
}
}
/**
* Returns a channel to the UDS endpoint specified by the file-path.
*
* @param path unix file system path to use for Unix Domain Socket.
* @param namespace the type of the namespace that the path belongs to.
*/
public static ManagedChannelBuilder<?> forPath(String path, Namespace namespace) {
if (OKHTTP_CHANNEL_BUILDER_CLASS == null) {
throw new UnsupportedOperationException("OkHttpChannelBuilder not found on the classpath");
}
try {
// Target 'dns:///127.0.0.1' is unused, but necessary as an argument for OkHttpChannelBuilder.
// An IP address is used instead of localhost to avoid a DNS lookup (see #11442). This should
// work even if IPv4 is unavailable, as the DNS resolver doesn't need working IPv4 to parse an
// IPv4 address. Unavailable IPv4 fails when we connect(), not at resolution time.
// TLS is unsupported because Conscrypt assumes the platform Socket implementation to improve
// performance by using the file descriptor directly.
Object o = OKHTTP_CHANNEL_BUILDER_CLASS
.getMethod("forTarget", String.class, ChannelCredentials.class)
.invoke(null, "dns:///127.0.0.1", InsecureChannelCredentials.create());
ManagedChannelBuilder<?> builder = OKHTTP_CHANNEL_BUILDER_CLASS.cast(o);
OKHTTP_CHANNEL_BUILDER_CLASS
.getMethod("socketFactory", SocketFactory.class)
.invoke(builder, new UdsSocketFactory(path, namespace));
return builder;
} catch (IllegalAccessException e) {
throw new RuntimeException("Failed to create OkHttpChannelBuilder", e);
} catch (NoSuchMethodException e) {
throw new RuntimeException("Failed to create OkHttpChannelBuilder", e);
} catch (InvocationTargetException e) {
throw new RuntimeException("Failed to create OkHttpChannelBuilder", e);
}
}
private UdsChannelBuilder() {}
}

View File

@ -0,0 +1,312 @@
/*
* 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;
import android.net.LocalSocket;
import android.net.LocalSocketAddress;
import com.google.errorprone.annotations.concurrent.GuardedBy;
import java.io.FilterInputStream;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketException;
import java.nio.channels.SocketChannel;
/**
* Adapter from Android's LocalSocket to Socket. This class is only needed by grpc-okhttp, so the
* adapter only has to support the things that grcp-okhttp uses. It is fine to support trivial
* things unused by the transport, to be less likely to break as the transport usage changes, but it
* is also unnecessary. It's okay to stretch the truth or lie when necessary. For example, little
* hurts with {@link #setTcpNoDelay(boolean)} being a noop since unix domain sockets don't have such
* unnecessary delays.
*/
@SuppressWarnings("UnsynchronizedOverridesSynchronized") // Rely on LocalSocket's synchronization
class UdsSocket extends Socket {
private final LocalSocket localSocket;
private final LocalSocketAddress localSocketAddress;
@GuardedBy("this")
private boolean closed = false;
@GuardedBy("this")
private boolean inputShutdown = false;
@GuardedBy("this")
private boolean outputShutdown = false;
public UdsSocket(LocalSocketAddress localSocketAddress) {
this.localSocketAddress = localSocketAddress;
localSocket = new LocalSocket();
}
@Override
public void bind(SocketAddress bindpoint) {
// no-op
}
@Override
public synchronized void close() throws IOException {
if (closed) {
return;
}
if (!inputShutdown) {
shutdownInput();
}
if (!outputShutdown) {
shutdownOutput();
}
localSocket.close();
closed = true;
}
@Override
public void connect(SocketAddress endpoint) throws IOException {
localSocket.connect(localSocketAddress);
}
@Override
public void connect(SocketAddress endpoint, int timeout) throws IOException {
localSocket.connect(localSocketAddress, timeout);
}
@Override
public SocketChannel getChannel() {
throw new UnsupportedOperationException("getChannel() not supported");
}
@Override
public InetAddress getInetAddress() {
throw new UnsupportedOperationException("getInetAddress() not supported");
}
@Override
public InputStream getInputStream() throws IOException {
return new FilterInputStream(localSocket.getInputStream()) {
@Override
public void close() throws IOException {
UdsSocket.this.close();
}
};
}
@Override
public boolean getKeepAlive() {
throw new UnsupportedOperationException("Unsupported operation getKeepAlive()");
}
@Override
public InetAddress getLocalAddress() {
throw new UnsupportedOperationException("Unsupported operation getLocalAddress()");
}
@Override
public int getLocalPort() {
throw new UnsupportedOperationException("Unsupported operation getLocalPort()");
}
@Override
public SocketAddress getLocalSocketAddress() {
return new SocketAddress() {};
}
@Override
public boolean getOOBInline() {
throw new UnsupportedOperationException("Unsupported operation getOOBInline()");
}
@Override
public OutputStream getOutputStream() throws IOException {
return new FilterOutputStream(localSocket.getOutputStream()) {
@Override
public void close() throws IOException {
UdsSocket.this.close();
}
};
}
@Override
public int getPort() {
throw new UnsupportedOperationException("Unsupported operation getPort()");
}
@Override
public int getReceiveBufferSize() throws SocketException {
try {
return localSocket.getReceiveBufferSize();
} catch (IOException e) {
throw toSocketException(e);
}
}
@Override
public SocketAddress getRemoteSocketAddress() {
return new SocketAddress() {};
}
@Override
public boolean getReuseAddress() {
throw new UnsupportedOperationException("Unsupported operation getReuseAddress()");
}
@Override
public int getSendBufferSize() throws SocketException {
try {
return localSocket.getSendBufferSize();
} catch (IOException e) {
throw toSocketException(e);
}
}
@Override
public int getSoLinger() {
return -1; // unsupported
}
@Override
public int getSoTimeout() throws SocketException {
try {
return localSocket.getSoTimeout();
} catch (IOException e) {
throw toSocketException(e);
}
}
@Override
public boolean getTcpNoDelay() {
return true;
}
@Override
public int getTrafficClass() {
throw new UnsupportedOperationException("Unsupported operation getTrafficClass()");
}
@Override
public boolean isBound() {
return localSocket.isBound();
}
@Override
public synchronized boolean isClosed() {
return closed;
}
@Override
public boolean isConnected() {
return localSocket.isConnected();
}
@Override
public synchronized boolean isInputShutdown() {
return inputShutdown;
}
@Override
public synchronized boolean isOutputShutdown() {
return outputShutdown;
}
@Override
public void sendUrgentData(int data) {
throw new UnsupportedOperationException("Unsupported operation sendUrgentData()");
}
@Override
public void setKeepAlive(boolean on) {
throw new UnsupportedOperationException("Unsupported operation setKeepAlive()");
}
@Override
public void setOOBInline(boolean on) {
throw new UnsupportedOperationException("Unsupported operation setOOBInline()");
}
@Override
public void setPerformancePreferences(int connectionTime, int latency, int bandwidth) {
throw new UnsupportedOperationException("Unsupported operation setPerformancePreferences()");
}
@Override
public void setReceiveBufferSize(int size) throws SocketException {
try {
localSocket.setReceiveBufferSize(size);
} catch (IOException e) {
throw toSocketException(e);
}
}
@Override
public void setReuseAddress(boolean on) {
throw new UnsupportedOperationException("Unsupported operation setReuseAddress()");
}
@Override
public void setSendBufferSize(int size) throws SocketException {
try {
localSocket.setSendBufferSize(size);
} catch (IOException e) {
throw toSocketException(e);
}
}
@Override
public void setSoLinger(boolean on, int linger) {
throw new UnsupportedOperationException("Unsupported operation setSoLinger()");
}
@Override
public void setSoTimeout(int timeout) throws SocketException {
try {
localSocket.setSoTimeout(timeout);
} catch (IOException e) {
throw toSocketException(e);
}
}
@Override
public void setTcpNoDelay(boolean on) {
// no-op
}
@Override
public void setTrafficClass(int tc) {
throw new UnsupportedOperationException("Unsupported operation setTrafficClass()");
}
@Override
public synchronized void shutdownInput() throws IOException {
localSocket.shutdownInput();
inputShutdown = true;
}
@Override
public synchronized void shutdownOutput() throws IOException {
localSocket.shutdownOutput();
outputShutdown = true;
}
private static SocketException toSocketException(Throwable e) {
SocketException se = new SocketException();
se.initCause(e);
return se;
}
}

View File

@ -0,0 +1,77 @@
/*
* 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;
import android.net.LocalSocketAddress;
import android.net.LocalSocketAddress.Namespace;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import javax.net.SocketFactory;
/**
* A SocketFactory that produces {@link UdsSocket} instances. This is used to provide support for
* gRPC channels with an underlying Unix Domain Socket transport.
*/
class UdsSocketFactory extends SocketFactory {
private final LocalSocketAddress localSocketAddress;
public UdsSocketFactory(String path, Namespace namespace) {
localSocketAddress = new LocalSocketAddress(path, namespace);
}
@Override
public Socket createSocket() throws IOException {
return create();
}
@Override
public Socket createSocket(String host, int port) throws IOException {
return createAndConnect();
}
@Override
public Socket createSocket(String host, int port, InetAddress localHost, int localPort)
throws IOException {
return createAndConnect();
}
@Override
public Socket createSocket(InetAddress host, int port) throws IOException {
return createAndConnect();
}
@Override
public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort)
throws IOException {
return createAndConnect();
}
private Socket create() {
return new UdsSocket(localSocketAddress);
}
private Socket createAndConnect() throws IOException {
Socket socket = create();
SocketAddress unusedAddress = new InetSocketAddress(0);
socket.connect(unusedAddress);
return socket;
}
}

View File

@ -27,7 +27,6 @@ import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkInfo;
import androidx.test.core.app.ApplicationProvider;
import io.grpc.CallOptions;
import io.grpc.ClientCall;
@ -53,34 +52,34 @@ import org.robolectric.shadows.ShadowNetworkInfo;
@Config(shadows = {AndroidChannelBuilderTest.ShadowDefaultNetworkListenerConnectivityManager.class})
@SuppressWarnings("deprecation")
public final class AndroidChannelBuilderTest {
private final NetworkInfo WIFI_CONNECTED =
private final android.net.NetworkInfo WIFI_CONNECTED =
ShadowNetworkInfo.newInstance(
NetworkInfo.DetailedState.CONNECTED,
android.net.NetworkInfo.DetailedState.CONNECTED,
ConnectivityManager.TYPE_WIFI,
0,
true,
NetworkInfo.State.CONNECTED);
private final NetworkInfo WIFI_DISCONNECTED =
android.net.NetworkInfo.State.CONNECTED);
private final android.net.NetworkInfo WIFI_DISCONNECTED =
ShadowNetworkInfo.newInstance(
NetworkInfo.DetailedState.DISCONNECTED,
android.net.NetworkInfo.DetailedState.DISCONNECTED,
ConnectivityManager.TYPE_WIFI,
0,
true,
NetworkInfo.State.DISCONNECTED);
private final NetworkInfo MOBILE_CONNECTED =
android.net.NetworkInfo.State.DISCONNECTED);
private final android.net.NetworkInfo MOBILE_CONNECTED =
ShadowNetworkInfo.newInstance(
NetworkInfo.DetailedState.CONNECTED,
android.net.NetworkInfo.DetailedState.CONNECTED,
ConnectivityManager.TYPE_MOBILE,
ConnectivityManager.TYPE_MOBILE_MMS,
true,
NetworkInfo.State.CONNECTED);
private final NetworkInfo MOBILE_DISCONNECTED =
android.net.NetworkInfo.State.CONNECTED);
private final android.net.NetworkInfo MOBILE_DISCONNECTED =
ShadowNetworkInfo.newInstance(
NetworkInfo.DetailedState.DISCONNECTED,
android.net.NetworkInfo.DetailedState.DISCONNECTED,
ConnectivityManager.TYPE_MOBILE,
ConnectivityManager.TYPE_MOBILE_MMS,
true,
NetworkInfo.State.DISCONNECTED);
android.net.NetworkInfo.State.DISCONNECTED);
private ConnectivityManager connectivityManager;
@ -280,9 +279,9 @@ public final class AndroidChannelBuilderTest {
}
@Override
public void setActiveNetworkInfo(NetworkInfo activeNetworkInfo) {
public void setActiveNetworkInfo(android.net.NetworkInfo activeNetworkInfo) {
if (getApiLevel() >= N) {
NetworkInfo previousNetworkInfo = getActiveNetworkInfo();
android.net.NetworkInfo previousNetworkInfo = getActiveNetworkInfo();
if (activeNetworkInfo != null && activeNetworkInfo.isConnected()) {
notifyDefaultNetworkCallbacksOnAvailable(
ShadowNetwork.newInstance(activeNetworkInfo.getType() /* use type as network ID */));

View File

@ -1,14 +1,16 @@
load("@rules_jvm_external//:defs.bzl", "artifact")
java_library(
name = "api",
srcs = glob([
"src/main/java/**/*.java",
"src/context/java/**/*.java",
]),
visibility = ["//visibility:public"],
deps = [
"//context",
"@com_google_code_findbugs_jsr305//jar",
"@com_google_guava_failureaccess//jar", # future transitive dep of Guava. See #5214
"@com_google_guava_guava//jar",
"@com_google_j2objc_j2objc_annotations//jar",
artifact("com.google.code.findbugs:jsr305"),
artifact("com.google.errorprone:error_prone_annotations"),
artifact("com.google.guava:failureaccess"), # future transitive dep of Guava. See #5214
artifact("com.google.guava:guava"),
],
)

Some files were not shown because too many files have changed in this diff Show More