-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
TcpIpConnection.java
315 lines (258 loc) · 8.86 KB
/
TcpIpConnection.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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
/*
* Copyright (c) 2008-2019, Hazelcast, Inc. All Rights Reserved.
*
* 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.hazelcast.nio.tcp;
import com.hazelcast.internal.metrics.Probe;
import com.hazelcast.internal.networking.Channel;
import com.hazelcast.internal.networking.Networking;
import com.hazelcast.internal.networking.OutboundFrame;
import com.hazelcast.logging.ILogger;
import com.hazelcast.nio.Address;
import com.hazelcast.nio.Connection;
import com.hazelcast.nio.ConnectionLifecycleListener;
import com.hazelcast.nio.ConnectionType;
import com.hazelcast.nio.IOService;
import java.io.EOFException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.channels.CancelledKeyException;
import java.util.Arrays;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import static com.hazelcast.nio.ConnectionType.MEMBER;
import static com.hazelcast.nio.ConnectionType.NONE;
/**
* The Tcp/Ip implementation of the {@link com.hazelcast.nio.Connection}.
* <p>
* A {@link TcpIpConnection} is not responsible for reading or writing data to the socket; that is task of
* the {@link Channel}.
*
* @see Networking
*/
@SuppressWarnings("checkstyle:methodcount")
public class TcpIpConnection
implements Connection {
private final Channel channel;
private final TcpIpEndpointManager endpointManager;
private final AtomicBoolean alive = new AtomicBoolean(true);
// indicate whether connection bind exchange is in progress/done (true) or not yet initiated (when false)
private final AtomicBoolean binding = new AtomicBoolean();
private final ILogger logger;
private final int connectionId;
private final IOService ioService;
private Address endPoint;
private TcpIpConnectionErrorHandler errorHandler;
private volatile ConnectionType type = NONE;
private volatile ConnectionLifecycleListener lifecycleListener;
private volatile Throwable closeCause;
private volatile String closeReason;
public TcpIpConnection(TcpIpEndpointManager endpointManager,
ConnectionLifecycleListener lifecycleListener,
int connectionId,
Channel channel) {
this.connectionId = connectionId;
this.endpointManager = endpointManager;
this.lifecycleListener = lifecycleListener;
this.ioService = endpointManager.getNetworkingService().getIoService();
this.logger = ioService.getLoggingService().getLogger(TcpIpConnection.class);
this.channel = channel;
channel.attributeMap().put(TcpIpConnection.class, this);
}
public Channel getChannel() {
return channel;
}
@Override
public ConnectionType getType() {
return type;
}
@Override
public void setType(ConnectionType type) {
if (this.type != NONE) {
return;
}
this.type = type;
if (type == MEMBER) {
logger.info("Initialized new cluster connection between "
+ channel.localSocketAddress() + " and " + channel.remoteSocketAddress());
}
}
@Probe
private int getConnectionType() {
ConnectionType t = type;
return t == null ? -1 : t.ordinal();
}
public TcpIpEndpointManager getEndpointManager() {
return endpointManager;
}
@Override
public InetAddress getInetAddress() {
return channel.socket().getInetAddress();
}
@Override
public int getPort() {
return channel.socket().getPort();
}
@Override
public InetSocketAddress getRemoteSocketAddress() {
return (InetSocketAddress) channel.remoteSocketAddress();
}
@Override
public boolean isAlive() {
return alive.get();
}
@Override
public long lastWriteTimeMillis() {
return channel.lastWriteTimeMillis();
}
@Override
public long lastReadTimeMillis() {
return channel.lastReadTimeMillis();
}
@Override
public Address getEndPoint() {
return endPoint;
}
public void setEndPoint(Address endPoint) {
this.endPoint = endPoint;
}
public void setErrorHandler(TcpIpConnectionErrorHandler errorHandler) {
this.errorHandler = errorHandler;
}
public int getConnectionId() {
return connectionId;
}
@Override
public boolean isClient() {
ConnectionType t = type;
return t != null && t != NONE && t.isClient();
}
@Override
public boolean write(OutboundFrame frame) {
if (channel.write(frame)) {
return true;
}
if (logger.isFinestEnabled()) {
logger.finest("Connection is closed, won't write packet -> " + frame);
}
return false;
}
@Override
public int hashCode() {
return hash(channel.isClientMode(), connectionId);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
TcpIpConnection other = (TcpIpConnection) obj;
return channel.isClientMode() == other.channel.isClientMode() && connectionId == other.connectionId
&& equals(endPoint, other.endPoint);
}
@Override
public void close(String reason, Throwable cause) {
if (!alive.compareAndSet(true, false)) {
// it is already closed.
return;
}
this.closeCause = cause;
this.closeReason = reason;
logClose();
try {
channel.close();
} catch (Exception e) {
logger.warning(e);
}
lifecycleListener.onConnectionClose(this, null, false);
ioService.onDisconnect(endPoint, cause);
if (cause != null && errorHandler != null) {
errorHandler.onError(cause);
}
}
public boolean setBinding() {
return binding.compareAndSet(false, true);
}
private void logClose() {
Level logLevel = resolveLogLevelOnClose();
if (!logger.isLoggable(logLevel)) {
return;
}
String message = toString() + " closed. Reason: ";
if (closeReason != null) {
message += closeReason;
} else if (closeCause != null) {
message += closeCause.getClass().getName() + "[" + closeCause.getMessage() + "]";
} else {
message += "Socket explicitly closed";
}
if (Level.FINEST.equals(logLevel)) {
logger.log(logLevel, message, closeCause);
} else if (closeCause == null || closeCause instanceof EOFException || closeCause instanceof CancelledKeyException) {
logger.log(logLevel, message);
} else {
logger.log(logLevel, message, closeCause);
}
}
private Level resolveLogLevelOnClose() {
if (!ioService.isActive()) {
return Level.FINEST;
}
if (closeCause == null || closeCause instanceof EOFException || closeCause instanceof CancelledKeyException) {
if (type == ConnectionType.REST_CLIENT || type == ConnectionType.MEMCACHE_CLIENT) {
// text-based clients are expected to come and go frequently.
return Level.FINE;
} else {
return Level.INFO;
}
} else {
return Level.WARNING;
}
}
@Override
public Throwable getCloseCause() {
return closeCause;
}
@Override
public String getCloseReason() {
if (closeReason == null) {
return closeCause == null ? null : closeCause.getMessage();
} else {
return closeReason;
}
}
@Override
public String toString() {
return "Connection[id=" + connectionId
+ ", " + channel.localSocketAddress() + "->" + channel.remoteSocketAddress()
+ ", qualifier=" + endpointManager.getEndpointQualifier()
+ ", endpoint=" + endPoint
+ ", alive=" + alive
+ ", type=" + type
+ "]";
}
private static int hash(Object... values) {
return Arrays.hashCode(values);
}
private static boolean equals(Object a, Object b) {
return (a == b) || (a != null && a.equals(b));
}
}