-
Notifications
You must be signed in to change notification settings - Fork 863
/
DriverChannel.java
241 lines (214 loc) · 8.19 KB
/
DriverChannel.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
/*
* Copyright DataStax, Inc.
*
* 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 com.datastax.oss.driver.internal.core.channel;
import com.datastax.oss.driver.api.core.CqlIdentifier;
import com.datastax.oss.driver.api.core.ProtocolVersion;
import com.datastax.oss.driver.internal.core.util.concurrent.UncaughtExceptions;
import com.datastax.oss.protocol.internal.Message;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoop;
import io.netty.util.AttributeKey;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.Promise;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* A thin wrapper around a Netty {@link Channel}, to send requests to a Cassandra node and receive
* responses.
*/
public class DriverChannel {
static final AttributeKey<String> CLUSTER_NAME_KEY = AttributeKey.newInstance("cluster_name");
@SuppressWarnings("RedundantStringConstructorCall")
static final Object GRACEFUL_CLOSE_MESSAGE = new String("GRACEFUL_CLOSE_MESSAGE");
@SuppressWarnings("RedundantStringConstructorCall")
static final Object FORCEFUL_CLOSE_MESSAGE = new String("FORCEFUL_CLOSE_MESSAGE");
private final Channel channel;
private final InFlightHandler inFlightHandler;
private final WriteCoalescer writeCoalescer;
private final ProtocolVersion protocolVersion;
private final AtomicBoolean closing = new AtomicBoolean();
private final AtomicBoolean forceClosing = new AtomicBoolean();
DriverChannel(Channel channel, WriteCoalescer writeCoalescer, ProtocolVersion protocolVersion) {
this.channel = channel;
this.inFlightHandler = channel.pipeline().get(InFlightHandler.class);
this.writeCoalescer = writeCoalescer;
this.protocolVersion = protocolVersion;
}
/**
* @return a future that succeeds when the request frame was successfully written on the channel.
* Beyond that, the caller will be notified through the {@code responseCallback}.
*/
public Future<Void> write(
Message request,
boolean tracing,
Map<String, ByteBuffer> customPayload,
ResponseCallback responseCallback) {
if (closing.get()) {
throw new IllegalStateException("Driver channel is closing");
}
RequestMessage message = new RequestMessage(request, tracing, customPayload, responseCallback);
return writeCoalescer.writeAndFlush(channel, message);
}
/**
* Cancels a callback, indicating that the client that wrote it is no longer interested in the
* answer.
*
* <p>Note that this does not cancel the request server-side (but might in the future if Cassandra
* supports it).
*/
public void cancel(ResponseCallback responseCallback) {
// To avoid creating an extra message, we adopt the convention that writing the callback
// directly means cancellation
writeCoalescer.writeAndFlush(channel, responseCallback).addListener(UncaughtExceptions::log);
}
/**
* Releases a stream id if the client was holding onto it, and has now determined that it can be
* safely reused.
*
* @see ResponseCallback#holdStreamId()
*/
public void release(int streamId) {
channel.pipeline().fireUserEventTriggered(new ReleaseEvent(streamId));
}
/**
* Switches the underlying Cassandra connection to a new keyspace (as if a {@code USE ...}
* statement was issued).
*
* <p>The future will complete once the change is effective. Only one change may run at a given
* time, concurrent attempts will fail.
*
* <p>Changing the keyspace is inherently thread-unsafe: if other queries are running at the same
* time, the keyspace they will use is unpredictable.
*/
public Future<Void> setKeyspace(CqlIdentifier newKeyspace) {
Promise<Void> promise = channel.eventLoop().newPromise();
channel.pipeline().fireUserEventTriggered(new SetKeyspaceEvent(newKeyspace, promise));
return promise;
}
/**
* @return the name of the Cassandra cluster as returned by {@code system.local.cluster_name} on
* this connection.
*/
public String getClusterName() {
return channel.attr(CLUSTER_NAME_KEY).get();
}
/**
* @return the number of available stream ids on the channel. This is used to weigh channels in
* pools that have a size bigger than 1, in the load balancing policy, and for monitoring
* purposes.
*/
public int getAvailableIds() {
return inFlightHandler.getAvailableIds();
}
public EventLoop eventLoop() {
return channel.eventLoop();
}
public ProtocolVersion protocolVersion() {
return protocolVersion;
}
public SocketAddress remoteAddress() {
return channel.remoteAddress();
}
public SocketAddress localAddress() {
return channel.localAddress();
}
/**
* Initiates a graceful shutdown: no new requests will be accepted, but all pending requests will
* be allowed to complete before the underlying channel is closed.
*/
public Future<Void> close() {
if (closing.compareAndSet(false, true) && channel.isOpen()) {
// go through the coalescer: this guarantees that we won't reject writes that were submitted
// before, but had not been coalesced yet.
writeCoalescer
.writeAndFlush(channel, GRACEFUL_CLOSE_MESSAGE)
.addListener(UncaughtExceptions::log);
}
return channel.closeFuture();
}
/**
* Initiates a forced shutdown: any pending request will be aborted and the underlying channel
* will be closed.
*/
public Future<Void> forceClose() {
this.close();
if (forceClosing.compareAndSet(false, true) && channel.isOpen()) {
writeCoalescer
.writeAndFlush(channel, FORCEFUL_CLOSE_MESSAGE)
.addListener(UncaughtExceptions::log);
}
return channel.closeFuture();
}
/**
* Returns a future that will complete when a graceful close has started, but not yet completed.
*
* <p>In other words, the channel has stopped accepting new requests, but is still waiting for
* pending requests to finish. Once the last response has been received, the channel will really
* close and {@link #closeFuture()} will be completed.
*
* <p>If there were no pending requests when the graceful shutdown was initiated, or if {@link
* #forceClose()} is called first, this future will never complete.
*/
public ChannelFuture closeStartedFuture() {
return this.inFlightHandler.closeStartedFuture;
}
/**
* Does not close the channel, but returns a future that will complete when it is completely
* closed.
*/
public ChannelFuture closeFuture() {
return channel.closeFuture();
}
@Override
public String toString() {
return channel.toString();
}
// This is essentially a stripped-down Frame. We can't materialize the frame before writing,
// because we need the stream id, which is assigned from within the event loop.
static class RequestMessage {
final Message request;
final boolean tracing;
final Map<String, ByteBuffer> customPayload;
final ResponseCallback responseCallback;
RequestMessage(
Message message,
boolean tracing,
Map<String, ByteBuffer> customPayload,
ResponseCallback responseCallback) {
this.request = message;
this.tracing = tracing;
this.customPayload = customPayload;
this.responseCallback = responseCallback;
}
}
static class ReleaseEvent {
final int streamId;
ReleaseEvent(int streamId) {
this.streamId = streamId;
}
}
static class SetKeyspaceEvent {
final CqlIdentifier keyspaceName;
final Promise<Void> promise;
public SetKeyspaceEvent(CqlIdentifier keyspaceName, Promise<Void> promise) {
this.keyspaceName = keyspaceName;
this.promise = promise;
}
}
}