-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
FailoverClientConnectionFactory.java
457 lines (403 loc) · 14.1 KB
/
FailoverClientConnectionFactory.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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
/*
* Copyright 2002-2020 the original author or 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
*
* https://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 org.springframework.integration.ip.tcp.connection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicLong;
import javax.net.ssl.SSLSession;
import org.springframework.core.serializer.Deserializer;
import org.springframework.core.serializer.Serializer;
import org.springframework.integration.ip.IpHeaders;
import org.springframework.integration.support.AbstractIntegrationMessageBuilder;
import org.springframework.messaging.Message;
import org.springframework.util.Assert;
/**
* Given a list of connection factories, serves up {@link TcpConnection}s
* that can iterate over a connection from each factory until the write
* succeeds or the list is exhausted.
*
* @author Gary Russell
* @since 2.2
*
*/
public class FailoverClientConnectionFactory extends AbstractClientConnectionFactory {
private static final long DEFAULT_REFRESH_SHARED_INTERVAL = 0L;
private final List<AbstractClientConnectionFactory> factories;
private final boolean cachingDelegates;
private long refreshSharedInterval = DEFAULT_REFRESH_SHARED_INTERVAL;
private boolean closeOnRefresh;
private boolean failBack = true;
private volatile long creationTime;
/**
* Construct an instance with the provided delegate factories.
* @param factories the delegates.
*/
public FailoverClientConnectionFactory(List<AbstractClientConnectionFactory> factories) {
super("", 0);
Assert.notEmpty(factories, "At least one factory is required");
this.factories = new ArrayList<>(factories);
this.cachingDelegates = factories.stream()
.anyMatch(factory -> factory instanceof CachingClientConnectionFactory);
}
/**
* When using a shared connection {@link #setSingleUse(boolean) singleUse} is false,
* specify how long to wait before trying to fail back to start from the beginning of
* the factory list. Default is 0 for backwards compatibility to always try to get a
* connection to the primary server. If you don't want to fail back until the current
* connection is closed, set this to {@link Long#MAX_VALUE}.
* Cannot be changed when using {@link CachingClientConnectionFactory} delegates.
* @param refreshSharedInterval the interval in milliseconds.
* @since 4.3.22
* @see #setSingleUse(boolean)
* @see #setCloseOnRefresh(boolean)
*/
public void setRefreshSharedInterval(long refreshSharedInterval) {
Assert.isTrue(!this.cachingDelegates,
"'refreshSharedInterval' cannot be changed when using 'CachingClientConnectionFactory` delegates");
this.refreshSharedInterval = refreshSharedInterval;
this.failBack = refreshSharedInterval != Long.MAX_VALUE;
}
/**
* When using a shared connection {@link #setSingleUse(boolean) singleUse} is false,
* set this to true to close the old shared connection after a refresh. If this is
* false, the connection will remain open, but unused until its connection factory is
* again used to get a connection. Default is false for backwards compatibility.
* Cannot be changed when using {@link CachingClientConnectionFactory} delegates.
* @param closeOnRefresh true to close.
* @since 4.3.22
* @see #setSingleUse(boolean)
* @see #setRefreshSharedInterval(long)
*/
public void setCloseOnRefresh(boolean closeOnRefresh) {
Assert.isTrue(!this.cachingDelegates,
"'closeOnRefresh' cannot be changed when using 'CachingClientConnectionFactory` delegates");
this.closeOnRefresh = closeOnRefresh;
}
@Override
protected void onInit() {
super.onInit();
for (AbstractClientConnectionFactory factory : this.factories) {
Assert.state(!(this.isSingleUse() ^ factory.isSingleUse()),
"Inconsistent singleUse - delegate factories must match this one");
factory.enableManualListenerRegistration();
}
}
/**
* Delegate TCP Client Connection factories that are used to receive
* data need a Listener to send the messages to.
* This applies to client factories used for outbound gateways
* or for a pair of collaborating channel adapters.
* <p>
* During initialization, if a factory detects it has no listener
* it's listening logic (active thread) is terminated.
* <p>
* The listener registered with a factory is provided to each
* connection it creates so it can call the onMessage() method.
* <p>
* This code satisfies the first requirement in that this
* listener signals to the factory that it needs to run
* its listening logic.
* <p>
* When we wrap actual connections with FailoverTcpConnections,
* the connection is given the wrapper as a listener, so it
* can enhance the headers in onMessage(); the wrapper then invokes
* the real listener supplied here, with the modified message.
*/
@Override
public void registerListener(TcpListener listener) {
super.registerListener(listener);
}
@Override
public void registerSender(TcpSender sender) {
for (AbstractClientConnectionFactory factory : this.factories) {
factory.registerSender(sender);
}
}
@Override
protected TcpConnectionSupport obtainConnection() throws Exception {
FailoverTcpConnection sharedConnection = (FailoverTcpConnection) getTheConnection();
boolean shared = !isSingleUse() && !this.cachingDelegates;
boolean refreshShared = this.failBack && shared
&& sharedConnection != null
&& System.currentTimeMillis() > this.creationTime + this.refreshSharedInterval;
if (sharedConnection != null && sharedConnection.isOpen() && !refreshShared) {
sharedConnection.incrementEpoch();
return sharedConnection;
}
FailoverTcpConnection failoverTcpConnection = new FailoverTcpConnection(this.factories);
if (getListener() != null) {
failoverTcpConnection.registerListener(getListener());
}
failoverTcpConnection.incrementEpoch();
if (shared) {
this.creationTime = System.currentTimeMillis();
/*
* We may have simply wrapped the same connection in a new wrapper; don't close.
*/
if (refreshShared && this.closeOnRefresh
&& !sharedConnection.delegate.equals(failoverTcpConnection.delegate)
&& sharedConnection.isOpen()) {
sharedConnection.close();
}
setTheConnection(failoverTcpConnection);
}
return failoverTcpConnection;
}
@Override
public void start() {
for (AbstractClientConnectionFactory factory : this.factories) {
factory.enableManualListenerRegistration();
factory.start();
}
setActive(true);
super.start();
}
@Override
public void stop() {
this.setActive(false);
for (AbstractClientConnectionFactory factory : this.factories) {
factory.stop();
}
}
/**
* Returns true if all factories are running
*/
@Override
public boolean isRunning() {
boolean isRunning = true;
for (AbstractClientConnectionFactory factory : this.factories) {
isRunning = !isRunning ? false : factory.isRunning();
}
return isRunning;
}
/**
* Wrapper for a list of factories; delegates to a connection from
* one of those factories and fails over to another if necessary.
* @author Gary Russell
* @since 2.2
*
*/
private final class FailoverTcpConnection extends TcpConnectionSupport implements TcpListener {
private final List<AbstractClientConnectionFactory> factories;
private final String connectionId;
private final AtomicLong epoch = new AtomicLong();
private volatile Iterator<AbstractClientConnectionFactory> factoryIterator;
private volatile AbstractClientConnectionFactory currentFactory;
volatile TcpConnectionSupport delegate; // NOSONAR visibility
private volatile boolean open = true;
private FailoverTcpConnection(List<AbstractClientConnectionFactory> factories) throws Exception {
this.factories = factories;
this.factoryIterator = factories.iterator();
findAConnection();
this.connectionId = UUID.randomUUID().toString();
}
void incrementEpoch() {
this.epoch.incrementAndGet();
}
/**
* Finds a connection from the underlying list of factories. If necessary,
* each factory is tried; including the current one if we wrap around.
* This allows for the condition where the current connection is closed,
* the current factory can serve up a new connection, but all other
* factories are down.
* @throws Exception if an exception occurs
*/
private synchronized void findAConnection() throws Exception {
boolean success = false;
AbstractClientConnectionFactory lastFactoryToTry = this.currentFactory;
AbstractClientConnectionFactory nextFactory = null;
if (!this.factoryIterator.hasNext()) {
this.factoryIterator = this.factories.iterator();
}
boolean retried = false;
while (!success) {
try {
nextFactory = this.factoryIterator.next();
this.delegate = nextFactory.getConnection();
if (logger.isDebugEnabled()) {
logger.debug("Got " + this.delegate.getConnectionId() + " from " + nextFactory);
}
this.delegate.registerListener(this);
this.currentFactory = nextFactory;
success = this.delegate.isOpen();
}
catch (Exception e) {
if (logger.isDebugEnabled()) {
logger.debug(nextFactory + " failed with "
+ e.toString()
+ ", trying another");
}
if (!this.factoryIterator.hasNext()) {
if (retried && lastFactoryToTry == null || lastFactoryToTry == nextFactory) {
/*
* We've tried every factory including the
* one the current connection was on.
*/
this.open = false;
throw e;
}
this.factoryIterator = this.factories.iterator();
retried = true;
}
}
}
}
@Override
public void close() {
this.delegate.close();
this.open = false;
}
@Override
public boolean isOpen() {
return this.open;
}
/**
* Sends to the current connection; if it fails, attempts to
* send to a new connection obtained from {@link #findAConnection()}.
* If send fails on a connection from every factory, we give up.
*/
@Override
public synchronized void send(Message<?> message) throws Exception {
boolean success = false;
AbstractClientConnectionFactory lastFactoryToTry = this.currentFactory;
AbstractClientConnectionFactory lastFactoryTried = null;
boolean retried = false;
while (!success) {
try {
lastFactoryTried = this.currentFactory;
this.delegate.send(message);
success = true;
}
catch (Exception e) {
if (retried && lastFactoryTried == lastFactoryToTry) {
logger.error("All connection factories exhausted", e);
this.open = false;
throw e;
}
retried = true;
if (logger.isDebugEnabled()) {
logger.debug("Send to " + this.delegate.getConnectionId() + " failed; attempting failover", e);
}
this.delegate.close();
findAConnection();
if (logger.isDebugEnabled()) {
logger.debug("Failing over to " + this.delegate.getConnectionId());
}
}
}
}
@Override
public Object getPayload() throws Exception {
return this.delegate.getPayload();
}
@Override
public void run() {
throw new UnsupportedOperationException("Not supported on FailoverTcpConnection");
}
@Override
public String getHostName() {
return this.delegate.getHostName();
}
@Override
public String getHostAddress() {
return this.delegate.getHostAddress();
}
@Override
public int getPort() {
return this.delegate.getPort();
}
@Override
public Object getDeserializerStateKey() {
return this.delegate.getDeserializerStateKey();
}
@Override
public void registerSender(TcpSender sender) {
this.delegate.registerSender(sender);
}
@Override
public String getConnectionId() {
return this.connectionId + ":" + this.epoch;
}
@Override
public SocketInfo getSocketInfo() {
return this.delegate.getSocketInfo();
}
@Override
public boolean isServer() {
return this.delegate.isServer();
}
@Override
public void setMapper(TcpMessageMapper mapper) {
this.delegate.setMapper(mapper);
}
@Override
public Deserializer<?> getDeserializer() {
return this.delegate.getDeserializer();
}
@Override
public void setDeserializer(Deserializer<?> deserializer) {
this.delegate.setDeserializer(deserializer);
}
@Override
public Serializer<?> getSerializer() {
return this.delegate.getSerializer();
}
@Override
public void setSerializer(Serializer<?> serializer) {
this.delegate.setSerializer(serializer);
}
@Override
public SSLSession getSslSession() {
return this.delegate.getSslSession();
}
/**
* We have to intercept the message to replace the connectionId header with
* ours so the listener can correlate a response with a request. We supply
* the actual connectionId in another header for convenience and tracing
* purposes.
*/
@Override
public boolean onMessage(Message<?> message) {
if (this.delegate.getConnectionId().equals(message.getHeaders().get(IpHeaders.CONNECTION_ID))) {
AbstractIntegrationMessageBuilder<?> messageBuilder = FailoverClientConnectionFactory.this
.getMessageBuilderFactory().fromMessage(message)
.setHeader(IpHeaders.CONNECTION_ID, this.getConnectionId());
if (message.getHeaders().get(IpHeaders.ACTUAL_CONNECTION_ID) == null) {
messageBuilder.setHeader(IpHeaders.ACTUAL_CONNECTION_ID,
message.getHeaders().get(IpHeaders.CONNECTION_ID));
}
TcpListener listener = getListener();
if (listener == null) {
if (this.logger.isDebugEnabled()) {
logger.debug("No listener for " + message);
}
return false;
}
else {
return listener.onMessage(messageBuilder.build());
}
}
else {
if (logger.isDebugEnabled()) {
logger.debug("Message from defunct connection ignored " + message);
}
return false;
}
}
}
}