-
Notifications
You must be signed in to change notification settings - Fork 2k
/
NetClientImpl.java
259 lines (228 loc) · 9.2 KB
/
NetClientImpl.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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
/*
* Copyright (c) 2011-2013 The original author or authors
* ------------------------------------------------------
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* The Apache License v2.0 is available at
* http://www.opensource.org/licenses/apache2.0.php
*
* You may elect to redistribute this code under either of these licenses.
*/
package io.vertx.core.net.impl;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.FixedRecvByteBufAllocator;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.ssl.SslHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;
import io.vertx.core.AsyncResult;
import io.vertx.core.Closeable;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.impl.ContextImpl;
import io.vertx.core.impl.VertxInternal;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import io.vertx.core.net.NetClient;
import io.vertx.core.net.NetClientOptions;
import io.vertx.core.net.NetSocket;
import io.vertx.core.spi.metrics.Metrics;
import io.vertx.core.spi.metrics.MetricsProvider;
import io.vertx.core.spi.metrics.TCPMetrics;
/**
*
* This class is thread-safe
*
* @author <a href="http://tfox.org">Tim Fox</a>
*/
public class NetClientImpl implements NetClient, MetricsProvider {
private static final Logger log = LoggerFactory.getLogger(NetClientImpl.class);
private final VertxInternal vertx;
private final NetClientOptions options;
private final SSLHelper sslHelper;
private final Map<Channel, NetSocketImpl> socketMap = new ConcurrentHashMap<>();
private final Closeable closeHook;
private final ContextImpl creatingContext;
private final TCPMetrics metrics;
private final boolean logEnabled;
private volatile boolean closed;
public NetClientImpl(VertxInternal vertx, NetClientOptions options) {
this(vertx, options, true);
}
public NetClientImpl(VertxInternal vertx, NetClientOptions options, boolean useCreatingContext) {
this.vertx = vertx;
this.options = new NetClientOptions(options);
this.sslHelper = new SSLHelper(options, options.getKeyCertOptions(), options.getTrustOptions());
this.logEnabled = options.getLogActivity();
this.closeHook = completionHandler -> {
NetClientImpl.this.close();
completionHandler.handle(Future.succeededFuture());
};
if (useCreatingContext) {
creatingContext = vertx.getContext();
if (creatingContext != null) {
if (creatingContext.isMultiThreadedWorkerContext()) {
throw new IllegalStateException("Cannot use NetClient in a multi-threaded worker verticle");
}
creatingContext.addCloseHook(closeHook);
}
} else {
creatingContext = null;
}
this.metrics = vertx.metricsSPI().createMetrics(this, options);
}
public synchronized NetClient connect(int port, String host, Handler<AsyncResult<NetSocket>> connectHandler) {
checkClosed();
connect(port, host, connectHandler, options.getReconnectAttempts());
return this;
}
@Override
public void close() {
if (!closed) {
for (NetSocket sock : socketMap.values()) {
sock.close();
}
if (creatingContext != null) {
creatingContext.removeCloseHook(closeHook);
}
closed = true;
metrics.close();
}
}
@Override
public boolean isMetricsEnabled() {
return metrics != null && metrics.isEnabled();
}
@Override
public Metrics getMetrics() {
return metrics;
}
private void checkClosed() {
if (closed) {
throw new IllegalStateException("Client is closed");
}
}
private void applyConnectionOptions(Bootstrap bootstrap) {
bootstrap.option(ChannelOption.TCP_NODELAY, options.isTcpNoDelay());
if (options.getSendBufferSize() != -1) {
bootstrap.option(ChannelOption.SO_SNDBUF, options.getSendBufferSize());
}
if (options.getReceiveBufferSize() != -1) {
bootstrap.option(ChannelOption.SO_RCVBUF, options.getReceiveBufferSize());
bootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(options.getReceiveBufferSize()));
}
if (options.getSoLinger() != -1) {
bootstrap.option(ChannelOption.SO_LINGER, options.getSoLinger());
}
if (options.getTrafficClass() != -1) {
bootstrap.option(ChannelOption.IP_TOS, options.getTrafficClass());
}
bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, options.getConnectTimeout());
bootstrap.option(ChannelOption.ALLOCATOR, PartialPooledByteBufAllocator.INSTANCE);
bootstrap.option(ChannelOption.SO_KEEPALIVE, options.isTcpKeepAlive());
}
private void connect(int port, String host, Handler<AsyncResult<NetSocket>> connectHandler,
int remainingAttempts) {
Objects.requireNonNull(host, "No null host accepted");
Objects.requireNonNull(connectHandler, "No null connectHandler accepted");
ContextImpl context = vertx.getOrCreateContext();
sslHelper.validate(vertx);
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(context.nettyEventLoop());
bootstrap.channel(NioSocketChannel.class);
applyConnectionOptions(bootstrap);
ChannelProvider channelProvider;
if (options.getProxyOptions() == null) {
channelProvider = ChannelProvider.INSTANCE;
} else {
channelProvider = ProxyChannelProvider.INSTANCE;
}
Handler<AsyncResult<Channel>> channelHandler = res -> {
if (res.succeeded()) {
Channel ch = res.result();
if (sslHelper.isSSL()) {
// TCP connected, so now we must do the SSL handshake
SslHandler sslHandler = sslHelper.createSslHandler(vertx, host, port);
ch.pipeline().addLast("ssl", sslHandler);
io.netty.util.concurrent.Future<Channel> fut = sslHandler.handshakeFuture();
fut.addListener(future2 -> {
if (future2.isSuccess()) {
connected(context, ch, connectHandler);
} else {
failed(context, ch, future2.cause(), connectHandler);
}
});
} else {
connected(context, ch, connectHandler);
}
} else {
if (remainingAttempts > 0 || remainingAttempts == -1) {
context.executeFromIO(() -> {
log.debug("Failed to create connection. Will retry in " + options.getReconnectInterval() + " milliseconds");
//Set a timer to retry connection
vertx.setTimer(options.getReconnectInterval(), tid ->
connect(port, host, connectHandler, remainingAttempts == -1 ? remainingAttempts : remainingAttempts - 1)
);
});
} else {
failed(context, null, res.cause(), connectHandler);
}
}
};
channelProvider.connect(vertx, bootstrap, options.getProxyOptions(), host, port, channelHandler);
}
private void connected(ContextImpl context, Channel ch, Handler<AsyncResult<NetSocket>> connectHandler) {
// Finish pipeline config
ChannelPipeline pipeline = ch.pipeline();
if (logEnabled) {
pipeline.addLast("logging", new LoggingHandler());
}
if (sslHelper.isSSL()) {
// only add ChunkedWriteHandler when SSL is enabled otherwise it is not needed as FileRegion is used.
pipeline.addLast("chunkedWriter", new ChunkedWriteHandler()); // For large file / sendfile support
}
if (options.getIdleTimeout() > 0) {
pipeline.addLast("idle", new IdleStateHandler(0, 0, options.getIdleTimeout()));
}
pipeline.addLast("handler", new VertxNetHandler(ch, socketMap));
// Need to set context before constructor is called as writehandler registration needs this
ContextImpl.setContext(context);
NetSocketImpl sock = new NetSocketImpl(vertx, ch, context, sslHelper, true, metrics, null);
VertxNetHandler handler = ch.pipeline().get(VertxNetHandler.class);
handler.conn = sock;
socketMap.put(ch, sock);
context.executeFromIO(() -> {
sock.setMetric(metrics.connected(sock.remoteAddress(), sock.remoteName()));
connectHandler.handle(Future.succeededFuture(sock));
});
}
private void failed(ContextImpl context, Channel ch, Throwable th, Handler<AsyncResult<NetSocket>> connectHandler) {
if (ch != null) {
ch.close();
}
context.executeFromIO(() -> doFailed(connectHandler, th));
}
private static void doFailed(Handler<AsyncResult<NetSocket>> connectHandler, Throwable th) {
connectHandler.handle(Future.failedFuture(th));
}
@Override
protected void finalize() throws Throwable {
// Make sure this gets cleaned up if there are no more references to it
// so as not to leave connections and resources dangling until the system is shutdown
// which could make the JVM run out of file handles.
close();
super.finalize();
}
}