Compare commits

...

716 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
1215 changed files with 74494 additions and 34223 deletions

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

@ -9,5 +9,5 @@ jobs:
name: "Gradle wrapper validation"
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: gradle/wrapper-validation-action@v1
- uses: actions/checkout@v4
- uses: gradle/actions/wrapper-validation@v4

View File

@ -13,7 +13,7 @@ jobs:
lock:
runs-on: ubuntu-latest
steps:
- uses: dessant/lock-threads@v4
- uses: dessant/lock-threads@v5
with:
github-token: ${{ github.token }}
issue-inactive-days: 90

View File

@ -17,18 +17,18 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
jre: [8, 11]
jre: [8, 11, 17]
fail-fast: false # Should swap to true if we grow a large matrix
steps:
- uses: actions/checkout@v3
- uses: actions/setup-java@v3
- uses: actions/checkout@v4
- uses: actions/setup-java@v4
with:
java-version: ${{ matrix.jre }}
distribution: 'temurin'
- name: Gradle cache
uses: actions/cache@v3
uses: actions/cache@v4
with:
path: |
~/.gradle/caches
@ -37,7 +37,7 @@ jobs:
restore-keys: |
${{ runner.os }}-gradle-
- name: Maven cache
uses: actions/cache@v3
uses: actions/cache@v4
with:
path: |
~/.m2/repository
@ -46,7 +46,7 @@ jobs:
restore-keys: |
${{ runner.os }}-maven-
- name: Protobuf cache
uses: actions/cache@v3
uses: actions/cache@v4
with:
path: /tmp/protobuf-cache
key: ${{ runner.os }}-maven-${{ hashFiles('buildscripts/make_dependencies.sh') }}
@ -55,7 +55,7 @@ jobs:
run: buildscripts/kokoro/unix.sh
- name: Post Failure Upload Test Reports to Artifacts
if: ${{ failure() }}
uses: actions/upload-artifact@v3
uses: actions/upload-artifact@v4
with:
name: Test Reports (JRE ${{ matrix.jre }})
path: |
@ -71,18 +71,28 @@ jobs:
COVERALLS_REPO_TOKEN: ${{ secrets.COVERALLS_REPO_TOKEN }}
run: ./gradlew :grpc-all:coveralls -PskipAndroid=true -x compileJava
- name: Codecov
uses: codecov/codecov-action@v3
uses: codecov/codecov-action@v4
with:
token: ${{ secrets.CODECOV_TOKEN }}
bazel:
runs-on: ubuntu-latest
strategy:
matrix:
bzlmod: [true, false]
env:
USE_BAZEL_VERSION: 6.0.0
USE_BAZEL_VERSION: 7.0.0
steps:
- uses: actions/checkout@v3
- 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@v3
uses: actions/cache@v4
with:
path: |
~/.cache/bazel/*/cache
@ -90,4 +100,11 @@ jobs:
key: ${{ runner.os }}-bazel-${{ env.USE_BAZEL_VERSION }}-${{ hashFiles('WORKSPACE', 'repositories.bzl') }}
- name: Run bazel build
run: bazelisk 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

1
.gitignore vendored
View File

@ -15,6 +15,7 @@ bazel-genfiles
bazel-grpc-java
bazel-out
bazel-testlogs
MODULE.bazel.lock
# IntelliJ IDEA
.idea

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,9 +46,8 @@ 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"),
],
)
@ -56,7 +55,7 @@ java_plugin(
name = "auto_value",
generates_api = 1,
processor_class = "com.google.auto.value.processor.AutoValueProcessor",
deps = ["@com_google_auto_value_auto_value//jar"],
deps = [artifact("com.google.auto.value:auto-value")],
)
java_library(
@ -65,7 +64,6 @@ java_library(
neverlink = 1,
visibility = ["//:__subpackages__"],
exports = [
"@com_google_auto_value_auto_value_annotations//jar",
"@org_apache_tomcat_annotations_api//jar", # @Generated for Java 9+
artifact("com.google.auto.value:auto-value-annotations"),
],
)

View File

@ -44,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 21.7 or later.
The codegen plugin is C++ code and requires protobuf 22.5 or later.
For Linux, Mac and MinGW:
```
$ PROTOBUF_VERSION=21.7
$ 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

View File

@ -30,56 +30,36 @@ style configurations are commonly useful. For IntelliJ 14, copy the style to
`~/.IdeaIC14/config/codestyles/`, start IntelliJ, go to File > Settings > Code
Style, and set the Scheme to `GoogleStyle`.
## Maintaining clean commit history
We have few conventions for keeping history clean and making code reviews easier
for reviewers:
* First line of commit messages should be in format of
`package-name: summary of change`
where the summary finishes the sentence: `This commit improves gRPC to ____________.`
for example:
`core,netty,interop-testing: add capacitive duractance to turbo encabulators`
* Every time you receive a feedback on your pull request, push changes that
address it as a separate one or multiple commits with a descriptive commit
message (try avoid using vauge `addressed pr feedback` type of messages).
Project maintainers are obligated to squash those commits into one when
merging.
## Running tests
### Jetty ALPN setup for IntelliJ
The tests in interop-testing project require jetty-alpn agent running in the background
otherwise they'll fail. Here are instructions on how to setup IntellJ IDEA to enable running
those tests in IDE:
* Settings -> Build Tools -> Gradle -> Runner -> select Gradle Test Runner
* View -> Tool Windows -> Gradle -> Edit Run Configuration -> Defaults -> JUnit -> Before lauch -> + -> Run Gradle task, enter the task in the build.gradle that sets the javaagent.
Step 1 must be taken, otherwise by the default JUnit Test Runner running a single test in IDE will trigger all the tests.
## Guidelines for Pull Requests
How to get your contributions merged smoothly and quickly.
- Create **small PRs** that are narrowly focused on **addressing a single concern**. We often times receive PRs that are trying to fix several things at a time, but only one fix is considered acceptable, nothing gets merged and both author's & review's time is wasted. Create more PRs to address different concerns and everyone will be happy.
- For speculative changes, consider opening an issue and discussing it first. If you are suggesting a behavioral or API change, consider starting with a [gRFC proposal](https://github.com/grpc/proposal).
- Provide a good **PR description** as a record of **what** change is being made and **why** it was made. Link to a github issue if it exists.
- Don't fix code style and formatting unless you are already changing that line to address an issue. PRs with irrelevant changes won't be merged. If you do want to fix formatting or style, do that in a separate PR.
- Unless your PR is trivial, you should expect there will be reviewer comments that you'll need to address before merging. We expect you to be reasonably responsive to those comments, otherwise the PR will be closed after 2-3 weeks of inactivity.
- Maintain **clean commit history** and use **meaningful commit messages**. See [maintaining clean commit history](#maintaining-clean-commit-history) for details.
- For speculative changes, consider opening an issue and discussing it to avoid
wasting time on an inappropriate approach. If you are suggesting a behavioral
or API change, consider starting with a [gRFC
proposal](https://github.com/grpc/proposal).
- Follow [typical Git commit message](https://cbea.ms/git-commit/#seven-rules)
structure. Have a good **commit description** as a record of **what** and
**why** the change is being made. Link to a GitHub issue if it exists. The
commit description makes a good PR description and is auto-copied by GitHub if
you have a single commit when creating the PR.
If your change is mostly for a single module (e.g., other module changes are
trivial), prefix your commit summary with the module name changed. Instead of
"Add HTTP/2 faster-than-light support to gRPC Netty" it is more terse as
"netty: Add faster-than-light support".
- Don't fix code style and formatting unless you are already changing that line
to address an issue. If you do want to fix formatting or style, do that in a
separate PR.
- Unless your PR is trivial, you should expect there will be reviewer comments
that you'll need to address before merging. Address comments with additional
commits so the reviewer can review just the changes; do not squash reviewed
commits unless the reviewer agrees. PRs are squashed when merging.
- Keep your PR up to date with upstream/master (if there are merge conflicts, we can't really merge your change).
- **All tests need to be passing** before your change can be merged. We recommend you **run tests locally** before creating your PR to catch breakages early on. Also, `./gradlew build` (`gradlew build` on Windows) **must not introduce any new warnings**.

View File

@ -10,25 +10,26 @@ for general contribution guidelines.
## Maintainers (in alphabetical order)
- [ejona86](https://github.com/ejona86), Google LLC
- [jdcormie](https://github.com/jdcormie), Google LLC
- [larry-safran](https://github.com/larry-safran), Google LLC
- [markb74](https://github.com/markb74), 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
- [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
- [creamsoup](https://github.com/creamsoup), Google LLC
- [dapengzhang0](https://github.com/dapengzhang0), Google LLC
- [ericgribkoff](https://github.com/ericgribkoff), Google LLC
- [jiangtaoli2016](https://github.com/jiangtaoli2016), 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
- [srini100](https://github.com/srini100), Google LLC
- [voidzcy](https://github.com/voidzcy), 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",
)

View File

@ -44,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.60.0/examples) and the
[Android example](https://github.com/grpc/grpc-java/tree/v1.60.0/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
@ -56,18 +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.60.0</version>
<version>1.75.0</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-protobuf</artifactId>
<version>1.60.0</version>
<version>1.75.0</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-stub</artifactId>
<version>1.60.0</version>
<version>1.75.0</version>
</dependency>
<dependency> <!-- necessary for Java 9+ -->
<groupId>org.apache.tomcat</groupId>
@ -79,18 +79,18 @@ 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
runtimeOnly 'io.grpc:grpc-netty-shaded:1.60.0'
implementation 'io.grpc:grpc-protobuf:1.60.0'
implementation 'io.grpc:grpc-stub:1.60.0'
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.60.0'
implementation 'io.grpc:grpc-protobuf-lite:1.60.0'
implementation 'io.grpc:grpc-stub:1.60.0'
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+
```
@ -99,10 +99,10 @@ For [Bazel](https://bazel.build), you can either
(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.60.0
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
--------------
@ -129,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.24.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.60.0:exe:${os.detected.classifier}</pluginArtifact>
<pluginArtifact>io.grpc:protoc-gen-grpc-java:1.75.0:exe:${os.detected.classifier}</pluginArtifact>
</configuration>
<executions>
<execution>
@ -152,16 +152,16 @@ For non-Android protobuf-based codegen integrated with the Gradle build system,
you can use [protobuf-gradle-plugin][]:
```gradle
plugins {
id 'com.google.protobuf' version '0.9.4'
id 'com.google.protobuf' version '0.9.5'
}
protobuf {
protoc {
artifact = "com.google.protobuf:protoc:3.24.0"
artifact = "com.google.protobuf:protoc:3.25.5"
}
plugins {
grpc {
artifact = 'io.grpc:protoc-gen-grpc-java:1.60.0'
artifact = 'io.grpc:protoc-gen-grpc-java:1.75.0'
}
}
generateProtoTasks {
@ -185,16 +185,16 @@ use protobuf-gradle-plugin but specify the 'lite' options:
```gradle
plugins {
id 'com.google.protobuf' version '0.9.4'
id 'com.google.protobuf' version '0.9.5'
}
protobuf {
protoc {
artifact = "com.google.protobuf:protoc:3.24.0"
artifact = "com.google.protobuf:protoc:3.25.5"
}
plugins {
grpc {
artifact = 'io.grpc:protoc-gen-grpc-java:1.60.0'
artifact = 'io.grpc:protoc-gen-grpc-java:1.75.0'
}
}
generateProtoTasks {
@ -269,6 +269,9 @@ gRPC comes with multiple Transport implementations:
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.

View File

@ -18,8 +18,10 @@ them before continuing, and set them again when resuming.
```bash
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
@ -63,7 +65,7 @@ would be used to create all `v1.7` tags (e.g. `v1.7.0`, `v1.7.1`).
```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 log --pretty=format:%H --grep "^Start $MAJOR.$((MINOR+1)).0 development cycle" upstream/master)^
git push upstream v$MAJOR.$MINOR.x
```
5. Continue with Google-internal steps at go/grpc-java/releasing, but stop
@ -76,7 +78,7 @@ would be used to create all `v1.7` tags (e.g. `v1.7.0`, `v1.7.1`).
```bash
echo "## gRPC Java $MAJOR.$MINOR.0 Release Notes" && echo && \
git shortlog --format='%s (%h)' "$(git merge-base upstream/v$MAJOR.$((MINOR-1)).x upstream/v$MAJOR.$MINOR.x)"..upstream/v$MAJOR.$MINOR.x | cat && \
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 log --oneline "$(git merge-base v$MAJOR.$((MINOR-1)).0 upstream/v$MAJOR.$MINOR.x)"..v$MAJOR.$((MINOR-1)).0^
```
@ -130,7 +132,9 @@ Tagging the Release
compiler/src/test{,Lite}/golden/Test{,Deprecated}Service.java.txt
./gradlew build
git commit -a -m "Bump version to $MAJOR.$MINOR.$((PATCH+1))-SNAPSHOT"
git push -u origin release-v$MAJOR.$MINOR.$PATCH
```
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):
@ -156,21 +160,21 @@ Tagging the Release
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).
Central on the [OSSRH site](https://central.sonatype.org/publish/publish-portal-ossrh-staging-api/#deploying).
10. We have containers for each release to detect compatibility regressions with
old releases. Generate one for the new release by following the [GCR image
generation instructions][gcr-image]. Summary:
```bash
# If you haven't previously configured docker:
gcloud auth configure-docker
gcloud auth configure-docker us-docker.pkg.dev
# In main grpc repo, add the new version to matrix
${EDITOR:-nano -w} tools/interop_matrix/client_matrix.py
tools/interop_matrix/create_matrix_images.py --git_checkout --release=v$MAJOR.$MINOR.$PATCH \
--upload_images --language java
docker pull gcr.io/grpc-testing/grpc_interop_java:v$MAJOR.$MINOR.$PATCH
docker_image=gcr.io/grpc-testing/grpc_interop_java:v$MAJOR.$MINOR.$PATCH \
docker pull us-docker.pkg.dev/grpc-testing/testing-images-public/grpc_interop_java:v$MAJOR.$MINOR.$PATCH
docker_image=us-docker.pkg.dev/grpc-testing/testing-images-public/grpc_interop_java:v$MAJOR.$MINOR.$PATCH \
tools/interop_matrix/testcases/java__master
# Commit the changes
@ -202,31 +206,47 @@ Tagging the Release
12. Add [Release Notes](https://github.com/grpc/grpc-java/releases) for the new tag.
*Make sure that any backports are reflected in the release notes.*
13. Notify the Community. Post a release announcement to
[grpc-io](https://groups.google.com/forum/#!forum/grpc-io)
(`grpc-io@googlegroups.com`) with the title `gRPC-Java v$MAJOR.$MINOR.$PATCH
Released`. The email content should link to the GitHub release notes and
include a copy of them.
Update README.md
----------------
After waiting ~1 day and verifying that the release is indexed on [Maven
Central](https://search.maven.org/search?q=g:io.grpc), cherry-pick the commit
that updated the README into the master branch.
14. Update README.md. Cherry-pick the commit that updated the README.md into the
master branch.
```bash
git checkout -b bump-readme master
git cherry-pick v$MAJOR.$MINOR.$PATCH^
git push --set-upstream origin bump-readme
```
Create a PR and go through the review process
15. Update version referenced by tutorials. Update `params.grpc_vers.java` in
[config.yaml](https://github.com/grpc/grpc.io/blob/master/config.yaml) of
the grpc.io repository. Create a PR and go through the review process.
Post-release upgrades
---------------------
Upgrade dependencies after the release so they can be well-tested before the
next release.
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 -b bump-readme master
git cherry-pick v$MAJOR.$MINOR.$PATCH^
git push --set-upstream origin bump-readme
./gradlew checkForUpdates
```
Create a PR and go through the review process
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.
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.
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.
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

@ -84,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
@ -398,7 +398,10 @@ grpc-netty version | netty-handler version | netty-tcnative-boringssl-static ver
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- | 4.1.100.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.)_

View File

@ -2,6 +2,12 @@ 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 = "d31e369b854322ca5098ea12c69d7175ded971435e55c18dd9dd5f29cc5249ac",
@ -16,32 +22,26 @@ 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("@envoy_api//bazel:repositories.bzl", "api_dependencies")
api_dependencies()
load("@com_google_googleapis//:repository_rules.bzl", "switched_rules_by_language")
switched_rules_by_language(
name = "com_google_googleapis_imports",
java = True,
)
maven_install(
artifacts = IO_GRPC_GRPC_JAVA_ARTIFACTS + PROTOBUF_MAVEN_ARTIFACTS,
generate_compat_repositories = True,
override_targets = IO_GRPC_GRPC_JAVA_OVERRIDE_TARGETS,
repositories = [
"https://repo.maven.apache.org/maven2/",
],
strict_visibility = True,
)
load("@maven//:compat.bzl", "compat_repositories")
compat_repositories()

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

@ -12,9 +12,11 @@ def subprojects = [
project(':grpc-auth'),
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'),
@ -49,7 +51,7 @@ tasks.named("javadoc").configure {
continue;
}
source subproject.javadoc.source
options.links subproject.javadoc.options.links.toArray(new String[0])
options.linksOffline.addAll subproject.javadoc.options.linksOffline
}
}

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"),
],
)
@ -35,19 +36,18 @@ java_library(
visibility = ["//visibility:public"],
deps = [
":alts_internal",
":handshaker_java_proto",
":handshaker_java_grpc",
":handshaker_java_proto",
"//api",
"//auth",
"//core:internal",
"//netty",
"@com_google_auth_google_auth_library_oauth2_http//jar",
"@com_google_code_findbugs_jsr305//jar",
"@com_google_guava_guava//jar",
"@com_google_j2objc_j2objc_annotations//jar",
"@io_netty_netty_common//jar",
"@io_netty_netty_handler//jar",
"@io_netty_netty_transport//jar",
artifact("com.google.auth:google-auth-library-oauth2-http"),
artifact("com.google.code.findbugs:jsr305"),
artifact("com.google.guava:guava"),
artifact("io.netty:netty-common"),
artifact("io.netty:netty-handler"),
artifact("io.netty:netty-transport"),
],
)

View File

@ -2,8 +2,8 @@ plugins {
id "java-library"
id "maven-publish"
id "com.github.johnrengelman.shadow"
id "com.google.protobuf"
id "com.gradleup.shadow"
id "ru.vyarus.animalsniffer"
}
@ -13,6 +13,7 @@ dependencies {
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'),
@ -43,7 +44,11 @@ dependencies {
classifier = "linux-x86_64"
}
}
signature libraries.signature.java
signature (libraries.signature.java) {
artifact {
extension = "signature"
}
}
}
configureProtoCompilation()

View File

@ -4,9 +4,6 @@ import static io.grpc.MethodDescriptor.generateFullMethodName;
/**
*/
@javax.annotation.Generated(
value = "by gRPC proto compiler",
comments = "Source: grpc/gcp/handshaker.proto")
@io.grpc.stub.annotations.GrpcGenerated
public final class HandshakerServiceGrpc {
@ -60,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
*/
@ -157,6 +169,40 @@ public final class HandshakerServiceGrpc {
/**
* A stub to allow clients to do synchronous rpc calls to service HandshakerService.
*/
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(

View File

@ -29,7 +29,7 @@ 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 ForwardingChannelBuilder2<AltsChannelBuilder> {
@ -38,7 +38,7 @@ public final class AltsChannelBuilder extends ForwardingChannelBuilder2<AltsChan
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 {

View File

@ -14,9 +14,10 @@
* limitations under the License.
*/
package io.grpc.alts;
import io.grpc.Attributes;
import io.grpc.ClientCall;
import io.grpc.ExperimentalApi;
import io.grpc.ServerCall;
import io.grpc.alts.internal.AltsInternalContext;
@ -29,14 +30,36 @@ public final class AltsContextUtil {
private AltsContextUtil() {}
/**
* Creates a {@link AltsContext} from ALTS context information in the {@link ServerCall}.
* Creates an {@link AltsContext} from ALTS context information in the {@link ServerCall}.
*
* @param call the {@link ServerCall} containing the ALTS information
* @return the created {@link AltsContext}
* @throws IllegalArgumentException if the {@link ServerCall} has no ALTS information.
*/
public static AltsContext createFrom(ServerCall<?,?> call) {
Object authContext = call.getAttributes().get(AltsProtocolNegotiator.AUTH_CONTEXT_KEY);
public static AltsContext createFrom(ServerCall<?, ?> call) {
return createFrom(call.getAttributes());
}
/**
* Creates an {@link AltsContext} from ALTS context information in the {@link ClientCall}.
*
* @param call the {@link ClientCall} containing the ALTS information
* @return the created {@link AltsContext}
* @throws IllegalArgumentException if the {@link ClientCall} has no ALTS information.
*/
public static AltsContext createFrom(ClientCall<?, ?> call) {
return createFrom(call.getAttributes());
}
/**
* Creates an {@link AltsContext} from ALTS context information in the {@link Attributes}.
*
* @param attributes the {@link Attributes} containing the ALTS information
* @return the created {@link AltsContext}
* @throws IllegalArgumentException if the {@link Attributes} has no ALTS information.
*/
public static AltsContext createFrom(Attributes attributes) {
Object authContext = attributes.get(AltsProtocolNegotiator.AUTH_CONTEXT_KEY);
if (!(authContext instanceof AltsInternalContext)) {
throw new IllegalArgumentException("No ALTS context information found");
}
@ -49,8 +72,28 @@ public final class AltsContextUtil {
* @param call the {@link ServerCall} to check
* @return true, if the {@link ServerCall} contains ALTS information and false otherwise.
*/
public static boolean check(ServerCall<?,?> call) {
Object authContext = call.getAttributes().get(AltsProtocolNegotiator.AUTH_CONTEXT_KEY);
public static boolean check(ServerCall<?, ?> call) {
return check(call.getAttributes());
}
/**
* Checks if the {@link ClientCall} contains ALTS information.
*
* @param call the {@link ClientCall} to check
* @return true, if the {@link ClientCall} contains ALTS information and false otherwise.
*/
public static boolean check(ClientCall<?, ?> call) {
return check(call.getAttributes());
}
/**
* Checks if the {@link Attributes} contains ALTS information.
*
* @param attributes the {@link Attributes} to check
* @return true, if the {@link Attributes} contains ALTS information and false otherwise.
*/
public static boolean check(Attributes attributes) {
Object authContext = attributes.get(AltsProtocolNegotiator.AUTH_CONTEXT_KEY);
return authContext instanceof AltsInternalContext;
}
}

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);
}

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

@ -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);
}

View File

@ -63,6 +63,7 @@ public final class GoogleDefaultChannelCredentials {
*/
public static final class Builder {
private CallCredentials callCredentials;
private CallCredentials altsCallCredentials;
private Builder() {}
@ -72,23 +73,32 @@ public final class GoogleDefaultChannelCredentials {
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());
if (callCredentials != null) {
return CompositeChannelCredentials.create(nettyCredentials, callCredentials);
}
CallCredentials callCreds;
try {
callCreds = MoreCallCredentials.from(GoogleCredentials.getApplicationDefault());
} catch (IOException e) {
callCreds =
new FailingCallCredentials(
Status.UNAUTHENTICATED
.withDescription("Failed to get Google default credentials")
.withCause(e));
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);
}

View File

@ -21,6 +21,7 @@ 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;
@ -45,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;
@ -57,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)
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

@ -16,12 +16,12 @@
package io.grpc.alts.internal;
import com.google.errorprone.annotations.concurrent.GuardedBy;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import java.util.LinkedList;
import java.util.Queue;
import javax.annotation.concurrent.GuardedBy;
/** Provides a semaphore primitive, without blocking waiting on permits. */
final class AsyncSemaphore {

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

@ -24,6 +24,7 @@ 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;
@ -37,27 +38,28 @@ import org.junit.runners.JUnit4;
/** Unit tests for {@link AltsContextUtil}. */
@RunWith(JUnit4.class)
public class AltsContextUtilTest {
private final ServerCall<?,?> call = mock(ServerCall.class);
@Test
public void check_noAttributeValue() {
when(call.getAttributes()).thenReturn(Attributes.newBuilder().build());
assertFalse(AltsContextUtil.check(call));
assertFalse(AltsContextUtil.check(Attributes.newBuilder().build()));
}
@Test
public void contains_unexpectedAttributeValueType() {
when(call.getAttributes()).thenReturn(Attributes.newBuilder()
public void check_unexpectedAttributeValueType() {
assertFalse(AltsContextUtil.check(Attributes.newBuilder()
.set(AltsProtocolNegotiator.AUTH_CONTEXT_KEY, new Object())
.build());
assertFalse(AltsContextUtil.check(call));
.build()));
}
@Test
public void contains_altsInternalContext() {
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());
@ -66,26 +68,67 @@ public class AltsContextUtilTest {
}
@Test
public void from_altsInternalContext() {
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();
when(call.getAttributes()).thenReturn(Attributes.newBuilder()
.set(AltsProtocolNegotiator.AUTH_CONTEXT_KEY, new AltsInternalContext(handshakerResult))
.build());
AltsContext context = AltsContextUtil.createFrom(call);
AltsContext context = AltsContextUtil.createFrom(Attributes.newBuilder()
.set(AltsProtocolNegotiator.AUTH_CONTEXT_KEY, new AltsInternalContext(handshakerResult))
.build());
assertEquals("remote@peer", context.getPeerServiceAccount());
assertEquals("local@peer", context.getLocalServiceAccount());
assertEquals(SecurityLevel.INTEGRITY_AND_PRIVACY, context.getSecurityLevel());
}
@Test(expected = IllegalArgumentException.class)
public void from_noAttributeValue() {
when(call.getAttributes()).thenReturn(Attributes.newBuilder().build());
public void createFrom_noAttributeValue() {
AltsContextUtil.createFrom(Attributes.newBuilder().build());
}
AltsContextUtil.createFrom(call);
@Test
public void createFromServer_altsInternalContext() {
HandshakerResult handshakerResult =
HandshakerResult.newBuilder()
.setPeerIdentity(Identity.newBuilder().setServiceAccount("remote@peer"))
.setLocalIdentity(Identity.newBuilder().setServiceAccount("local@peer"))
.build();
ServerCall<?,?> call = mock(ServerCall.class);
when(call.getAttributes()).thenReturn(Attributes.newBuilder()
.set(AltsProtocolNegotiator.AUTH_CONTEXT_KEY, new AltsInternalContext(handshakerResult))
.build());
AltsContext context = AltsContextUtil.createFrom(call);
assertEquals("remote@peer", context.getPeerServiceAccount());
}
@Test
public void createFromClient_altsInternalContext() {
HandshakerResult handshakerResult =
HandshakerResult.newBuilder()
.setPeerIdentity(Identity.newBuilder().setServiceAccount("remote@peer"))
.setLocalIdentity(Identity.newBuilder().setServiceAccount("local@peer"))
.build();
ClientCall<?,?> call = mock(ClientCall.class);
when(call.getAttributes()).thenReturn(Attributes.newBuilder()
.set(AltsProtocolNegotiator.AUTH_CONTEXT_KEY, new AltsInternalContext(handshakerResult))
.build());
AltsContext context = AltsContextUtil.createFrom(call);
assertEquals("remote@peer", context.getPeerServiceAccount());
}
}

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

@ -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

View File

@ -68,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];
@ -147,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.

View File

@ -7,11 +7,10 @@ description = 'gRPC: Android Integration Testing'
repositories {
google()
mavenCentral()
}
android {
namespace 'io.grpc.android.integrationtest'
namespace = 'io.grpc.android.integrationtest'
sourceSets {
main {
java {
@ -42,7 +41,7 @@ android {
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
multiDexEnabled true
multiDexEnabled = true
}
buildTypes {
debug { minifyEnabled false }
@ -69,22 +68,16 @@ dependencies {
implementation project(':grpc-android'),
project(':grpc-core'),
project(':grpc-auth'),
project(':grpc-census'),
project(':grpc-okhttp'),
project(':grpc-protobuf-lite'),
project(':grpc-stub'),
project(':grpc-testing'),
libraries.hdrhistogram,
libraries.junit,
libraries.truth,
libraries.androidx.test.rules,
libraries.opencensus.contrib.grpc.metrics
implementation (libraries.google.auth.oauth2Http) {
exclude group: 'org.apache.httpcomponents'
}
implementation (project(':grpc-services')) {
exclude group: 'com.google.protobuf'
exclude group: 'com.google.guava'
@ -116,7 +109,6 @@ import net.ltgt.gradle.errorprone.CheckSeverity
tasks.withType(JavaCompile).configureEach {
options.compilerArgs += [
"-Xlint:-cast",
"-Xlint:-deprecation", // https://github.com/grpc/grpc-java/issues/10298
]
appendToProperty(it.options.errorprone.excludedPaths, ".*/R.java", "|")
appendToProperty(

View File

@ -30,6 +30,7 @@ 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.Test;
import org.junit.runner.RunWith;
@ -115,9 +116,10 @@ public class InteropInstrumentationTest {
result = executor.submit(new TestCallable(
TesterOkHttpChannelBuilder.build(host, port, serverHostOverride, useTls, testCa),
testCase)).get(TIMEOUT_SECONDS, TimeUnit.SECONDS);
assertEquals(testCase + " failed", TestCallable.SUCCESS_MESSAGE, result);
} catch (ExecutionException | InterruptedException e) {
} 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

@ -7,9 +7,6 @@ import static io.grpc.MethodDescriptor.generateFullMethodName;
* 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 {
@ -92,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
*/
@ -212,6 +224,46 @@ public final class LoadBalancerStatsServiceGrpc {
* A service used to obtain stats for verifying LB behavior.
* </pre>
*/
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(

View File

@ -4,9 +4,6 @@ import static io.grpc.MethodDescriptor.generateFullMethodName;
/**
*/
@javax.annotation.Generated(
value = "by gRPC proto compiler",
comments = "Source: grpc/testing/metrics.proto")
@io.grpc.stub.annotations.GrpcGenerated
public final class MetricsServiceGrpc {
@ -89,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
*/
@ -199,6 +211,46 @@ public final class MetricsServiceGrpc {
/**
* A stub to allow clients to do synchronous rpc calls to service MetricsService.
*/
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(

View File

@ -7,9 +7,6 @@ import static io.grpc.MethodDescriptor.generateFullMethodName;
* 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 {
@ -92,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
*/
@ -200,6 +212,40 @@ public final class ReconnectServiceGrpc {
* A service used to control reconnect server.
* </pre>
*/
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(

View File

@ -8,9 +8,6 @@ import static io.grpc.MethodDescriptor.generateFullMethodName;
* 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 {
@ -273,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
*/
@ -543,6 +555,125 @@ public final class TestServiceGrpc {
* performance with various types of payload.
* </pre>
*/
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(

View File

@ -8,9 +8,6 @@ import static io.grpc.MethodDescriptor.generateFullMethodName;
* 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 {
@ -63,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
*/
@ -166,6 +178,37 @@ public final class UnimplementedServiceGrpc {
* that case.
* </pre>
*/
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(

View File

@ -7,9 +7,6 @@ import static io.grpc.MethodDescriptor.generateFullMethodName;
* A service to dynamically update the configuration of an xDS test client.
* </pre>
*/
@javax.annotation.Generated(
value = "by gRPC proto compiler",
comments = "Source: grpc/testing/test.proto")
@io.grpc.stub.annotations.GrpcGenerated
public final class XdsUpdateClientConfigureServiceGrpc {
@ -62,6 +59,21 @@ public final class XdsUpdateClientConfigureServiceGrpc {
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
*/
@ -161,6 +173,36 @@ public final class XdsUpdateClientConfigureServiceGrpc {
* 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(

View File

@ -7,9 +7,6 @@ import static io.grpc.MethodDescriptor.generateFullMethodName;
* A service to remotely control health status of an xDS test server.
* </pre>
*/
@javax.annotation.Generated(
value = "by gRPC proto compiler",
comments = "Source: grpc/testing/test.proto")
@io.grpc.stub.annotations.GrpcGenerated
public final class XdsUpdateHealthServiceGrpc {
@ -92,6 +89,21 @@ public final class XdsUpdateHealthServiceGrpc {
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
*/
@ -200,6 +212,40 @@ public final class XdsUpdateHealthServiceGrpc {
* 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(

View File

@ -7,9 +7,6 @@ import static io.grpc.MethodDescriptor.generateFullMethodName;
* 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 {
@ -92,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
*/
@ -212,6 +224,46 @@ public final class LoadBalancerStatsServiceGrpc {
* A service used to obtain stats for verifying LB behavior.
* </pre>
*/
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(

View File

@ -4,9 +4,6 @@ import static io.grpc.MethodDescriptor.generateFullMethodName;
/**
*/
@javax.annotation.Generated(
value = "by gRPC proto compiler",
comments = "Source: grpc/testing/metrics.proto")
@io.grpc.stub.annotations.GrpcGenerated
public final class MetricsServiceGrpc {
@ -89,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
*/
@ -199,6 +211,46 @@ public final class MetricsServiceGrpc {
/**
* A stub to allow clients to do synchronous rpc calls to service MetricsService.
*/
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(

View File

@ -7,9 +7,6 @@ import static io.grpc.MethodDescriptor.generateFullMethodName;
* 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 {
@ -92,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
*/
@ -200,6 +212,40 @@ public final class ReconnectServiceGrpc {
* A service used to control reconnect server.
* </pre>
*/
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(

View File

@ -8,9 +8,6 @@ import static io.grpc.MethodDescriptor.generateFullMethodName;
* 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 {
@ -273,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
*/
@ -543,6 +555,125 @@ public final class TestServiceGrpc {
* performance with various types of payload.
* </pre>
*/
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(

View File

@ -8,9 +8,6 @@ import static io.grpc.MethodDescriptor.generateFullMethodName;
* 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 {
@ -63,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
*/
@ -166,6 +178,37 @@ public final class UnimplementedServiceGrpc {
* that case.
* </pre>
*/
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(

View File

@ -7,9 +7,6 @@ import static io.grpc.MethodDescriptor.generateFullMethodName;
* A service to dynamically update the configuration of an xDS test client.
* </pre>
*/
@javax.annotation.Generated(
value = "by gRPC proto compiler",
comments = "Source: grpc/testing/test.proto")
@io.grpc.stub.annotations.GrpcGenerated
public final class XdsUpdateClientConfigureServiceGrpc {
@ -62,6 +59,21 @@ public final class XdsUpdateClientConfigureServiceGrpc {
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
*/
@ -161,6 +173,36 @@ public final class XdsUpdateClientConfigureServiceGrpc {
* 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(

View File

@ -7,9 +7,6 @@ import static io.grpc.MethodDescriptor.generateFullMethodName;
* A service to remotely control health status of an xDS test server.
* </pre>
*/
@javax.annotation.Generated(
value = "by gRPC proto compiler",
comments = "Source: grpc/testing/test.proto")
@io.grpc.stub.annotations.GrpcGenerated
public final class XdsUpdateHealthServiceGrpc {
@ -92,6 +89,21 @@ public final class XdsUpdateHealthServiceGrpc {
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
*/
@ -200,6 +212,40 @@ public final class XdsUpdateHealthServiceGrpc {
* 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(

View File

@ -37,12 +37,15 @@
android:layout_height="wrap_content"
android:onClick="enableUds"
android:textColor="@color/focus"
android:text="Use UDS (SSL not supported)"/>
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>

View File

@ -7,20 +7,20 @@ plugins {
description = 'gRPC: Android'
android {
namespace 'io.grpc.android'
namespace = 'io.grpc.android'
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
compileSdkVersion 34
defaultConfig {
minSdkVersion 21
minSdkVersion 22
targetSdkVersion 33
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
lintOptions { abortOnError true }
lintOptions { abortOnError = true }
publishing {
singleVariant('release') {
withSourcesJar()
@ -31,7 +31,6 @@ android {
repositories {
google()
mavenCentral()
}
dependencies {

View File

@ -28,6 +28,7 @@ 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;
@ -41,7 +42,6 @@ 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
@ -217,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);
@ -231,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);

View File

@ -68,12 +68,15 @@ public final class UdsChannelBuilder {
throw new UnsupportedOperationException("OkHttpChannelBuilder not found on the classpath");
}
try {
// Target 'dns:///localhost' is unused, but necessary as an argument for OkHttpChannelBuilder.
// 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:///localhost", InsecureChannelCredentials.create());
.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)

View File

@ -1,16 +1,16 @@
load("@rules_jvm_external//:defs.bzl", "artifact")
java_library(
name = "api",
srcs = glob([
"src/main/java/**/*.java",
"src/context/java/**/*.java",
]),
javacopts = ["-Xep:DoNotCall:OFF"], # Remove once requiring Bazel 3.4.0+; allows non-final
visibility = ["//visibility:public"],
deps = [
"@com_google_code_findbugs_jsr305//jar",
"@com_google_errorprone_error_prone_annotations//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"),
],
)

View File

@ -47,15 +47,32 @@ dependencies {
testImplementation project(':grpc-core')
testImplementation project(':grpc-testing')
testImplementation libraries.guava.testlib
testImplementation libraries.truth
signature libraries.signature.java
signature libraries.signature.android
signature (libraries.signature.java) {
artifact {
extension = "signature"
}
}
signature (libraries.signature.android) {
artifact {
extension = "signature"
}
}
}
animalsniffer {
annotation = 'io.grpc.IgnoreJRERequirement'
}
tasks.named("javadoc").configure {
source sourceSets.context.allSource
// We want io.grpc.Internal, but not io.grpc.Internal*
exclude 'io/grpc/*MetricInstrument.java'
exclude 'io/grpc/*MetricInstrumentRegistry.java'
exclude 'io/grpc/Internal?*.java'
exclude 'io/grpc/MetricRecorder.java'
exclude 'io/grpc/MetricSink.java'
}
tasks.named("sourcesJar").configure {

View File

@ -16,8 +16,10 @@
package io.grpc;
import java.util.Arrays;
import static java.util.Objects.requireNonNull;
import java.util.Locale;
import java.util.Objects;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
@ -33,7 +35,7 @@ import java.util.concurrent.TimeUnit;
* passed to the various components unambiguously.
*/
public final class Deadline implements Comparable<Deadline> {
private static final SystemTicker SYSTEM_TICKER = new SystemTicker();
private static final Ticker SYSTEM_TICKER = new SystemTicker();
// nanoTime has a range of just under 300 years. Only allow up to 100 years in the past or future
// to prevent wraparound as long as process runs for less than ~100 years.
private static final long MAX_OFFSET = TimeUnit.DAYS.toNanos(100 * 365);
@ -91,7 +93,7 @@ public final class Deadline implements Comparable<Deadline> {
* @since 1.24.0
*/
public static Deadline after(long duration, TimeUnit units, Ticker ticker) {
checkNotNull(units, "units");
requireNonNull(units, "units");
return new Deadline(ticker, units.toNanos(duration), true);
}
@ -191,8 +193,8 @@ public final class Deadline implements Comparable<Deadline> {
* @return {@link ScheduledFuture} which can be used to cancel execution of the task
*/
public ScheduledFuture<?> runOnExpiration(Runnable task, ScheduledExecutorService scheduler) {
checkNotNull(task, "task");
checkNotNull(scheduler, "scheduler");
requireNonNull(task, "task");
requireNonNull(scheduler, "scheduler");
return scheduler.schedule(task, deadlineNanos - ticker.nanoTime(), TimeUnit.NANOSECONDS);
}
@ -225,37 +227,27 @@ public final class Deadline implements Comparable<Deadline> {
@Override
public int compareTo(Deadline that) {
checkTicker(that);
long diff = this.deadlineNanos - that.deadlineNanos;
if (diff < 0) {
return -1;
} else if (diff > 0) {
return 1;
}
return 0;
return Long.compare(this.deadlineNanos, that.deadlineNanos);
}
@Override
public int hashCode() {
return Arrays.asList(this.ticker, this.deadlineNanos).hashCode();
return Objects.hash(this.ticker, this.deadlineNanos);
}
@Override
public boolean equals(final Object o) {
if (o == this) {
public boolean equals(final Object object) {
if (object == this) {
return true;
}
if (!(o instanceof Deadline)) {
if (!(object instanceof Deadline)) {
return false;
}
final Deadline other = (Deadline) o;
if (this.ticker == null ? other.ticker != null : this.ticker != other.ticker) {
final Deadline that = (Deadline) object;
if (this.ticker == null ? that.ticker != null : this.ticker != that.ticker) {
return false;
}
if (this.deadlineNanos != other.deadlineNanos) {
return false;
}
return true;
return this.deadlineNanos == that.deadlineNanos;
}
/**
@ -275,24 +267,17 @@ public final class Deadline implements Comparable<Deadline> {
* @since 1.24.0
*/
public abstract static class Ticker {
/** Returns the number of nanoseconds since this source's epoch. */
/** Returns the number of nanoseconds elapsed since this ticker's reference point in time. */
public abstract long nanoTime();
}
private static class SystemTicker extends Ticker {
private static final class SystemTicker extends Ticker {
@Override
public long nanoTime() {
return System.nanoTime();
}
}
private static <T> T checkNotNull(T reference, Object errorMessage) {
if (reference == null) {
throw new NullPointerException(String.valueOf(errorMessage));
}
return reference;
}
private void checkTicker(Deadline other) {
if (ticker != other.ticker) {
throw new AssertionError(

View File

@ -236,13 +236,12 @@ public final class Attributes {
}
/**
* Removes the key and associated value from the attribtues.
* Removes the key and associated value from the attributes.
*
* @since 1.22.0
* @param key The key to remove
* @return this
*/
@ExperimentalApi("https://github.com/grpc/grpc-java/issues/5777")
public <T> Builder discard(Key<T> key) {
if (base.data.containsKey(key)) {
IdentityHashMap<Key<?>, Object> newBaseData = new IdentityHashMap<>(base.data);

View File

@ -43,7 +43,7 @@ public abstract class CallCredentials {
* <p>It is called for each individual RPC, within the {@link Context} of the call, before the
* stream is about to be created on a transport. Implementations should not block in this
* method. If metadata is not immediately available, e.g., needs to be fetched from network, the
* implementation may give the {@code applier} to an asynchronous task which will eventually call
* implementation may give the {@code appExecutor} an asynchronous task which will eventually call
* the {@code applier}. The RPC proceeds only after the {@code applier} is called.
*
* @param requestInfo request-related information

View File

@ -17,16 +17,18 @@
package io.grpc;
import static com.google.common.base.Preconditions.checkArgument;
import static io.grpc.TimeUtils.convertToNanos;
import com.google.common.base.MoreObjects;
import com.google.common.base.Preconditions;
import com.google.errorprone.annotations.CheckReturnValue;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import javax.annotation.CheckReturnValue;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
@ -79,6 +81,8 @@ public final class CallOptions {
private final Integer maxInboundMessageSize;
@Nullable
private final Integer maxOutboundMessageSize;
@Nullable
private final Integer onReadyThreshold;
private CallOptions(Builder builder) {
this.deadline = builder.deadline;
@ -91,6 +95,7 @@ public final class CallOptions {
this.waitForReady = builder.waitForReady;
this.maxInboundMessageSize = builder.maxInboundMessageSize;
this.maxOutboundMessageSize = builder.maxOutboundMessageSize;
this.onReadyThreshold = builder.onReadyThreshold;
}
static class Builder {
@ -105,6 +110,7 @@ public final class CallOptions {
Boolean waitForReady;
Integer maxInboundMessageSize;
Integer maxOutboundMessageSize;
Integer onReadyThreshold;
private CallOptions build() {
return new CallOptions(this);
@ -172,6 +178,11 @@ public final class CallOptions {
return withDeadline(Deadline.after(duration, unit));
}
@ExperimentalApi("https://github.com/grpc/grpc-java/issues/11657")
public CallOptions withDeadlineAfter(Duration duration) {
return withDeadlineAfter(convertToNanos(duration), TimeUnit.NANOSECONDS);
}
/**
* Returns the deadline or {@code null} if the deadline is not set.
*/
@ -203,6 +214,46 @@ public final class CallOptions {
return builder.build();
}
/**
* Specifies how many bytes must be queued before the call is
* considered not ready to send more messages.
*
* @param numBytes The number of bytes that must be queued. Must be a
* positive integer.
*/
@ExperimentalApi("https://github.com/grpc/grpc-java/issues/11021")
public CallOptions withOnReadyThreshold(int numBytes) {
checkArgument(numBytes > 0, "numBytes must be positive: %s", numBytes);
Builder builder = toBuilder(this);
builder.onReadyThreshold = numBytes;
return builder.build();
}
/**
* Resets to the default number of bytes that must be queued before the
* call will leave the <a href="https://github.com/grpc/grpc/blob/master/doc/wait-for-ready.md">
* 'wait for ready'</a> state.
*/
@ExperimentalApi("https://github.com/grpc/grpc-java/issues/11021")
public CallOptions clearOnReadyThreshold() {
Builder builder = toBuilder(this);
builder.onReadyThreshold = null;
return builder.build();
}
/**
* Returns to the default number of bytes that must be queued before the
* call will leave the <a href="https://github.com/grpc/grpc/blob/master/doc/wait-for-ready.md">
* 'wait for ready'</a> state.
*
* @return null if the default threshold is used.
*/
@Nullable
@ExperimentalApi("https://github.com/grpc/grpc-java/issues/11021")
public Integer getOnReadyThreshold() {
return onReadyThreshold;
}
/**
* Returns the compressor's name.
*/
@ -468,6 +519,7 @@ public final class CallOptions {
builder.waitForReady = other.waitForReady;
builder.maxInboundMessageSize = other.maxInboundMessageSize;
builder.maxOutboundMessageSize = other.maxOutboundMessageSize;
builder.onReadyThreshold = other.onReadyThreshold;
return builder;
}
@ -483,6 +535,7 @@ public final class CallOptions {
.add("waitForReady", isWaitForReady())
.add("maxInboundMessageSize", maxInboundMessageSize)
.add("maxOutboundMessageSize", maxOutboundMessageSize)
.add("onReadyThreshold", onReadyThreshold)
.add("streamTracerFactories", streamTracerFactories)
.toString();
}

View File

@ -0,0 +1,23 @@
/*
* 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;
/**
* Tagging interface for MetricInstruments that can be used with batch callbacks.
*/
@Internal
public interface CallbackMetricInstrument extends MetricInstrument {}

View File

@ -67,7 +67,7 @@ import javax.annotation.Nullable;
* manner, and notifies gRPC library to receive additional response after one is consumed by
* a fictional <code>processResponse()</code>.
*
* <p><pre>
* <pre>
* call = channel.newCall(bidiStreamingMethod, callOptions);
* listener = new ClientCall.Listener&lt;FooResponse&gt;() {
* &#64;Override

View File

@ -70,15 +70,35 @@ public abstract class ClientStreamTracer extends StreamTracer {
}
/**
* Trailing metadata has been received from the server.
* Headers has been received from the server. This method does not pass ownership to {@code
* headers}, so implementations must not access the metadata after returning. Modifications to the
* metadata within this method will be seen by interceptors and the application.
*
* @param trailers the mutable trailing metadata. Modifications to it will be seen by
* interceptors and the application.
* @param headers the received header metadata
*/
public void inboundHeaders(Metadata headers) {
inboundHeaders();
}
/**
* Trailing metadata has been received from the server. This method does not pass ownership to
* {@code trailers}, so implementations must not access the metadata after returning.
* Modifications to the metadata within this method will be seen by interceptors and the
* application.
*
* @param trailers the received trailing metadata
* @since 1.17.0
*/
public void inboundTrailers(Metadata trailers) {
}
/**
* Information providing context to the call became available.
*/
@Internal
public void addOptionalLabel(String key, String value) {
}
/**
* Factory class for {@link ClientStreamTracer}.
*/

View File

@ -0,0 +1,51 @@
/*
* Copyright 2023 The gRPC Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.grpc;
/**
* Listens on the client transport life-cycle events. These filters do not have the capability
* to modify the channels or transport life-cycle event behavior, but they can be useful hooks
* for transport observability. Multiple filters may be registered to the client.
*
* @since 1.62.0
*/
@ExperimentalApi("https://gitub.com/grpc/grpc-java/issues/10652")
public abstract class ClientTransportFilter {
/**
* Called when a transport is ready to accept traffic (when a connection has been established).
* The default implementation is a no-op.
*
* @param transportAttrs current transport attributes
*
* @return new transport attributes. Default implementation returns the passed-in attributes
* intact.
*/
public Attributes transportReady(Attributes transportAttrs) {
return transportAttrs;
}
/**
* Called when a transport completed shutting down. All resources have been released.
* All streams have either been closed or transferred off this transport.
* Default implementation is a no-op
*
* @param transportAttrs the effective transport attributes, which is what is returned by {@link
* #transportReady} of the last executed filter.
*/
public void transportTerminated(Attributes transportAttrs) {
}
}

View File

@ -0,0 +1,36 @@
/*
* 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;
/**
* Provides hooks for modifying gRPC channels and servers during their construction.
*/
interface Configurator {
/**
* Allows implementations to modify the channel builder.
*
* @param channelBuilder the channel builder being constructed
*/
default void configureChannelBuilder(ManagedChannelBuilder<?> channelBuilder) {}
/**
* Allows implementations to modify the server builder.
*
* @param serverBuilder the server builder being constructed
*/
default void configureServerBuilder(ServerBuilder<?> serverBuilder) {}
}

View File

@ -0,0 +1,87 @@
/*
* 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;
import com.google.errorprone.annotations.concurrent.GuardedBy;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* A registry for {@link Configurator} instances.
*
* <p>This class is responsible for maintaining a list of configurators and providing access to
* them. The default registry can be obtained using {@link #getDefaultRegistry()}.
*/
final class ConfiguratorRegistry {
private static ConfiguratorRegistry instance;
@GuardedBy("this")
private boolean wasConfiguratorsSet;
@GuardedBy("this")
private List<Configurator> configurators = Collections.emptyList();
@GuardedBy("this")
private int configuratorsCallCountBeforeSet = 0;
ConfiguratorRegistry() {}
/**
* Returns the default global instance of the configurator registry.
*/
public static synchronized ConfiguratorRegistry getDefaultRegistry() {
if (instance == null) {
instance = new ConfiguratorRegistry();
}
return instance;
}
/**
* Sets the configurators in this registry. This method can only be called once.
*
* @param configurators the configurators to set
* @throws IllegalStateException if this method is called more than once
*/
public synchronized void setConfigurators(List<? extends Configurator> configurators) {
if (wasConfiguratorsSet) {
throw new IllegalStateException("Configurators are already set");
}
this.configurators = Collections.unmodifiableList(new ArrayList<>(configurators));
wasConfiguratorsSet = true;
}
/**
* Returns a list of the configurators in this registry.
*/
public synchronized List<Configurator> getConfigurators() {
if (!wasConfiguratorsSet) {
configuratorsCallCountBeforeSet++;
}
return configurators;
}
/**
* Returns the number of times getConfigurators() was called before
* setConfigurators() was successfully invoked.
*/
public synchronized int getConfiguratorsCallCountBeforeSet() {
return configuratorsCallCountBeforeSet;
}
public synchronized boolean wasSetConfiguratorsCalled() {
return wasConfiguratorsSet;
}
}

View File

@ -0,0 +1,30 @@
/*
* 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;
import java.util.List;
/**
* Represents a double-valued counter metric instrument.
*/
@Internal
public final class DoubleCounterMetricInstrument extends PartialMetricInstrument {
public DoubleCounterMetricInstrument(int index, String name, String description, String unit,
List<String> requiredLabelKeys, List<String> optionalLabelKeys, boolean enableByDefault) {
super(index, name, description, unit, requiredLabelKeys, optionalLabelKeys, enableByDefault);
}
}

View File

@ -0,0 +1,38 @@
/*
* 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;
import java.util.List;
/**
* Represents a double-valued histogram metric instrument.
*/
@Internal
public final class DoubleHistogramMetricInstrument extends PartialMetricInstrument {
private final List<Double> bucketBoundaries;
public DoubleHistogramMetricInstrument(int index, String name, String description, String unit,
List<Double> bucketBoundaries, List<String> requiredLabelKeys, List<String> optionalLabelKeys,
boolean enableByDefault) {
super(index, name, description, unit, requiredLabelKeys, optionalLabelKeys, enableByDefault);
this.bucketBoundaries = bucketBoundaries;
}
public List<Double> getBucketBoundaries() {
return bucketBoundaries;
}
}

View File

@ -94,6 +94,18 @@ public abstract class ForwardingChannelBuilder2<T extends ManagedChannelBuilder<
return thisT();
}
@Override
protected T interceptWithTarget(InterceptorFactory factory) {
delegate().interceptWithTarget(factory);
return thisT();
}
@Override
public T addTransportFilter(ClientTransportFilter transportFilter) {
delegate().addTransportFilter(transportFilter);
return thisT();
}
@Override
public T userAgent(String userAgent) {
delegate().userAgent(userAgent);
@ -245,6 +257,18 @@ public abstract class ForwardingChannelBuilder2<T extends ManagedChannelBuilder<
return thisT();
}
@Override
protected T addMetricSink(MetricSink metricSink) {
delegate().addMetricSink(metricSink);
return thisT();
}
@Override
public <X> T setNameResolverArg(NameResolver.Args.Key<X> key, X value) {
delegate().setNameResolverArg(key, value);
return thisT();
}
/**
* Returns the {@link ManagedChannel} built by the delegate by default. Overriding method can
* return different value.

View File

@ -1,93 +0,0 @@
/*
* Copyright 2022 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;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/** The collection of global interceptors and global server stream tracers. */
@Internal
final class GlobalInterceptors {
private static List<ClientInterceptor> clientInterceptors = null;
private static List<ServerInterceptor> serverInterceptors = null;
private static List<ServerStreamTracer.Factory> serverStreamTracerFactories =
null;
private static boolean isGlobalInterceptorsTracersSet;
private static boolean isGlobalInterceptorsTracersGet;
// Prevent instantiation
private GlobalInterceptors() {}
/**
* Sets the list of global interceptors and global server stream tracers.
*
* <p>If {@code setInterceptorsTracers()} is called again, this method will throw {@link
* IllegalStateException}.
*
* <p>It is only safe to call early. This method throws {@link IllegalStateException} after any of
* the get calls [{@link #getClientInterceptors()}, {@link #getServerInterceptors()} or {@link
* #getServerStreamTracerFactories()}] has been called, in order to limit changes to the result of
* {@code setInterceptorsTracers()}.
*
* @param clientInterceptorList list of {@link ClientInterceptor} that make up global Client
* Interceptors.
* @param serverInterceptorList list of {@link ServerInterceptor} that make up global Server
* Interceptors.
* @param serverStreamTracerFactoryList list of {@link ServerStreamTracer.Factory} that make up
* global ServerStreamTracer factories.
*/
static synchronized void setInterceptorsTracers(
List<ClientInterceptor> clientInterceptorList,
List<ServerInterceptor> serverInterceptorList,
List<ServerStreamTracer.Factory> serverStreamTracerFactoryList) {
if (isGlobalInterceptorsTracersGet) {
throw new IllegalStateException("Set cannot be called after any get call");
}
if (isGlobalInterceptorsTracersSet) {
throw new IllegalStateException("Global interceptors and tracers are already set");
}
checkNotNull(clientInterceptorList);
checkNotNull(serverInterceptorList);
checkNotNull(serverStreamTracerFactoryList);
clientInterceptors = Collections.unmodifiableList(new ArrayList<>(clientInterceptorList));
serverInterceptors = Collections.unmodifiableList(new ArrayList<>(serverInterceptorList));
serverStreamTracerFactories =
Collections.unmodifiableList(new ArrayList<>(serverStreamTracerFactoryList));
isGlobalInterceptorsTracersSet = true;
}
/** Returns the list of global {@link ClientInterceptor}. If not set, this returns null. */
static synchronized List<ClientInterceptor> getClientInterceptors() {
isGlobalInterceptorsTracersGet = true;
return clientInterceptors;
}
/** Returns list of global {@link ServerInterceptor}. If not set, this returns null. */
static synchronized List<ServerInterceptor> getServerInterceptors() {
isGlobalInterceptorsTracersGet = true;
return serverInterceptors;
}
/** Returns list of global {@link ServerStreamTracer.Factory}. If not set, this returns null. */
static synchronized List<ServerStreamTracer.Factory> getServerStreamTracerFactories() {
isGlobalInterceptorsTracersGet = true;
return serverStreamTracerFactories;
}
}

View File

@ -0,0 +1,30 @@
/*
* 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;
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
/**
* Disables Animal Sniffer's signature checking. This is our own package-private version to avoid
* dependening on animalsniffer-annotations.
*
* <p>FIELD is purposefully not supported, as Android wouldn't be able to ignore a field. Instead,
* the entire class would need to be avoided on Android.
*/
@Target({ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.TYPE})
@interface IgnoreJRERequirement {}

View File

@ -35,7 +35,7 @@ public abstract class InternalConfigSelector {
= Attributes.Key.create("internal:io.grpc.config-selector");
// Use PickSubchannelArgs for SelectConfigArgs for now. May change over time.
/** Selects the config for an PRC. */
/** Selects the config for an RPC. */
public abstract Result selectConfig(LoadBalancer.PickSubchannelArgs args);
public static final class Result {

View File

@ -0,0 +1,23 @@
/*
* 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;
/**
* Internal access to Configurator API.
*/
@Internal
public interface InternalConfigurator extends Configurator {}

View File

@ -0,0 +1,55 @@
/*
* 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;
import java.util.List;
/**
* Access internal global configurators.
*/
@Internal
public final class InternalConfiguratorRegistry {
private InternalConfiguratorRegistry() {}
public static void setConfigurators(List<InternalConfigurator> configurators) {
ConfiguratorRegistry.getDefaultRegistry().setConfigurators(configurators);
}
public static List<?> getConfigurators() {
return ConfiguratorRegistry.getDefaultRegistry().getConfigurators();
}
public static void configureChannelBuilder(ManagedChannelBuilder<?> channelBuilder) {
for (Configurator configurator : ConfiguratorRegistry.getDefaultRegistry().getConfigurators()) {
configurator.configureChannelBuilder(channelBuilder);
}
}
public static void configureServerBuilder(ServerBuilder<?> serverBuilder) {
for (Configurator configurator : ConfiguratorRegistry.getDefaultRegistry().getConfigurators()) {
configurator.configureServerBuilder(serverBuilder);
}
}
public static boolean wasSetConfiguratorsCalled() {
return ConfiguratorRegistry.getDefaultRegistry().wasSetConfiguratorsCalled();
}
public static int getConfiguratorsCallCountBeforeSet() {
return ConfiguratorRegistry.getDefaultRegistry().getConfiguratorsCallCountBeforeSet();
}
}

View File

@ -1,46 +0,0 @@
/*
* Copyright 2022 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;
import java.util.List;
/** Accessor to internal methods of {@link GlobalInterceptors}. */
@Internal
public final class InternalGlobalInterceptors {
public static void setInterceptorsTracers(
List<ClientInterceptor> clientInterceptorList,
List<ServerInterceptor> serverInterceptorList,
List<ServerStreamTracer.Factory> serverStreamTracerFactoryList) {
GlobalInterceptors.setInterceptorsTracers(
clientInterceptorList, serverInterceptorList, serverStreamTracerFactoryList);
}
public static List<ClientInterceptor> getClientInterceptors() {
return GlobalInterceptors.getClientInterceptors();
}
public static List<ServerInterceptor> getServerInterceptors() {
return GlobalInterceptors.getServerInterceptors();
}
public static List<ServerStreamTracer.Factory> getServerStreamTracerFactories() {
return GlobalInterceptors.getServerStreamTracerFactories();
}
private InternalGlobalInterceptors() {}
}

View File

@ -0,0 +1,37 @@
/*
* 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;
/**
* Internal accessors for {@link ManagedChannelBuilder}.
*/
@Internal
public final class InternalManagedChannelBuilder {
private InternalManagedChannelBuilder() {}
public static <T extends ManagedChannelBuilder<T>> T interceptWithTarget(
ManagedChannelBuilder<T> builder, InternalInterceptorFactory factory) {
return builder.interceptWithTarget(factory);
}
public static <T extends ManagedChannelBuilder<T>> T addMetricSink(
ManagedChannelBuilder<T> builder, MetricSink metricSink) {
return builder.addMetricSink(metricSink);
}
public interface InternalInterceptorFactory extends ManagedChannelBuilder.InterceptorFactory {}
}

View File

@ -30,10 +30,12 @@ public final class InternalMethodDescriptor {
this.transport = checkNotNull(transport, "transport");
}
@SuppressWarnings("EnumOrdinal")
public Object geRawMethodName(MethodDescriptor<?, ?> descriptor) {
return descriptor.getRawMethodName(transport.ordinal());
}
@SuppressWarnings("EnumOrdinal")
public void setRawMethodName(MethodDescriptor<?, ?> descriptor, Object o) {
descriptor.setRawMethodName(transport.ordinal(), o);
}

View File

@ -38,12 +38,11 @@ public final class InternalStatus {
public static final Metadata.Key<Status> CODE_KEY = Status.CODE_KEY;
/**
* Create a new {@link StatusRuntimeException} with the internal option of skipping the filling
* of the stack trace.
* Create a new {@link StatusRuntimeException} skipping the filling of the stack trace.
*/
@Internal
public static final StatusRuntimeException asRuntimeException(Status status,
@Nullable Metadata trailers, boolean fillInStackTrace) {
return new StatusRuntimeException(status, trailers, fillInStackTrace);
public static StatusRuntimeException asRuntimeExceptionWithoutStacktrace(Status status,
@Nullable Metadata trailers) {
return new InternalStatusRuntimeException(status, trailers);
}
}

View File

@ -0,0 +1,39 @@
/*
* Copyright 2015 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;
import javax.annotation.Nullable;
/**
* StatusRuntimeException without stack trace, implemented as a subclass, as the
* {@code String, Throwable, boolean, boolean} constructor is not available in the supported
* version of Android.
*
* @see StatusRuntimeException
*/
class InternalStatusRuntimeException extends StatusRuntimeException {
private static final long serialVersionUID = 0;
public InternalStatusRuntimeException(Status status, @Nullable Metadata trailers) {
super(status, trailers);
}
@Override
public synchronized Throwable fillInStackTrace() {
return this;
}
}

View File

@ -0,0 +1,31 @@
/*
* 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;
/**
* An internal class. Do not use.
*
* <p>An interface to provide the attributes for address connected by subchannel.
*/
@Internal
public interface InternalSubchannelAddressAttributes {
/**
* Return attributes of the server address connected by sub channel.
*/
public Attributes getConnectedAddressAttributes();
}

View File

@ -0,0 +1,26 @@
/*
* 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;
import java.time.Duration;
@Internal
public final class InternalTimeUtils {
public static long convert(Duration duration) {
return TimeUtils.convertToNanos(duration);
}
}

View File

@ -121,6 +121,12 @@ public abstract class LoadBalancer {
HEALTH_CONSUMER_LISTENER_ARG_KEY =
LoadBalancer.CreateSubchannelArgs.Key.create("internal:health-check-consumer-listener");
@Internal
public static final LoadBalancer.CreateSubchannelArgs.Key<Boolean>
DISABLE_SUBCHANNEL_RECONNECT_KEY =
LoadBalancer.CreateSubchannelArgs.Key.createWithDefault(
"internal:disable-subchannel-reconnect", Boolean.FALSE);
@Internal
public static final Attributes.Key<Boolean>
HAS_HEALTH_PRODUCER_LISTENER_KEY =
@ -206,7 +212,7 @@ public abstract class LoadBalancer {
*
* @since 1.21.0
*/
@ExperimentalApi("https://github.com/grpc/grpc-java/issues/1771")
@ExperimentalApi("https://github.com/grpc/grpc-java/issues/11657")
public static final class ResolvedAddresses {
private final List<EquivalentAddressGroup> addresses;
@NameResolver.ResolutionResultAttr
@ -446,18 +452,6 @@ public abstract class LoadBalancer {
* @since 1.3.0
*/
public abstract PickResult pickSubchannel(PickSubchannelArgs args);
/**
* Tries to establish connections now so that the upcoming RPC may then just pick a ready
* connection without having to connect first.
*
* <p>No-op if unsupported.
*
* @deprecated override {@link LoadBalancer#requestConnection} instead.
* @since 1.11.0
*/
@Deprecated
public void requestConnection() {}
}
/**
@ -490,6 +484,29 @@ public abstract class LoadBalancer {
* @since 1.2.0
*/
public abstract MethodDescriptor<?, ?> getMethodDescriptor();
/**
* Gets an object that can be informed about what sort of pick was made.
*/
@Internal
public PickDetailsConsumer getPickDetailsConsumer() {
return new PickDetailsConsumer() {};
}
}
/** Receives information about the pick being chosen. */
@Internal
public interface PickDetailsConsumer {
/**
* Optional labels that provide context of how the pick was routed. Particularly helpful for
* per-RPC metrics.
*
* @throws NullPointerException if key or value is {@code null}
*/
default void addOptionalLabel(String key, String value) {
checkNotNull(key, "key");
checkNotNull(value, "value");
}
}
/**
@ -523,6 +540,7 @@ public abstract class LoadBalancer {
private final Status status;
// True if the result is created by withDrop()
private final boolean drop;
@Nullable private final String authorityOverride;
private PickResult(
@Nullable Subchannel subchannel, @Nullable ClientStreamTracer.Factory streamTracerFactory,
@ -531,6 +549,17 @@ public abstract class LoadBalancer {
this.streamTracerFactory = streamTracerFactory;
this.status = checkNotNull(status, "status");
this.drop = drop;
this.authorityOverride = null;
}
private PickResult(
@Nullable Subchannel subchannel, @Nullable ClientStreamTracer.Factory streamTracerFactory,
Status status, boolean drop, @Nullable String authorityOverride) {
this.subchannel = subchannel;
this.streamTracerFactory = streamTracerFactory;
this.status = checkNotNull(status, "status");
this.drop = drop;
this.authorityOverride = authorityOverride;
}
/**
@ -610,6 +639,19 @@ public abstract class LoadBalancer {
false);
}
/**
* Same as {@code withSubchannel(subchannel, streamTracerFactory)} but with an authority name
* to override in the host header.
*/
@ExperimentalApi("https://github.com/grpc/grpc-java/issues/11656")
public static PickResult withSubchannel(
Subchannel subchannel, @Nullable ClientStreamTracer.Factory streamTracerFactory,
@Nullable String authorityOverride) {
return new PickResult(
checkNotNull(subchannel, "subchannel"), streamTracerFactory, Status.OK,
false, authorityOverride);
}
/**
* Equivalent to {@code withSubchannel(subchannel, null)}.
*
@ -653,6 +695,13 @@ public abstract class LoadBalancer {
return NO_RESULT;
}
/** Returns the authority override if any. */
@ExperimentalApi("https://github.com/grpc/grpc-java/issues/11656")
@Nullable
public String getAuthorityOverride() {
return authorityOverride;
}
/**
* The Subchannel if this result was created by {@link #withSubchannel withSubchannel()}, or
* null otherwise.
@ -693,6 +742,13 @@ public abstract class LoadBalancer {
return drop;
}
/**
* Returns {@code true} if the pick was not created with {@link #withNoResult()}.
*/
public boolean hasResult() {
return !(subchannel == null && status.isOk());
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
@ -700,6 +756,7 @@ public abstract class LoadBalancer {
.add("streamTracerFactory", streamTracerFactory)
.add("status", status)
.add("drop", drop)
.add("authority-override", authorityOverride)
.toString();
}
@ -955,6 +1012,8 @@ public abstract class LoadBalancer {
*
* <p>It must be called from {@link #getSynchronizationContext the Synchronization Context}
*
* @return Must return a valid Subchannel object, may not return null.
*
* @since 1.22.0
*/
public Subchannel createSubchannel(CreateSubchannelArgs args) {
@ -962,8 +1021,8 @@ public abstract class LoadBalancer {
}
/**
* Out-of-band channel for LoadBalancers own RPC needs, e.g., talking to an external
* load-balancer service.
* Create an out-of-band channel for the LoadBalancers own RPC needs, e.g., talking to an
* external load-balancer service.
*
* <p>The LoadBalancer is responsible for closing unused OOB channels, and closing all OOB
* channels within {@link #shutdown}.
@ -973,7 +1032,12 @@ public abstract class LoadBalancer {
public abstract ManagedChannel createOobChannel(EquivalentAddressGroup eag, String authority);
/**
* Accept a list of EAG for multiple authorities: https://github.com/grpc/grpc-java/issues/4618
* Create an out-of-band channel for the LoadBalancer's own RPC needs, e.g., talking to an
* external load-balancer service. This version of the method allows multiple EAGs, so different
* addresses can have different authorities.
*
* <p>The LoadBalancer is responsible for closing unused OOB channels, and closing all OOB
* channels within {@link #shutdown}.
* */
public ManagedChannel createOobChannel(List<EquivalentAddressGroup> eag,
String authority) {
@ -1125,6 +1189,10 @@ public abstract class LoadBalancer {
* Returns a {@link SynchronizationContext} that runs tasks in the same Synchronization Context
* as that the callback methods on the {@link LoadBalancer} interface are run in.
*
* <p>Work added to the synchronization context might not run immediately, so LB implementations
* must be careful to ensure that any assumptions still hold when it is executed. In particular,
* the LB might have been shut down or subchannels might have changed state.
*
* <p>Pro-tip: in order to call {@link SynchronizationContext#schedule}, you need to provide a
* {@link ScheduledExecutorService}. {@link #getScheduledExecutorService} is provided for your
* convenience.
@ -1160,6 +1228,13 @@ public abstract class LoadBalancer {
*/
public abstract String getAuthority();
/**
* Returns the target string of the channel, guaranteed to include its scheme.
*/
public String getChannelTarget() {
throw new UnsupportedOperationException();
}
/**
* Returns the ChannelCredentials used to construct the channel, without bearer tokens.
*
@ -1210,6 +1285,16 @@ public abstract class LoadBalancer {
public NameResolverRegistry getNameResolverRegistry() {
throw new UnsupportedOperationException();
}
/**
* Returns the {@link MetricRecorder} that the channel uses to record metrics.
*
* @since 1.64.0
*/
@Internal
public MetricRecorder getMetricRecorder() {
return new MetricRecorder() {};
}
}
/**
@ -1287,7 +1372,8 @@ public abstract class LoadBalancer {
*/
public final EquivalentAddressGroup getAddresses() {
List<EquivalentAddressGroup> groups = getAllAddresses();
Preconditions.checkState(groups.size() == 1, "%s does not have exactly one group", groups);
Preconditions.checkState(groups != null && groups.size() == 1,
"%s does not have exactly one group", groups);
return groups.get(0);
}
@ -1378,6 +1464,18 @@ public abstract class LoadBalancer {
public Object getInternalSubchannel() {
throw new UnsupportedOperationException();
}
/**
* (Internal use only) returns attributes of the address subchannel is connected to.
*
* <p>Warning: this is INTERNAL API, is not supposed to be used by external users, and may
* change without notice. If you think you must use it, please file an issue and we can consider
* removing its "internal" status.
*/
@Internal
public Attributes getConnectedAddressAttributes() {
throw new UnsupportedOperationException();
}
}
/**
@ -1476,5 +1574,19 @@ public abstract class LoadBalancer {
public String toString() {
return "FixedResultPicker(" + result + ")";
}
@Override
public int hashCode() {
return result.hashCode();
}
@Override
public boolean equals(Object o) {
if (!(o instanceof FixedResultPicker)) {
return false;
}
FixedResultPicker that = (FixedResultPicker) o;
return this.result.equals(that.result);
}
}
}

View File

@ -0,0 +1,30 @@
/*
* 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;
import java.util.List;
/**
* Represents a long-valued counter metric instrument.
*/
@Internal
public final class LongCounterMetricInstrument extends PartialMetricInstrument {
public LongCounterMetricInstrument(int index, String name, String description, String unit,
List<String> requiredLabelKeys, List<String> optionalLabelKeys, boolean enableByDefault) {
super(index, name, description, unit, requiredLabelKeys, optionalLabelKeys, enableByDefault);
}
}

View File

@ -0,0 +1,31 @@
/*
* 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;
import java.util.List;
/**
* Represents a long-valued gauge metric instrument.
*/
@Internal
public final class LongGaugeMetricInstrument extends PartialMetricInstrument
implements CallbackMetricInstrument {
public LongGaugeMetricInstrument(int index, String name, String description, String unit,
List<String> requiredLabelKeys, List<String> optionalLabelKeys, boolean enableByDefault) {
super(index, name, description, unit, requiredLabelKeys, optionalLabelKeys, enableByDefault);
}
}

View File

@ -0,0 +1,38 @@
/*
* 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;
import java.util.List;
/**
* Represents a long-valued histogram metric instrument.
*/
@Internal
public final class LongHistogramMetricInstrument extends PartialMetricInstrument {
private final List<Long> bucketBoundaries;
public LongHistogramMetricInstrument(int index, String name, String description, String unit,
List<Long> bucketBoundaries, List<String> requiredLabelKeys, List<String> optionalLabelKeys,
boolean enableByDefault) {
super(index, name, description, unit, requiredLabelKeys, optionalLabelKeys, enableByDefault);
this.bucketBoundaries = bucketBoundaries;
}
public List<Long> getBucketBoundaries() {
return bucketBoundaries;
}
}

View File

@ -159,6 +159,33 @@ public abstract class ManagedChannelBuilder<T extends ManagedChannelBuilder<T>>
*/
public abstract T intercept(ClientInterceptor... interceptors);
/**
* Internal-only: Adds a factory that will construct an interceptor based on the channel's target.
* This can be used to work around nameResolverFactory() changing the target string.
*/
@Internal
protected T interceptWithTarget(InterceptorFactory factory) {
throw new UnsupportedOperationException();
}
/** Internal-only. */
@Internal
protected interface InterceptorFactory {
ClientInterceptor newInterceptor(String target);
}
/**
* Adds a {@link ClientTransportFilter}. The order of filters being added is the order they will
* be executed
*
* @return this
* @since 1.60.0
*/
@ExperimentalApi("https://github.com/grpc/grpc-java/issues/10652")
public T addTransportFilter(ClientTransportFilter filter) {
throw new UnsupportedOperationException();
}
/**
* Provides a custom {@code User-Agent} for the application.
*
@ -595,6 +622,35 @@ public abstract class ManagedChannelBuilder<T extends ManagedChannelBuilder<T>>
throw new UnsupportedOperationException();
}
/**
* Adds a {@link MetricSink} for channel to use for configuring and recording metrics.
*
* @return this
* @since 1.64.0
*/
@Internal
protected T addMetricSink(MetricSink metricSink) {
throw new UnsupportedOperationException();
}
/**
* Provides a "custom" argument for the {@link NameResolver}, if applicable, replacing any 'value'
* previously provided for 'key'.
*
* <p>NB: If the selected {@link NameResolver} does not understand 'key', or target URI resolution
* isn't needed at all, your custom argument will be silently ignored.
*
* <p>See {@link NameResolver.Args#getArg(NameResolver.Args.Key)} for more.
*
* @param key identifies the argument in a type-safe manner
* @param value the argument itself
* @return this
*/
@ExperimentalApi("https://github.com/grpc/grpc-java/issues/1770")
public <X> T setNameResolverArg(NameResolver.Args.Key<X> key, X value) {
throw new UnsupportedOperationException();
}
/**
* Builds a channel using the given parameters.
*

View File

@ -18,6 +18,7 @@ package io.grpc;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.errorprone.annotations.concurrent.GuardedBy;
import java.net.SocketAddress;
import java.net.URI;
import java.net.URISyntaxException;
@ -30,7 +31,6 @@ import java.util.LinkedHashSet;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.concurrent.GuardedBy;
import javax.annotation.concurrent.ThreadSafe;
/**

View File

@ -16,12 +16,14 @@
package io.grpc;
import static com.google.common.base.Charsets.US_ASCII;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.nio.charset.StandardCharsets.US_ASCII;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.common.io.BaseEncoding;
import com.google.common.io.ByteStreams;
import java.io.ByteArrayInputStream;
@ -32,8 +34,6 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
@ -325,7 +325,7 @@ public final class Metadata {
if (isEmpty()) {
return Collections.emptySet();
}
Set<String> ks = new HashSet<>(size);
Set<String> ks = Sets.newHashSetWithExpectedSize(size);
for (int i = 0; i < size; i++) {
ks.add(new String(name(i), 0 /* hibyte */));
}
@ -526,7 +526,7 @@ public final class Metadata {
public void merge(Metadata other, Set<Key<?>> keys) {
Preconditions.checkNotNull(other, "other");
// Use ByteBuffer for equals and hashCode.
Map<ByteBuffer, Key<?>> asciiKeys = new HashMap<>(keys.size());
Map<ByteBuffer, Key<?>> asciiKeys = Maps.newHashMapWithExpectedSize(keys.size());
for (Key<?> key : keys) {
asciiKeys.put(ByteBuffer.wrap(key.asciiName()), key);
}

View File

@ -20,9 +20,9 @@ import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.base.MoreObjects;
import com.google.common.base.Preconditions;
import com.google.errorprone.annotations.CheckReturnValue;
import java.io.InputStream;
import java.util.concurrent.atomic.AtomicReferenceArray;
import javax.annotation.CheckReturnValue;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
@ -158,7 +158,7 @@ public final class MethodDescriptor<ReqT, RespT> {
}
/**
* A marshaller that supports retrieving it's type parameter {@code T} at runtime.
* A marshaller that supports retrieving its type parameter {@code T} at runtime.
*
* @since 1.1.0
*/

View File

@ -0,0 +1,75 @@
/*
* 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;
import java.util.List;
/**
* Represents a metric instrument. Metric instrument contains information used to describe a metric.
*/
@Internal
public interface MetricInstrument {
/**
* Returns the unique index of this metric instrument.
*
* @return the index of the metric instrument.
*/
public int getIndex();
/**
* Returns the name of the metric.
*
* @return the name of the metric.
*/
public String getName();
/**
* Returns a description of the metric.
*
* @return a description of the metric.
*/
public String getDescription();
/**
* Returns the unit of measurement for the metric.
*
* @return the unit of measurement.
*/
public String getUnit();
/**
* Returns a list of required label keys for this metric instrument.
*
* @return a list of required label keys.
*/
public List<String> getRequiredLabelKeys();
/**
* Returns a list of optional label keys for this metric instrument.
*
* @return a list of optional label keys.
*/
public List<String> getOptionalLabelKeys();
/**
* Indicates whether this metric instrument is enabled by default.
*
* @return {@code true} if this metric instrument is enabled by default,
* {@code false} otherwise.
*/
public boolean isEnableByDefault();
}

View File

@ -0,0 +1,276 @@
/*
* 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;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Strings;
import com.google.errorprone.annotations.concurrent.GuardedBy;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* A registry for globally registered metric instruments.
*/
@Internal
public final class MetricInstrumentRegistry {
static final int INITIAL_INSTRUMENT_CAPACITY = 5;
private static MetricInstrumentRegistry instance;
private final Object lock = new Object();
@GuardedBy("lock")
private final Set<String> registeredMetricNames = new HashSet<>();
@GuardedBy("lock")
private MetricInstrument[] metricInstruments =
new MetricInstrument[INITIAL_INSTRUMENT_CAPACITY];
@GuardedBy("lock")
private int nextAvailableMetricIndex;
@VisibleForTesting
MetricInstrumentRegistry() {}
/**
* Returns the default metric instrument registry.
*/
public static synchronized MetricInstrumentRegistry getDefaultRegistry() {
if (instance == null) {
instance = new MetricInstrumentRegistry();
}
return instance;
}
/**
* Returns a list of registered metric instruments.
*/
public List<MetricInstrument> getMetricInstruments() {
synchronized (lock) {
return Collections.unmodifiableList(
Arrays.asList(Arrays.copyOfRange(metricInstruments, 0, nextAvailableMetricIndex)));
}
}
/**
* Registers a new Double Counter metric instrument.
*
* @param name the name of the metric
* @param description a description of the metric
* @param unit the unit of measurement for the metric
* @param requiredLabelKeys a list of required label keys
* @param optionalLabelKeys a list of optional label keys
* @param enableByDefault whether the metric should be enabled by default
* @return the newly created DoubleCounterMetricInstrument
* @throws IllegalStateException if a metric with the same name already exists
*/
public DoubleCounterMetricInstrument registerDoubleCounter(String name,
String description, String unit, List<String> requiredLabelKeys,
List<String> optionalLabelKeys, boolean enableByDefault) {
checkArgument(!Strings.isNullOrEmpty(name), "missing metric name");
checkNotNull(description, "description");
checkNotNull(unit, "unit");
checkNotNull(requiredLabelKeys, "requiredLabelKeys");
checkNotNull(optionalLabelKeys, "optionalLabelKeys");
synchronized (lock) {
if (registeredMetricNames.contains(name)) {
throw new IllegalStateException("Metric with name " + name + " already exists");
}
int index = nextAvailableMetricIndex;
if (index + 1 == metricInstruments.length) {
resizeMetricInstruments();
}
// TODO(dnvindhya): add limit for number of optional labels allowed
DoubleCounterMetricInstrument instrument = new DoubleCounterMetricInstrument(
index, name, description, unit, requiredLabelKeys, optionalLabelKeys,
enableByDefault);
metricInstruments[index] = instrument;
registeredMetricNames.add(name);
nextAvailableMetricIndex += 1;
return instrument;
}
}
/**
* Registers a new Long Counter metric instrument.
*
* @param name the name of the metric
* @param description a description of the metric
* @param unit the unit of measurement for the metric
* @param requiredLabelKeys a list of required label keys
* @param optionalLabelKeys a list of optional label keys
* @param enableByDefault whether the metric should be enabled by default
* @return the newly created LongCounterMetricInstrument
* @throws IllegalStateException if a metric with the same name already exists
*/
public LongCounterMetricInstrument registerLongCounter(String name,
String description, String unit, List<String> requiredLabelKeys,
List<String> optionalLabelKeys, boolean enableByDefault) {
checkArgument(!Strings.isNullOrEmpty(name), "missing metric name");
checkNotNull(description, "description");
checkNotNull(unit, "unit");
checkNotNull(requiredLabelKeys, "requiredLabelKeys");
checkNotNull(optionalLabelKeys, "optionalLabelKeys");
synchronized (lock) {
if (registeredMetricNames.contains(name)) {
throw new IllegalStateException("Metric with name " + name + " already exists");
}
int index = nextAvailableMetricIndex;
if (index + 1 == metricInstruments.length) {
resizeMetricInstruments();
}
LongCounterMetricInstrument instrument = new LongCounterMetricInstrument(
index, name, description, unit, requiredLabelKeys, optionalLabelKeys,
enableByDefault);
metricInstruments[index] = instrument;
registeredMetricNames.add(name);
nextAvailableMetricIndex += 1;
return instrument;
}
}
/**
* Registers a new Double Histogram metric instrument.
*
* @param name the name of the metric
* @param description a description of the metric
* @param unit the unit of measurement for the metric
* @param bucketBoundaries recommended set of explicit bucket boundaries for the histogram
* @param requiredLabelKeys a list of required label keys
* @param optionalLabelKeys a list of optional label keys
* @param enableByDefault whether the metric should be enabled by default
* @return the newly created DoubleHistogramMetricInstrument
* @throws IllegalStateException if a metric with the same name already exists
*/
public DoubleHistogramMetricInstrument registerDoubleHistogram(String name,
String description, String unit, List<Double> bucketBoundaries,
List<String> requiredLabelKeys, List<String> optionalLabelKeys, boolean enableByDefault) {
checkArgument(!Strings.isNullOrEmpty(name), "missing metric name");
checkNotNull(description, "description");
checkNotNull(unit, "unit");
checkNotNull(bucketBoundaries, "bucketBoundaries");
checkNotNull(requiredLabelKeys, "requiredLabelKeys");
checkNotNull(optionalLabelKeys, "optionalLabelKeys");
synchronized (lock) {
if (registeredMetricNames.contains(name)) {
throw new IllegalStateException("Metric with name " + name + " already exists");
}
int index = nextAvailableMetricIndex;
if (index + 1 == metricInstruments.length) {
resizeMetricInstruments();
}
DoubleHistogramMetricInstrument instrument = new DoubleHistogramMetricInstrument(
index, name, description, unit, bucketBoundaries, requiredLabelKeys,
optionalLabelKeys,
enableByDefault);
metricInstruments[index] = instrument;
registeredMetricNames.add(name);
nextAvailableMetricIndex += 1;
return instrument;
}
}
/**
* Registers a new Long Histogram metric instrument.
*
* @param name the name of the metric
* @param description a description of the metric
* @param unit the unit of measurement for the metric
* @param bucketBoundaries recommended set of explicit bucket boundaries for the histogram
* @param requiredLabelKeys a list of required label keys
* @param optionalLabelKeys a list of optional label keys
* @param enableByDefault whether the metric should be enabled by default
* @return the newly created LongHistogramMetricInstrument
* @throws IllegalStateException if a metric with the same name already exists
*/
public LongHistogramMetricInstrument registerLongHistogram(String name,
String description, String unit, List<Long> bucketBoundaries, List<String> requiredLabelKeys,
List<String> optionalLabelKeys, boolean enableByDefault) {
checkArgument(!Strings.isNullOrEmpty(name), "missing metric name");
checkNotNull(description, "description");
checkNotNull(unit, "unit");
checkNotNull(bucketBoundaries, "bucketBoundaries");
checkNotNull(requiredLabelKeys, "requiredLabelKeys");
checkNotNull(optionalLabelKeys, "optionalLabelKeys");
synchronized (lock) {
if (registeredMetricNames.contains(name)) {
throw new IllegalStateException("Metric with name " + name + " already exists");
}
int index = nextAvailableMetricIndex;
if (index + 1 == metricInstruments.length) {
resizeMetricInstruments();
}
LongHistogramMetricInstrument instrument = new LongHistogramMetricInstrument(
index, name, description, unit, bucketBoundaries, requiredLabelKeys,
optionalLabelKeys,
enableByDefault);
metricInstruments[index] = instrument;
registeredMetricNames.add(name);
nextAvailableMetricIndex += 1;
return instrument;
}
}
/**
* Registers a new Long Gauge metric instrument.
*
* @param name the name of the metric
* @param description a description of the metric
* @param unit the unit of measurement for the metric
* @param requiredLabelKeys a list of required label keys
* @param optionalLabelKeys a list of optional label keys
* @param enableByDefault whether the metric should be enabled by default
* @return the newly created LongGaugeMetricInstrument
* @throws IllegalStateException if a metric with the same name already exists
*/
public LongGaugeMetricInstrument registerLongGauge(String name, String description,
String unit, List<String> requiredLabelKeys, List<String> optionalLabelKeys, boolean
enableByDefault) {
checkArgument(!Strings.isNullOrEmpty(name), "missing metric name");
checkNotNull(description, "description");
checkNotNull(unit, "unit");
checkNotNull(requiredLabelKeys, "requiredLabelKeys");
checkNotNull(optionalLabelKeys, "optionalLabelKeys");
synchronized (lock) {
if (registeredMetricNames.contains(name)) {
throw new IllegalStateException("Metric with name " + name + " already exists");
}
int index = nextAvailableMetricIndex;
if (index + 1 == metricInstruments.length) {
resizeMetricInstruments();
}
LongGaugeMetricInstrument instrument = new LongGaugeMetricInstrument(
index, name, description, unit, requiredLabelKeys, optionalLabelKeys,
enableByDefault);
metricInstruments[index] = instrument;
registeredMetricNames.add(name);
nextAvailableMetricIndex += 1;
return instrument;
}
}
@GuardedBy("lock")
private void resizeMetricInstruments() {
// Increase the capacity of the metricInstruments array by INITIAL_INSTRUMENT_CAPACITY
int newInstrumentsCapacity = metricInstruments.length + INITIAL_INSTRUMENT_CAPACITY;
MetricInstrument[] resizedMetricInstruments = Arrays.copyOf(metricInstruments,
newInstrumentsCapacity);
metricInstruments = resizedMetricInstruments;
}
}

View File

@ -0,0 +1,156 @@
/*
* 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;
import static com.google.common.base.Preconditions.checkArgument;
import java.util.List;
/**
* An interface used for recording gRPC metrics. Implementations of this interface are responsible
* for collecting and potentially reporting metrics from various gRPC components.
*/
@Internal
public interface MetricRecorder {
/**
* Adds a value for a double-precision counter metric instrument.
*
* @param metricInstrument The counter metric instrument to add the value against.
* @param value The value to add.
* @param requiredLabelValues A list of required label values for the metric.
* @param optionalLabelValues A list of additional, optional label values for the metric.
*/
default void addDoubleCounter(DoubleCounterMetricInstrument metricInstrument, double value,
List<String> requiredLabelValues, List<String> optionalLabelValues) {
checkArgument(requiredLabelValues != null
&& requiredLabelValues.size() == metricInstrument.getRequiredLabelKeys().size(),
"Incorrect number of required labels provided. Expected: %s",
metricInstrument.getRequiredLabelKeys().size());
checkArgument(optionalLabelValues != null
&& optionalLabelValues.size() == metricInstrument.getOptionalLabelKeys().size(),
"Incorrect number of optional labels provided. Expected: %s",
metricInstrument.getOptionalLabelKeys().size());
}
/**
* Adds a value for a long valued counter metric instrument.
*
* @param metricInstrument The counter metric instrument to add the value against.
* @param value The value to add.
* @param requiredLabelValues A list of required label values for the metric.
* @param optionalLabelValues A list of additional, optional label values for the metric.
*/
default void addLongCounter(LongCounterMetricInstrument metricInstrument, long value,
List<String> requiredLabelValues, List<String> optionalLabelValues) {
checkArgument(requiredLabelValues != null
&& requiredLabelValues.size() == metricInstrument.getRequiredLabelKeys().size(),
"Incorrect number of required labels provided. Expected: %s",
metricInstrument.getRequiredLabelKeys().size());
checkArgument(optionalLabelValues != null
&& optionalLabelValues.size() == metricInstrument.getOptionalLabelKeys().size(),
"Incorrect number of optional labels provided. Expected: %s",
metricInstrument.getOptionalLabelKeys().size());
}
/**
* Records a value for a double-precision histogram metric instrument.
*
* @param metricInstrument The histogram metric instrument to record the value against.
* @param value The value to record.
* @param requiredLabelValues A list of required label values for the metric.
* @param optionalLabelValues A list of additional, optional label values for the metric.
*/
default void recordDoubleHistogram(DoubleHistogramMetricInstrument metricInstrument, double value,
List<String> requiredLabelValues, List<String> optionalLabelValues) {
checkArgument(requiredLabelValues != null
&& requiredLabelValues.size() == metricInstrument.getRequiredLabelKeys().size(),
"Incorrect number of required labels provided. Expected: %s",
metricInstrument.getRequiredLabelKeys().size());
checkArgument(optionalLabelValues != null
&& optionalLabelValues.size() == metricInstrument.getOptionalLabelKeys().size(),
"Incorrect number of optional labels provided. Expected: %s",
metricInstrument.getOptionalLabelKeys().size());
}
/**
* Records a value for a long valued histogram metric instrument.
*
* @param metricInstrument The histogram metric instrument to record the value against.
* @param value The value to record.
* @param requiredLabelValues A list of required label values for the metric.
* @param optionalLabelValues A list of additional, optional label values for the metric.
*/
default void recordLongHistogram(LongHistogramMetricInstrument metricInstrument, long value,
List<String> requiredLabelValues, List<String> optionalLabelValues) {
checkArgument(requiredLabelValues != null
&& requiredLabelValues.size() == metricInstrument.getRequiredLabelKeys().size(),
"Incorrect number of required labels provided. Expected: %s",
metricInstrument.getRequiredLabelKeys().size());
checkArgument(optionalLabelValues != null
&& optionalLabelValues.size() == metricInstrument.getOptionalLabelKeys().size(),
"Incorrect number of optional labels provided. Expected: %s",
metricInstrument.getOptionalLabelKeys().size());
}
/**
* Registers a callback to produce metric values for only the listed instruments. The returned
* registration must be closed when no longer needed, which will remove the callback.
*
* @param callback The callback to call to record.
* @param metricInstruments The metric instruments the callback will record against.
*/
default Registration registerBatchCallback(BatchCallback callback,
CallbackMetricInstrument... metricInstruments) {
return () -> { };
}
/** Callback to record gauge values. */
interface BatchCallback {
/** Records instrument values into {@code recorder}. */
void accept(BatchRecorder recorder);
}
/** Recorder for instrument values produced by a batch callback. */
interface BatchRecorder {
/**
* Record a long gauge value.
*
* @param value The value to record.
* @param requiredLabelValues A list of required label values for the metric.
* @param optionalLabelValues A list of additional, optional label values for the metric.
*/
default void recordLongGauge(LongGaugeMetricInstrument metricInstrument, long value,
List<String> requiredLabelValues, List<String> optionalLabelValues) {
checkArgument(requiredLabelValues != null
&& requiredLabelValues.size() == metricInstrument.getRequiredLabelKeys().size(),
"Incorrect number of required labels provided. Expected: %s",
metricInstrument.getRequiredLabelKeys().size());
checkArgument(optionalLabelValues != null
&& optionalLabelValues.size() == metricInstrument.getOptionalLabelKeys().size(),
"Incorrect number of optional labels provided. Expected: %s",
metricInstrument.getOptionalLabelKeys().size());
}
}
/** A handle to a registration, that allows unregistration. */
interface Registration extends AutoCloseable {
// Redefined to not throw an exception.
/** Unregister. */
@Override
void close();
}
}

View File

@ -0,0 +1,128 @@
/*
* 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;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* An internal interface representing a receiver or aggregator of gRPC metrics data.
*/
@Internal
public interface MetricSink {
/**
* Returns a set of names for the metrics that are currently enabled or disabled.
*
* @return A set of enabled metric names.
*/
Map<String, Boolean> getEnabledMetrics();
/**
* Returns a set of optional label names for metrics that the sink actually wants.
*
* @return A set of optional label names.
*/
Set<String> getOptionalLabels();
/**
* Returns size of metric measures used to record metric values. These measures are created
* based on registered metrics (via MetricInstrumentRegistry) and are ordered according to their
* registration sequence.
*
* @return Size of metric measures.
*/
int getMeasuresSize();
/**
* Adds a value for a double-precision counter associated with specified metric instrument.
*
* @param metricInstrument The counter metric instrument identifies metric measure to add.
* @param value The value to record.
* @param requiredLabelValues A list of required label values for the metric.
* @param optionalLabelValues A list of additional, optional label values for the metric.
*/
default void addDoubleCounter(DoubleCounterMetricInstrument metricInstrument, double value,
List<String> requiredLabelValues, List<String> optionalLabelValues) {
}
/**
* Adds a value for a long valued counter metric associated with specified metric instrument.
*
* @param metricInstrument The counter metric instrument identifies metric measure to add.
* @param value The value to record.
* @param requiredLabelValues A list of required label values for the metric.
* @param optionalLabelValues A list of additional, optional label values for the metric.
*/
default void addLongCounter(LongCounterMetricInstrument metricInstrument, long value,
List<String> requiredLabelValues, List<String> optionalLabelValues) {
}
/**
* Records a value for a double-precision histogram metric associated with specified metric
* instrument.
*
* @param metricInstrument The histogram metric instrument identifies metric measure to record.
* @param value The value to record.
* @param requiredLabelValues A list of required label values for the metric.
* @param optionalLabelValues A list of additional, optional label values for the metric.
*/
default void recordDoubleHistogram(DoubleHistogramMetricInstrument metricInstrument, double value,
List<String> requiredLabelValues, List<String> optionalLabelValues) {
}
/**
* Records a value for a long valued histogram metric associated with specified metric
* instrument.
*
* @param metricInstrument The histogram metric instrument identifies metric measure to record.
* @param value The value to record.
* @param requiredLabelValues A list of required label values for the metric.
* @param optionalLabelValues A list of additional, optional label values for the metric.
*/
default void recordLongHistogram(LongHistogramMetricInstrument metricInstrument, long value,
List<String> requiredLabelValues, List<String> optionalLabelValues) {
}
/**
* Record a long gauge value.
*
* @param value The value to record.
* @param requiredLabelValues A list of required label values for the metric.
* @param optionalLabelValues A list of additional, optional label values for the metric.
*/
default void recordLongGauge(LongGaugeMetricInstrument metricInstrument, long value,
List<String> requiredLabelValues, List<String> optionalLabelValues){
}
/**
* Registers a callback to produce metric values for only the listed instruments. The returned
* registration must be closed when no longer needed, which will remove the callback.
*
* @param callback The callback to call to record.
* @param metricInstruments The metric instruments the callback will record against.
*/
default Registration registerBatchCallback(Runnable callback,
CallbackMetricInstrument... metricInstruments) {
return () -> { };
}
interface Registration extends MetricRecorder.Registration {}
void updateMeasures(List<MetricInstrument> instruments);
}

View File

@ -20,19 +20,21 @@ import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.base.MoreObjects;
import com.google.common.base.MoreObjects.ToStringHelper;
import com.google.common.base.Objects;
import com.google.errorprone.annotations.InlineMe;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.ScheduledExecutorService;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import javax.annotation.concurrent.ThreadSafe;
/**
@ -95,7 +97,8 @@ public abstract class NameResolver {
@Override
public void onResult(ResolutionResult resolutionResult) {
listener.onAddresses(resolutionResult.getAddresses(), resolutionResult.getAttributes());
listener.onAddresses(resolutionResult.getAddressesOrError().getValue(),
resolutionResult.getAttributes());
}
});
}
@ -218,19 +221,26 @@ public abstract class NameResolver {
@Override
@Deprecated
@InlineMe(
replacement = "this.onResult(ResolutionResult.newBuilder().setAddresses(servers)"
+ ".setAttributes(attributes).build())",
imports = "io.grpc.NameResolver.ResolutionResult")
replacement = "this.onResult(ResolutionResult.newBuilder().setAddressesOrError("
+ "StatusOr.fromValue(servers)).setAttributes(attributes).build())",
imports = {"io.grpc.NameResolver.ResolutionResult", "io.grpc.StatusOr"})
public final void onAddresses(
List<EquivalentAddressGroup> servers, @ResolutionResultAttr Attributes attributes) {
// TODO(jihuncho) need to promote Listener2 if we want to use ConfigOrError
// Calling onResult and not onResult2 because onResult2 can only be called from a
// synchronization context.
onResult(
ResolutionResult.newBuilder().setAddresses(servers).setAttributes(attributes).build());
ResolutionResult.newBuilder().setAddressesOrError(
StatusOr.fromValue(servers)).setAttributes(attributes).build());
}
/**
* Handles updates on resolved addresses and attributes. If
* {@link ResolutionResult#getAddresses()} is empty, {@link #onError(Status)} will be called.
* {@link ResolutionResult#getAddressesOrError()} is empty, {@link #onError(Status)} will be
* called.
*
* <p>Newer NameResolver implementations should prefer calling onResult2. This method exists to
* facilitate older {@link Listener} implementations to migrate to {@link Listener2}.
*
* @param resolutionResult the resolved server addresses, attributes, and Service Config.
* @since 1.21.0
@ -241,11 +251,31 @@ public abstract class NameResolver {
* Handles a name resolving error from the resolver. The listener is responsible for eventually
* invoking {@link NameResolver#refresh()} to re-attempt resolution.
*
* <p>New NameResolver implementations should prefer calling onResult2 which will have the
* address resolution error in {@link ResolutionResult}'s addressesOrError. This method exists
* to facilitate older implementations using {@link Listener} to migrate to {@link Listener2}.
*
* @param error a non-OK status
* @since 1.21.0
*/
@Override
public abstract void onError(Status error);
/**
* Handles updates on resolved addresses and attributes. Must be called from the same
* {@link SynchronizationContext} available in {@link NameResolver.Args} that is passed
* from the channel.
*
* @param resolutionResult the resolved server addresses or error in address resolution,
* attributes, and Service Config or error
* @return status indicating whether the resolutionResult was accepted by the listener,
* typically the result from a load balancer.
* @since 1.66
*/
public Status onResult2(ResolutionResult resolutionResult) {
onResult(resolutionResult);
return Status.OK;
}
}
/**
@ -257,10 +287,20 @@ public abstract class NameResolver {
@Documented
public @interface ResolutionResultAttr {}
@ExperimentalApi("https://github.com/grpc/grpc-java/issues/11989")
@ResolutionResultAttr
public static final Attributes.Key<String> ATTR_BACKEND_SERVICE =
Attributes.Key.create("io.grpc.NameResolver.ATTR_BACKEND_SERVICE");
/**
* Information that a {@link Factory} uses to create a {@link NameResolver}.
*
* <p>Note this class doesn't override neither {@code equals()} nor {@code hashCode()}.
* <p>Args applicable to all {@link NameResolver}s are defined here using ordinary setters and
* getters. This container can also hold externally-defined "custom" args that aren't so widely
* useful or that would be inappropriate dependencies for this low level API. See {@link
* Args#getArg} for more.
*
* <p>Note this class overrides neither {@code equals()} nor {@code hashCode()}.
*
* @since 1.21.0
*/
@ -274,24 +314,23 @@ public abstract class NameResolver {
@Nullable private final ChannelLogger channelLogger;
@Nullable private final Executor executor;
@Nullable private final String overrideAuthority;
@Nullable private final MetricRecorder metricRecorder;
@Nullable private final NameResolverRegistry nameResolverRegistry;
@Nullable private final IdentityHashMap<Key<?>, Object> customArgs;
private Args(
Integer defaultPort,
ProxyDetector proxyDetector,
SynchronizationContext syncContext,
ServiceConfigParser serviceConfigParser,
@Nullable ScheduledExecutorService scheduledExecutorService,
@Nullable ChannelLogger channelLogger,
@Nullable Executor executor,
@Nullable String overrideAuthority) {
this.defaultPort = checkNotNull(defaultPort, "defaultPort not set");
this.proxyDetector = checkNotNull(proxyDetector, "proxyDetector not set");
this.syncContext = checkNotNull(syncContext, "syncContext not set");
this.serviceConfigParser = checkNotNull(serviceConfigParser, "serviceConfigParser not set");
this.scheduledExecutorService = scheduledExecutorService;
this.channelLogger = channelLogger;
this.executor = executor;
this.overrideAuthority = overrideAuthority;
private Args(Builder builder) {
this.defaultPort = checkNotNull(builder.defaultPort, "defaultPort not set");
this.proxyDetector = checkNotNull(builder.proxyDetector, "proxyDetector not set");
this.syncContext = checkNotNull(builder.syncContext, "syncContext not set");
this.serviceConfigParser =
checkNotNull(builder.serviceConfigParser, "serviceConfigParser not set");
this.scheduledExecutorService = builder.scheduledExecutorService;
this.channelLogger = builder.channelLogger;
this.executor = builder.executor;
this.overrideAuthority = builder.overrideAuthority;
this.metricRecorder = builder.metricRecorder;
this.nameResolverRegistry = builder.nameResolverRegistry;
this.customArgs = cloneCustomArgs(builder.customArgs);
}
/**
@ -300,6 +339,7 @@ public abstract class NameResolver {
*
* @since 1.21.0
*/
// <p>TODO: Only meaningful for InetSocketAddress producers. Make this a custom arg?
public int getDefaultPort() {
return defaultPort;
}
@ -352,6 +392,30 @@ public abstract class NameResolver {
return serviceConfigParser;
}
/**
* Returns the value of a custom arg named 'key', or {@code null} if it's not set.
*
* <p>While ordinary {@link Args} should be universally useful and meaningful, custom arguments
* can apply just to resolvers of a certain URI scheme, just to resolvers producing a particular
* type of {@link java.net.SocketAddress}, or even an individual {@link NameResolver} subclass.
* Custom args are identified by an instance of {@link Args.Key} which should be a constant
* defined in a java package and class appropriate for the argument's scope.
*
* <p>{@link Args} are normally reserved for information in *support* of name resolution, not
* the name to be resolved itself. However, there are rare cases where all or part of the target
* name can't be represented by any standard URI scheme or can't be encoded as a String at all.
* Custom args, in contrast, can hold arbitrary Java types, making them a useful work around in
* these cases.
*
* <p>Custom args can also be used simply to avoid adding inappropriate deps to the low level
* io.grpc package.
*/
@SuppressWarnings("unchecked") // Cast is safe because all put()s go through the setArg() API.
@Nullable
public <T> T getArg(Key<T> key) {
return customArgs != null ? (T) customArgs.get(key) : null;
}
/**
* Returns the {@link ChannelLogger} for the Channel served by this NameResolver.
*
@ -389,6 +453,26 @@ public abstract class NameResolver {
return overrideAuthority;
}
/**
* Returns the {@link MetricRecorder} that the channel uses to record metrics.
*/
@Nullable
public MetricRecorder getMetricRecorder() {
return metricRecorder;
}
/**
* Returns the {@link NameResolverRegistry} that the Channel uses to look for {@link
* NameResolver}s.
*
* @since 1.74.0
*/
public NameResolverRegistry getNameResolverRegistry() {
if (nameResolverRegistry == null) {
throw new IllegalStateException("NameResolverRegistry is not set in Builder");
}
return nameResolverRegistry;
}
@Override
public String toString() {
@ -397,10 +481,13 @@ public abstract class NameResolver {
.add("proxyDetector", proxyDetector)
.add("syncContext", syncContext)
.add("serviceConfigParser", serviceConfigParser)
.add("customArgs", customArgs)
.add("scheduledExecutorService", scheduledExecutorService)
.add("channelLogger", channelLogger)
.add("executor", executor)
.add("overrideAuthority", overrideAuthority)
.add("metricRecorder", metricRecorder)
.add("nameResolverRegistry", nameResolverRegistry)
.toString();
}
@ -419,6 +506,9 @@ public abstract class NameResolver {
builder.setChannelLogger(channelLogger);
builder.setOffloadExecutor(executor);
builder.setOverrideAuthority(overrideAuthority);
builder.setMetricRecorder(metricRecorder);
builder.setNameResolverRegistry(nameResolverRegistry);
builder.customArgs = cloneCustomArgs(customArgs);
return builder;
}
@ -445,6 +535,9 @@ public abstract class NameResolver {
private ChannelLogger channelLogger;
private Executor executor;
private String overrideAuthority;
private MetricRecorder metricRecorder;
private NameResolverRegistry nameResolverRegistry;
private IdentityHashMap<Key<?>, Object> customArgs;
Builder() {
}
@ -531,16 +624,75 @@ public abstract class NameResolver {
return this;
}
/** See {@link Args#getArg(Key)}. */
public <T> Builder setArg(Key<T> key, T value) {
checkNotNull(key, "key");
checkNotNull(value, "value");
if (customArgs == null) {
customArgs = new IdentityHashMap<>();
}
customArgs.put(key, value);
return this;
}
/**
* See {@link Args#getMetricRecorder()}. This is an optional field.
*/
public Builder setMetricRecorder(MetricRecorder metricRecorder) {
this.metricRecorder = metricRecorder;
return this;
}
/**
* See {@link Args#getNameResolverRegistry}. This is an optional field.
*
* @since 1.74.0
*/
public Builder setNameResolverRegistry(NameResolverRegistry registry) {
this.nameResolverRegistry = registry;
return this;
}
/**
* Builds an {@link Args}.
*
* @since 1.21.0
*/
public Args build() {
return
new Args(
defaultPort, proxyDetector, syncContext, serviceConfigParser,
scheduledExecutorService, channelLogger, executor, overrideAuthority);
return new Args(this);
}
}
/**
* Identifies an externally-defined custom argument that can be stored in {@link Args}.
*
* <p>Uses reference equality so keys should be defined as global constants.
*
* @param <T> type of values that can be stored under this key
*/
@Immutable
@SuppressWarnings("UnusedTypeParameter")
public static final class Key<T> {
private final String debugString;
private Key(String debugString) {
this.debugString = debugString;
}
@Override
public String toString() {
return debugString;
}
/**
* Creates a new instance of {@link Key}.
*
* @param debugString a string used to describe the key, used for debugging.
* @param <T> Key type
* @return a new instance of Key
*/
public static <T> Key<T> create(String debugString) {
return new Key<>(debugString);
}
}
}
@ -573,17 +725,17 @@ public abstract class NameResolver {
*/
@ExperimentalApi("https://github.com/grpc/grpc-java/issues/1770")
public static final class ResolutionResult {
private final List<EquivalentAddressGroup> addresses;
private final StatusOr<List<EquivalentAddressGroup>> addressesOrError;
@ResolutionResultAttr
private final Attributes attributes;
@Nullable
private final ConfigOrError serviceConfig;
ResolutionResult(
List<EquivalentAddressGroup> addresses,
StatusOr<List<EquivalentAddressGroup>> addressesOrError,
@ResolutionResultAttr Attributes attributes,
ConfigOrError serviceConfig) {
this.addresses = Collections.unmodifiableList(new ArrayList<>(addresses));
this.addressesOrError = addressesOrError;
this.attributes = checkNotNull(attributes, "attributes");
this.serviceConfig = serviceConfig;
}
@ -604,7 +756,7 @@ public abstract class NameResolver {
*/
public Builder toBuilder() {
return newBuilder()
.setAddresses(addresses)
.setAddressesOrError(addressesOrError)
.setAttributes(attributes)
.setServiceConfig(serviceConfig);
}
@ -613,9 +765,20 @@ public abstract class NameResolver {
* Gets the addresses resolved by name resolution.
*
* @since 1.21.0
* @deprecated Will be superseded by getAddressesOrError
*/
@Deprecated
public List<EquivalentAddressGroup> getAddresses() {
return addresses;
return addressesOrError.getValue();
}
/**
* Gets the addresses resolved by name resolution or the error in doing so.
*
* @since 1.65.0
*/
public StatusOr<List<EquivalentAddressGroup>> getAddressesOrError() {
return addressesOrError;
}
/**
@ -641,11 +804,11 @@ public abstract class NameResolver {
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("addresses", addresses)
.add("attributes", attributes)
.add("serviceConfig", serviceConfig)
.toString();
ToStringHelper stringHelper = MoreObjects.toStringHelper(this);
stringHelper.add("addressesOrError", addressesOrError.toString());
stringHelper.add("attributes", attributes);
stringHelper.add("serviceConfigOrError", serviceConfig);
return stringHelper.toString();
}
/**
@ -657,7 +820,7 @@ public abstract class NameResolver {
return false;
}
ResolutionResult that = (ResolutionResult) obj;
return Objects.equal(this.addresses, that.addresses)
return Objects.equal(this.addressesOrError, that.addressesOrError)
&& Objects.equal(this.attributes, that.attributes)
&& Objects.equal(this.serviceConfig, that.serviceConfig);
}
@ -667,7 +830,7 @@ public abstract class NameResolver {
*/
@Override
public int hashCode() {
return Objects.hashCode(addresses, attributes, serviceConfig);
return Objects.hashCode(addressesOrError, attributes, serviceConfig);
}
/**
@ -677,7 +840,8 @@ public abstract class NameResolver {
*/
@ExperimentalApi("https://github.com/grpc/grpc-java/issues/1770")
public static final class Builder {
private List<EquivalentAddressGroup> addresses = Collections.emptyList();
private StatusOr<List<EquivalentAddressGroup>> addresses =
StatusOr.fromValue(Collections.emptyList());
private Attributes attributes = Attributes.EMPTY;
@Nullable
private ConfigOrError serviceConfig;
@ -689,9 +853,21 @@ public abstract class NameResolver {
* Sets the addresses resolved by name resolution. This field is required.
*
* @since 1.21.0
* @deprecated Will be superseded by setAddressesOrError
*/
@Deprecated
public Builder setAddresses(List<EquivalentAddressGroup> addresses) {
this.addresses = addresses;
setAddressesOrError(StatusOr.fromValue(addresses));
return this;
}
/**
* Sets the addresses resolved by name resolution or the error in doing so. This field is
* required.
* @param addresses Resolved addresses or an error in resolving addresses
*/
public Builder setAddressesOrError(StatusOr<List<EquivalentAddressGroup>> addresses) {
this.addresses = checkNotNull(addresses, "StatusOr addresses cannot be null.");
return this;
}
@ -814,4 +990,10 @@ public abstract class NameResolver {
}
}
}
@Nullable
private static IdentityHashMap<Args.Key<?>, Object> cloneCustomArgs(
@Nullable IdentityHashMap<Args.Key<?>, Object> customArgs) {
return customArgs != null ? new IdentityHashMap<>(customArgs) : null;
}
}

View File

@ -20,6 +20,7 @@ import static com.google.common.base.Preconditions.checkArgument;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableMap;
import com.google.errorprone.annotations.concurrent.GuardedBy;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collections;
@ -31,7 +32,6 @@ import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Nullable;
import javax.annotation.concurrent.GuardedBy;
import javax.annotation.concurrent.ThreadSafe;
/**
@ -166,6 +166,11 @@ public final class NameResolverRegistry {
} catch (ClassNotFoundException e) {
logger.log(Level.FINE, "Unable to find DNS NameResolver", e);
}
try {
list.add(Class.forName("io.grpc.binder.internal.IntentNameResolverProvider"));
} catch (ClassNotFoundException e) {
logger.log(Level.FINE, "Unable to find IntentNameResolverProvider", e);
}
return Collections.unmodifiableList(list);
}

View File

@ -58,6 +58,12 @@ abstract class PartialForwardingServerCall<ReqT, RespT> extends ServerCall<ReqT,
delegate().setMessageCompression(enabled);
}
@Override
@ExperimentalApi("https://github.com/grpc/grpc-java/issues/11021")
public void setOnReadyThreshold(int numBytes) {
delegate().setOnReadyThreshold(numBytes);
}
@Override
@ExperimentalApi("https://github.com/grpc/grpc-java/issues/1704")
public void setCompression(String compressor) {

View File

@ -0,0 +1,97 @@
/*
* 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;
import com.google.common.collect.ImmutableList;
import java.util.List;
/**
* A partial implementation of the {@link MetricInstrument} interface. This class
* provides common fields and functionality for metric instruments.
*/
@Internal
abstract class PartialMetricInstrument implements MetricInstrument {
protected final int index;
protected final String name;
protected final String description;
protected final String unit;
protected final List<String> requiredLabelKeys;
protected final List<String> optionalLabelKeys;
protected final boolean enableByDefault;
/**
* Constructs a new PartialMetricInstrument with the specified attributes.
*
* @param index the unique index of this metric instrument
* @param name the name of the metric
* @param description a description of the metric
* @param unit the unit of measurement for the metric
* @param requiredLabelKeys a list of required label keys for the metric
* @param optionalLabelKeys a list of optional label keys for the metric
* @param enableByDefault whether the metric should be enabled by default
*/
protected PartialMetricInstrument(int index, String name, String description, String unit,
List<String> requiredLabelKeys, List<String> optionalLabelKeys, boolean enableByDefault) {
this.index = index;
this.name = name;
this.description = description;
this.unit = unit;
this.requiredLabelKeys = ImmutableList.copyOf(requiredLabelKeys);
this.optionalLabelKeys = ImmutableList.copyOf(optionalLabelKeys);
this.enableByDefault = enableByDefault;
}
@Override
public int getIndex() {
return index;
}
@Override
public String getName() {
return name;
}
@Override
public String getDescription() {
return description;
}
@Override
public String getUnit() {
return unit;
}
@Override
public List<String> getRequiredLabelKeys() {
return requiredLabelKeys;
}
@Override
public List<String> getOptionalLabelKeys() {
return optionalLabelKeys;
}
@Override
public boolean isEnableByDefault() {
return enableByDefault;
}
@Override
public String toString() {
return getClass().getName() + "(" + getName() + ")";
}
}

View File

@ -71,7 +71,6 @@ public abstract class Server {
* @throws IllegalStateException if the server has not yet been started.
* @since 1.19.0
*/
@ExperimentalApi("https://github.com/grpc/grpc-java/issues/5332")
public List<? extends SocketAddress> getListenSockets() {
throw new UnsupportedOperationException();
}

View File

@ -114,13 +114,15 @@ public abstract class ServerBuilder<T extends ServerBuilder<T>> {
public abstract T addService(BindableService bindableService);
/**
* Adds a list of service implementations to the handler registry together.
* Adds a list of service implementations to the handler registry together. This exists for
* convenience - equivalent to repeatedly calling addService() with different services.
* If multiple services on the list use the same name, only the last one on the list will
* be added.
*
* @param services the list of ServerServiceDefinition objects
* @return this
* @since 1.37.0
*/
@ExperimentalApi("https://github.com/grpc/grpc-java/issues/7925")
public final T addServices(List<ServerServiceDefinition> services) {
checkNotNull(services, "services");
for (ServerServiceDefinition service : services) {

View File

@ -16,6 +16,8 @@
package io.grpc;
import static com.google.common.base.Preconditions.checkArgument;
import javax.annotation.Nullable;
/**
@ -209,6 +211,19 @@ public abstract class ServerCall<ReqT, RespT> {
// noop
}
/**
* A hint to the call that specifies how many bytes must be queued before
* {@link #isReady()} will return false. A call may ignore this property if
* unsupported. This may only be set before any messages are sent.
*
* @param numBytes The number of bytes that must be queued. Must be a
* positive integer.
*/
@ExperimentalApi("https://github.com/grpc/grpc-java/issues/11021")
public void setOnReadyThreshold(int numBytes) {
checkArgument(numBytes > 0, "numBytes must be positive: %s", numBytes);
}
/**
* Returns the level of security guarantee in communications
*

View File

@ -19,7 +19,7 @@ package io.grpc;
import javax.annotation.concurrent.ThreadSafe;
/**
* Interface for intercepting incoming calls before that are dispatched by
* Interface for intercepting incoming calls before they are dispatched by
* {@link ServerCallHandler}.
*
* <p>Implementers use this mechanism to add cross-cutting behavior to server-side calls. Common

Some files were not shown because too many files have changed in this diff Show More