-
Notifications
You must be signed in to change notification settings - Fork 891
CASSJAVA-124: Add GRACEFUL_DISCONNECT support (CEP-59) #2091
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: trunk
Are you sure you want to change the base?
Changes from 16 commits
a226207
45c5f95
8c5139e
0a95963
1de60ae
3927a33
32fcb1b
85e7c25
442561d
23835de
618a7f8
c146d19
402d1bf
6de6523
4885827
6b9ac8f
3234760
2ae468b
86d0fad
9e1437e
ef912d2
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -78,7 +78,7 @@ | |
| <dependency> | ||
| <groupId>com.datastax.oss</groupId> | ||
| <artifactId>native-protocol</artifactId> | ||
| <version>1.5.2</version> | ||
| <version>1.5.3-SNAPSHOT</version> | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. We need to remember to change it to 1.5.3 after the release of the native protocol
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Agreed — I'll bump this to 1.5.3 as soon as native-protocol releases (tracking it in my native-protocol PR, datastax/native-protocol#61). Related finding while fixing CI: the build had never actually resolved this snapshot — ci/run-tests.sh wasn't running install-snapshots.sh at all, so every CI run failed at dependency resolution. That's fixed now (402d1bf, 4885827, 6b9ac8f) and CI installs the snapshot from the PR #61 branch. One heads-up: I initially pointed it at your fork's cep-59 branch (which the PR description referenced), but that copy has Frame.forResponse stubbed out with UnsupportedOperationException, which failed the graph unit tests — you may want to update or remove that branch so nothing else picks it up.
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Don't worry about CI or
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Reverted the CI changes in 3234760. |
||
| </dependency> | ||
| </dependencies> | ||
| </dependencyManagement> | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -51,6 +51,7 @@ public enum DefaultNodeMetric implements NodeMetric { | |
| SPECULATIVE_EXECUTIONS("speculative-executions"), | ||
| CONNECTION_INIT_ERRORS("errors.connection.init"), | ||
| AUTHENTICATION_ERRORS("errors.connection.auth"), | ||
| GRACEFUL_DISCONNECTS("pool.graceful-disconnects"), | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. +1
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Done; the counter is now initialized in all three backends (DropwizardNodeMetricUpdater, MicrometerNodeMetricUpdater, MicroProfileNodeMetricUpdater) in 618a7f8, and incremented when a GRACEFUL_DISCONNECT event is received on one of the node's pooled connections (ChannelPool query-connection callback, 442561d). It's documented in reference.conf, covered by the zero-value assertions in the three metrics ITs and by ChannelPoolGracefulDisconnectTest, and the new GracefulDisconnectIT exercises the session-level counter end to end against a real drain. I also verified both counters increment during manual drain runs on 2- and 3-node ccm clusters. |
||
| ; | ||
|
|
||
| private static final Map<String, DefaultNodeMetric> BY_PATH = sortByPath(); | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -32,6 +32,7 @@ public enum DefaultSessionMetric implements SessionMetric { | |
| THROTTLING_QUEUE_SIZE("throttling.queue-size"), | ||
| THROTTLING_ERRORS("throttling.errors"), | ||
| CQL_PREPARED_CACHE_SIZE("cql-prepared-cache-size"), | ||
| GRACEFUL_DISCONNECTS("graceful-disconnects"), | ||
|
Shanzita marked this conversation as resolved.
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. We need integration tests and manual testing for metrics
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. and the actual implementation of incrementing the metric
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. All three parts are done now:
|
||
| ; | ||
|
|
||
| private static final Map<String, DefaultSessionMetric> BY_PATH = sortByPath(); | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,51 @@ | ||
| /* | ||
| * Licensed to the Apache Software Foundation (ASF) under one | ||
| * or more contributor license agreements. See the NOTICE file | ||
| * distributed with this work for additional information | ||
| * regarding copyright ownership. The ASF licenses this file | ||
| * to you under the Apache License, Version 2.0 (the | ||
| * "License"); you may not use this file except in compliance | ||
| * with the License. You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
| package com.datastax.oss.driver.internal.core.channel; | ||
|
|
||
| import com.datastax.oss.driver.api.core.metadata.Node; | ||
| import net.jcip.annotations.Immutable; | ||
|
|
||
| /** | ||
| * This event indicates that the server is shutting down gracefully and the driver should: | ||
| * | ||
| * <ul> | ||
| * <li>Stop sending new requests on the affected connection | ||
| * <li>Allow in-flight requests to complete | ||
| * <li>Begin reconnection attempts with exponential backoff | ||
| * </ul> | ||
| * | ||
| * <p>This is part of CEP-59: Graceful Disconnect – In-Band Connection Draining for Node Shutdown. | ||
| */ | ||
| @Immutable | ||
| public class GracefulDisconnectEvent { | ||
|
|
||
| /** The event type string as defined in the native protocol. */ | ||
| public static final String EVENT_TYPE = "GRACEFUL_DISCONNECT"; | ||
|
|
||
| /** The node that sent the graceful disconnect event. */ | ||
| public final Node node; | ||
|
|
||
| public GracefulDisconnectEvent(Node node) { | ||
| this.node = node; | ||
| } | ||
|
|
||
| @Override | ||
| public String toString() { | ||
| return "GracefulDisconnectEvent{node=" + node + '}'; | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -33,6 +33,7 @@ | |
| import com.datastax.oss.protocol.internal.Frame; | ||
| import com.datastax.oss.protocol.internal.Message; | ||
| import com.datastax.oss.protocol.internal.request.Query; | ||
| import com.datastax.oss.protocol.internal.response.Event; | ||
| import com.datastax.oss.protocol.internal.response.result.SetKeyspace; | ||
| import io.netty.channel.ChannelDuplexHandler; | ||
| import io.netty.channel.ChannelFuture; | ||
|
|
@@ -218,6 +219,13 @@ public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception | |
|
|
||
| if (streamId < 0) { | ||
| Message event = responseFrame.message; | ||
| if (event instanceof Event | ||
| && GracefulDisconnectEvent.EVENT_TYPE.equals(((Event) event).type)) { | ||
| // Start draining this channel first, so that the drain is not compromised if the | ||
| // callback below misbehaves. | ||
| LOG.debug("[{}] Received GRACEFUL_DISCONNECT, initiating graceful drain", logPrefix); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Can you confirm, on receiving a graceful disconnect event, will line 226 and line 232 both logs
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Confirmed, both lines logged it (the drain-specific debug plus the generic received-event log). Removed the redundant one in 86d0fad; the generic log and the logs inside startGracefulShutdown cover it. |
||
| startGracefulShutdown(ctx); | ||
| } | ||
| if (eventCallback == null) { | ||
| LOG.debug("[{}] Received event {} but no callback was registered", logPrefix, event); | ||
| } else { | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -36,6 +36,7 @@ | |
| import com.datastax.oss.driver.internal.core.protocol.SegmentToFrameDecoder; | ||
| import com.datastax.oss.driver.internal.core.util.ProtocolUtils; | ||
| import com.datastax.oss.driver.internal.core.util.concurrent.UncaughtExceptions; | ||
| import com.datastax.oss.driver.shaded.guava.common.annotations.VisibleForTesting; | ||
| import com.datastax.oss.protocol.internal.Message; | ||
| import com.datastax.oss.protocol.internal.ProtocolConstants; | ||
| import com.datastax.oss.protocol.internal.ProtocolConstants.ErrorCode; | ||
|
|
@@ -55,7 +56,9 @@ | |
| import io.netty.channel.ChannelHandlerContext; | ||
| import io.netty.channel.ChannelPipeline; | ||
| import java.nio.ByteBuffer; | ||
| import java.util.ArrayList; | ||
| import java.util.List; | ||
| import java.util.Map; | ||
| import java.util.Objects; | ||
| import net.jcip.annotations.NotThreadSafe; | ||
| import org.slf4j.Logger; | ||
|
|
@@ -140,6 +143,30 @@ protected boolean setConnectSuccess() { | |
| return result; | ||
| } | ||
|
|
||
| /** | ||
| * Whether a SUPPORTED response advertises the CEP-59 graceful disconnect capability. | ||
| * | ||
| * <p>The server signals support with a {@code GRACEFUL_DISCONNECT} key; depending on the code | ||
| * path it may also send the key with an explicit {@code "false"} value when the feature is | ||
| * disabled, so any value other than {@code false} (in any case) is treated as supported. | ||
| */ | ||
| @VisibleForTesting | ||
| static boolean supportsGracefulDisconnect(Map<String, List<String>> supportedOptions) { | ||
| if (supportedOptions == null) { | ||
| return false; | ||
| } | ||
| List<String> values = supportedOptions.get(GracefulDisconnectEvent.EVENT_TYPE); | ||
| if (values == null) { | ||
| return false; | ||
| } | ||
| for (String value : values) { | ||
| if ("false".equalsIgnoreCase(value)) { | ||
| return false; | ||
| } | ||
| } | ||
| return true; | ||
| } | ||
|
|
||
| private enum Step { | ||
| OPTIONS, | ||
| STARTUP, | ||
|
|
@@ -157,6 +184,8 @@ private class InitRequest extends ChannelHandlerRequest { | |
| private Message request; | ||
| private Authenticator authenticator; | ||
| private ByteBuffer authResponseToken; | ||
| private List<String> lastRegisterEventTypes; | ||
| private boolean retriedRegisterWithoutGracefulDisconnect; | ||
|
|
||
| InitRequest(ChannelHandlerContext ctx) { | ||
| super(ctx, timeoutMillis); | ||
|
|
@@ -183,12 +212,36 @@ Message getRequest() { | |
| case AUTH_RESPONSE: | ||
| return request = new AuthResponse(authResponseToken); | ||
| case REGISTER: | ||
| return request = new Register(options.eventTypes); | ||
| return request = new Register(lastRegisterEventTypes = filterSupportedEventTypes()); | ||
| default: | ||
| throw new AssertionError("unhandled step: " + step); | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Filters the requested event types to only include those supported by the server. | ||
| * | ||
| * <p>Specifically, GRACEFUL_DISCONNECT is only included if this channel's own SUPPORTED | ||
| * response advertises the capability. Capabilities are tracked per connection: in a | ||
| * mixed-version cluster (e.g. during a rolling upgrade), some nodes may support graceful | ||
| * disconnect while others don't, so a channel never relies on what another channel negotiated. | ||
| * Channels that request this event type always run the OPTIONS step (see {@link | ||
| * ChannelFactory}), so the channel attribute is populated by the time REGISTER is sent. | ||
| */ | ||
| private List<String> filterSupportedEventTypes() { | ||
| List<String> filteredEventTypes = new ArrayList<>(options.eventTypes); | ||
|
|
||
| if (filteredEventTypes.contains(GracefulDisconnectEvent.EVENT_TYPE)) { | ||
| Map<String, List<String>> supportedOptions = channel.attr(DriverChannel.OPTIONS_KEY).get(); | ||
| if (!supportsGracefulDisconnect(supportedOptions) | ||
| || retriedRegisterWithoutGracefulDisconnect) { | ||
| filteredEventTypes.remove(GracefulDisconnectEvent.EVENT_TYPE); | ||
| } | ||
| } | ||
|
|
||
| return filteredEventTypes; | ||
| } | ||
|
|
||
| @Override | ||
| void send() { | ||
| stepNumber++; | ||
|
|
@@ -339,6 +392,23 @@ void onResponse(Message response) { | |
| } else if (step == Step.SET_KEYSPACE | ||
| && error.code == ProtocolConstants.ErrorCode.INVALID) { | ||
| fail(new InvalidKeyspaceException(error.message)); | ||
| } else if (step == Step.REGISTER | ||
| && !retriedRegisterWithoutGracefulDisconnect | ||
| && lastRegisterEventTypes != null | ||
| && lastRegisterEventTypes.contains(GracefulDisconnectEvent.EVENT_TYPE) | ||
| && (serverOrProtocolError || error.code == ProtocolConstants.ErrorCode.INVALID)) { | ||
| // The server rejected our REGISTER, most likely because it does not recognize the | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. No need for retry. The handling of registering graceful disconnect should be the same as the handling of other events.
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. So the logic here should be much simplified
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Removed the retry entirely in 2ae468b. Registration is now handled the same as the other events. |
||
| // GRACEFUL_DISCONNECT event type: a pre-CEP-59 node in a mixed-version cluster, or a | ||
| // node where the (still evolving) CEP-59 wire contract has changed. Losing graceful | ||
| // disconnect on this connection is benign; failing channel init is disruptive. So | ||
| // retry once without the event type instead of failing. | ||
| LOG.warn( | ||
| "[{}] Server rejected REGISTER including {} ({}), retrying without it", | ||
| logPrefix, | ||
| GracefulDisconnectEvent.EVENT_TYPE, | ||
| error.message); | ||
| retriedRegisterWithoutGracefulDisconnect = true; | ||
| send(); | ||
| } else { | ||
| failOnUnexpected(error); | ||
| } | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -26,10 +26,12 @@ | |
| import com.datastax.oss.driver.api.core.loadbalancing.NodeDistance; | ||
| import com.datastax.oss.driver.api.core.metadata.Node; | ||
| import com.datastax.oss.driver.api.core.metadata.NodeState; | ||
| import com.datastax.oss.driver.api.core.metrics.DefaultSessionMetric; | ||
| import com.datastax.oss.driver.internal.core.channel.ChannelEvent; | ||
| import com.datastax.oss.driver.internal.core.channel.DriverChannel; | ||
| import com.datastax.oss.driver.internal.core.channel.DriverChannelOptions; | ||
| import com.datastax.oss.driver.internal.core.channel.EventCallback; | ||
| import com.datastax.oss.driver.internal.core.channel.GracefulDisconnectEvent; | ||
| import com.datastax.oss.driver.internal.core.context.InternalDriverContext; | ||
| import com.datastax.oss.driver.internal.core.metadata.DefaultTopologyMonitor; | ||
| import com.datastax.oss.driver.internal.core.metadata.DistanceEvent; | ||
|
|
@@ -178,8 +180,8 @@ public void onEvent(Message eventMessage) { | |
| if (!(eventMessage instanceof Event)) { | ||
| LOG.warn("[{}] Unsupported event class: {}", logPrefix, eventMessage.getClass().getName()); | ||
| } else { | ||
| LOG.debug("[{}] Processing incoming event {}", logPrefix, eventMessage); | ||
| Event event = (Event) eventMessage; | ||
| LOG.debug("[{}] Processing incoming event {}", logPrefix, eventMessage); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Pls revert the reversion of these two lines
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Reverted in 86d0fad. |
||
| switch (event.type) { | ||
| case ProtocolConstants.EventType.TOPOLOGY_CHANGE: | ||
| processTopologyChange(event); | ||
|
|
@@ -190,6 +192,9 @@ public void onEvent(Message eventMessage) { | |
| case ProtocolConstants.EventType.SCHEMA_CHANGE: | ||
| processSchemaChange(event); | ||
| break; | ||
| case GracefulDisconnectEvent.EVENT_TYPE: | ||
| processGracefulDisconnect(); | ||
| break; | ||
| default: | ||
| LOG.warn("[{}] Unsupported event type: {}", logPrefix, event.type); | ||
| } | ||
|
|
@@ -242,6 +247,30 @@ private void processSchemaChange(Event event) { | |
| }); | ||
| } | ||
|
|
||
| private void processGracefulDisconnect() { | ||
| LOG.info( | ||
| "[{}] Received GRACEFUL_DISCONNECT event on control connection, " | ||
| + "the server is shutting down gracefully", | ||
| logPrefix); | ||
| context | ||
| .getMetricsFactory() | ||
| .getSessionUpdater() | ||
| .incrementCounter(DefaultSessionMetric.GRACEFUL_DISCONNECTS, null); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Why not increment DefaultNodeMetric.GRACEFUL_DISCONNECTS?
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Good catch, added in 86d0fad along with a unit test asserting both counters increment. |
||
| // Fire an internal event to notify other components (particularly the ChannelPool) | ||
| DriverChannel currentChannel = channel; | ||
| if (currentChannel != null) { | ||
| context | ||
| .getMetadataManager() | ||
| .getMetadata() | ||
| .findNode(currentChannel.getEndPoint()) | ||
| .ifPresent(node -> context.getEventBus().fire(new GracefulDisconnectEvent(node))); | ||
| } | ||
| // The control connection will handle reconnection automatically when the channel closes. | ||
| // The ChannelPool will close all its channels when it receives the GracefulDisconnectEvent, | ||
| // which will cause the NodeStateManager to set the node to DOWN state and trigger the | ||
| // LoadBalancingPolicy to remove it from the live set. | ||
| } | ||
|
|
||
| private class SingleThreaded { | ||
| private final InternalDriverContext context; | ||
| private final DriverConfig config; | ||
|
|
@@ -292,7 +321,13 @@ private void init( | |
| } | ||
| initWasCalled = true; | ||
| try { | ||
| ImmutableList<String> eventTypes = buildEventTypes(listenToClusterEvents); | ||
| boolean gracefulDisconnectEnabled = | ||
| context | ||
| .getConfig() | ||
| .getDefaultProfile() | ||
| .getBoolean(DefaultDriverOption.GRACEFUL_DISCONNECT_ENABLED, true); | ||
| ImmutableList<String> eventTypes = | ||
| buildEventTypes(listenToClusterEvents, gracefulDisconnectEnabled); | ||
| LOG.debug("[{}] Initializing with event types {}", logPrefix, eventTypes); | ||
| channelOptions = | ||
| DriverChannelOptions.builder() | ||
|
|
@@ -606,14 +641,18 @@ private boolean isAuthFailure(Throwable error) { | |
| return true; | ||
| } | ||
|
|
||
| private static ImmutableList<String> buildEventTypes(boolean listenClusterEvents) { | ||
| private static ImmutableList<String> buildEventTypes( | ||
| boolean listenClusterEvents, boolean gracefulDisconnectEnabled) { | ||
| ImmutableList.Builder<String> builder = ImmutableList.builder(); | ||
| builder.add(ProtocolConstants.EventType.SCHEMA_CHANGE); | ||
| if (listenClusterEvents) { | ||
| builder | ||
| .add(ProtocolConstants.EventType.STATUS_CHANGE) | ||
| .add(ProtocolConstants.EventType.TOPOLOGY_CHANGE); | ||
| } | ||
| if (gracefulDisconnectEnabled) { | ||
| builder.add(GracefulDisconnectEvent.EVENT_TYPE); | ||
| } | ||
| return builder.build(); | ||
| } | ||
| } | ||
Uh oh!
There was an error while loading. Please reload this page.