-
Notifications
You must be signed in to change notification settings - Fork 914
/
RemotingServiceImpl.java
817 lines (644 loc) · 28.8 KB
/
RemotingServiceImpl.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
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
/*
* 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 org.apache.activemq.artemis.core.remoting.server.impl;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.activemq.artemis.api.core.ActiveMQBuffer;
import org.apache.activemq.artemis.api.core.ActiveMQException;
import org.apache.activemq.artemis.api.core.ActiveMQInterruptedException;
import org.apache.activemq.artemis.api.core.ActiveMQRemoteDisconnectException;
import org.apache.activemq.artemis.api.core.BaseInterceptor;
import org.apache.activemq.artemis.api.core.Pair;
import org.apache.activemq.artemis.api.core.TransportConfiguration;
import org.apache.activemq.artemis.core.config.Configuration;
import org.apache.activemq.artemis.core.config.ConfigurationUtils;
import org.apache.activemq.artemis.core.protocol.core.CoreRemotingConnection;
import org.apache.activemq.artemis.core.protocol.core.impl.CoreProtocolManagerFactory;
import org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants;
import org.apache.activemq.artemis.core.remoting.server.RemotingService;
import org.apache.activemq.artemis.core.security.ActiveMQPrincipal;
import org.apache.activemq.artemis.core.server.ActiveMQComponent;
import org.apache.activemq.artemis.core.server.ActiveMQMessageBundle;
import org.apache.activemq.artemis.core.server.ActiveMQServer;
import org.apache.activemq.artemis.core.server.ActiveMQServerLogger;
import org.apache.activemq.artemis.core.server.ServiceRegistry;
import org.apache.activemq.artemis.core.server.cluster.ClusterConnection;
import org.apache.activemq.artemis.core.server.cluster.ClusterManager;
import org.apache.activemq.artemis.core.server.management.ManagementService;
import org.apache.activemq.artemis.spi.core.protocol.ConnectionEntry;
import org.apache.activemq.artemis.spi.core.protocol.MessagePersister;
import org.apache.activemq.artemis.spi.core.protocol.ProtocolManager;
import org.apache.activemq.artemis.spi.core.protocol.ProtocolManagerFactory;
import org.apache.activemq.artemis.spi.core.protocol.RemotingConnection;
import org.apache.activemq.artemis.spi.core.remoting.Acceptor;
import org.apache.activemq.artemis.spi.core.remoting.AcceptorFactory;
import org.apache.activemq.artemis.spi.core.remoting.BufferHandler;
import org.apache.activemq.artemis.spi.core.remoting.Connection;
import org.apache.activemq.artemis.spi.core.remoting.ServerConnectionLifeCycleListener;
import org.apache.activemq.artemis.utils.ActiveMQThreadFactory;
import org.apache.activemq.artemis.utils.ConfigurationHelper;
import org.apache.activemq.artemis.utils.ReusableLatch;
import org.jboss.logging.Logger;
public class RemotingServiceImpl implements RemotingService, ServerConnectionLifeCycleListener {
// Constants -----------------------------------------------------
private static final Logger logger = Logger.getLogger(RemotingServiceImpl.class);
private static final int ACCEPTOR_STOP_TIMEOUT = 3000;
// Attributes ----------------------------------------------------
private volatile boolean started = false;
private final Set<TransportConfiguration> acceptorsConfig;
private final List<BaseInterceptor> incomingInterceptors = new CopyOnWriteArrayList<>();
private final List<BaseInterceptor> outgoingInterceptors = new CopyOnWriteArrayList<>();
private final Map<String, Acceptor> acceptors = new HashMap<>();
private final Map<Object, ConnectionEntry> connections = new ConcurrentHashMap<>();
private final ReusableLatch connectionCountLatch = new ReusableLatch(0);
private final ActiveMQServer server;
private final ManagementService managementService;
private ExecutorService threadPool;
private final Executor flushExecutor;
private final ScheduledExecutorService scheduledThreadPool;
private FailureCheckAndFlushThread failureCheckAndFlushThread;
private final ClusterManager clusterManager;
private final Map<String, ProtocolManagerFactory> protocolMap = new ConcurrentHashMap<>();
private ActiveMQPrincipal defaultInvmSecurityPrincipal;
private ServiceRegistry serviceRegistry;
private boolean paused = false;
private AtomicLong totalConnectionCount = new AtomicLong(0);
private long connectionTtlCheckInterval;
// Static --------------------------------------------------------
// Constructors --------------------------------------------------
public RemotingServiceImpl(final ClusterManager clusterManager,
final Configuration config,
final ActiveMQServer server,
final ManagementService managementService,
final ScheduledExecutorService scheduledThreadPool,
List<ProtocolManagerFactory> protocolManagerFactories,
final Executor flushExecutor,
final ServiceRegistry serviceRegistry) {
this.serviceRegistry = serviceRegistry;
acceptorsConfig = config.getAcceptorConfigurations();
this.server = server;
this.clusterManager = clusterManager;
setInterceptors(config);
this.managementService = managementService;
this.scheduledThreadPool = scheduledThreadPool;
CoreProtocolManagerFactory coreProtocolManagerFactory = new CoreProtocolManagerFactory();
MessagePersister.getInstance().registerProtocol(coreProtocolManagerFactory);
this.flushExecutor = flushExecutor;
ActiveMQServerLogger.LOGGER.addingProtocolSupport(coreProtocolManagerFactory.getProtocols()[0], coreProtocolManagerFactory.getModuleName());
this.protocolMap.put(coreProtocolManagerFactory.getProtocols()[0], coreProtocolManagerFactory);
if (config.isResolveProtocols()) {
resolveProtocols(this.getClass().getClassLoader());
if (this.getClass().getClassLoader() != Thread.currentThread().getContextClassLoader()) {
resolveProtocols(Thread.currentThread().getContextClassLoader());
}
}
if (protocolManagerFactories != null) {
loadProtocolManagerFactories(protocolManagerFactories);
}
this.connectionTtlCheckInterval = config.getConnectionTtlCheckInterval();
}
private void setInterceptors(Configuration configuration) {
incomingInterceptors.addAll(serviceRegistry.getIncomingInterceptors(configuration.getIncomingInterceptorClassNames()));
outgoingInterceptors.addAll(serviceRegistry.getOutgoingInterceptors(configuration.getOutgoingInterceptorClassNames()));
}
@Override
public Map<String, ProtocolManagerFactory> getProtocolFactoryMap() {
return protocolMap;
}
@Override
public synchronized void start() throws Exception {
if (started) {
return;
}
logger.tracef("Starting remoting service %s", this);
paused = false;
// The remoting service maintains it's own thread pool for handling remoting traffic
// If OIO each connection will have it's own thread
// If NIO these are capped at nio-remoting-threads which defaults to num cores * 3
// This needs to be a different thread pool to the main thread pool especially for OIO where we may need
// to support many hundreds of connections, but the main thread pool must be kept small for better performance
ThreadFactory tFactory = AccessController.doPrivileged(new PrivilegedAction<ThreadFactory>() {
@Override
public ThreadFactory run() {
return new ActiveMQThreadFactory("ActiveMQ-remoting-threads-" + server.toString() +
"-" +
System.identityHashCode(this), false, Thread.currentThread().getContextClassLoader());
}
});
threadPool = Executors.newCachedThreadPool(tFactory);
for (TransportConfiguration info : acceptorsConfig) {
createAcceptor(info);
}
/**
* Don't start the acceptors here. Only start the acceptors at the every end of the start-up process to avoid
* race conditions. See {@link #startAcceptors()}.
*/
// This thread checks connections that need to be closed, and also flushes confirmations
failureCheckAndFlushThread = new FailureCheckAndFlushThread(connectionTtlCheckInterval);
failureCheckAndFlushThread.start();
started = true;
}
@Override
public Acceptor createAcceptor(String name, String uri) throws Exception {
List<TransportConfiguration> configurations = ConfigurationUtils.parseAcceptorURI(name, uri);
return createAcceptor(configurations.get(0));
}
@Override
public Acceptor createAcceptor(TransportConfiguration info) {
Acceptor acceptor = null;
try {
AcceptorFactory factory = server.getServiceRegistry().getAcceptorFactory(info.getName(), info.getFactoryClassName());
Map<String, ProtocolManagerFactory> selectedProtocolFactories = new ConcurrentHashMap<>();
@SuppressWarnings("deprecation")
String protocol = ConfigurationHelper.getStringProperty(TransportConstants.PROTOCOL_PROP_NAME, null, info.getParams());
if (protocol != null) {
ActiveMQServerLogger.LOGGER.warnDeprecatedProtocol();
locateProtocols(protocol, info, selectedProtocolFactories);
}
String protocols = ConfigurationHelper.getStringProperty(TransportConstants.PROTOCOLS_PROP_NAME, null, info.getParams());
if (protocols != null) {
locateProtocols(protocols, info, selectedProtocolFactories);
}
ClusterConnection clusterConnection = lookupClusterConnection(info);
// If empty: we get the default list
if (selectedProtocolFactories.isEmpty()) {
selectedProtocolFactories = protocolMap;
}
Map<String, ProtocolManager> selectedProtocols = new ConcurrentHashMap<>();
for (Entry<String, ProtocolManagerFactory> entry : selectedProtocolFactories.entrySet()) {
selectedProtocols.put(entry.getKey(), entry.getValue().createProtocolManager(server, info.getCombinedParams(), incomingInterceptors, outgoingInterceptors));
}
acceptor = factory.createAcceptor(info.getName(), clusterConnection, info.getParams(), new DelegatingBufferHandler(), this, threadPool, scheduledThreadPool, selectedProtocols);
if (defaultInvmSecurityPrincipal != null && acceptor.isUnsecurable()) {
acceptor.setDefaultActiveMQPrincipal(defaultInvmSecurityPrincipal);
}
acceptors.put(info.getName(), acceptor);
if (managementService != null) {
acceptor.setNotificationService(managementService);
managementService.registerAcceptor(acceptor, info);
}
} catch (Exception e) {
ActiveMQServerLogger.LOGGER.errorCreatingAcceptor(e, info.getFactoryClassName());
}
return acceptor;
}
/** No interface method, for tests only */
public Map<String, Acceptor> getAcceptors() {
return acceptors;
}
@Override
public void destroyAcceptor(String name) throws Exception {
Acceptor acceptor = acceptors.get(name);
if (acceptor != null) {
acceptor.stop();
acceptors.remove(name);
}
}
@Override
public synchronized void startAcceptors() throws Exception {
if (isStarted()) {
for (Acceptor a : acceptors.values()) {
a.start();
}
}
}
@Override
public synchronized void allowInvmSecurityOverride(ActiveMQPrincipal principal) {
defaultInvmSecurityPrincipal = principal;
for (Acceptor acceptor : acceptors.values()) {
if (acceptor.isUnsecurable()) {
acceptor.setDefaultActiveMQPrincipal(principal);
}
}
}
@Override
public synchronized void pauseAcceptors() {
if (!started)
return;
paused = true;
for (Acceptor acceptor : acceptors.values()) {
try {
acceptor.pause();
} catch (Exception e) {
ActiveMQServerLogger.LOGGER.errorStoppingAcceptor(acceptor.getName());
}
}
}
@Override
public synchronized boolean isPaused() {
return paused;
}
@Override
public synchronized void freeze(final String scaleDownNodeID, final CoreRemotingConnection connectionToKeepOpen) {
if (!started)
return;
failureCheckAndFlushThread.close(false);
HashMap<Object, ConnectionEntry> connectionEntries = new HashMap<>(connections);
// Now we ensure that no connections will process any more packets after this method is
// complete then send a disconnect packet
for (Entry<Object, ConnectionEntry> entry : connectionEntries.entrySet()) {
RemotingConnection conn = entry.getValue().connection;
if (conn.equals(connectionToKeepOpen))
continue;
if (logger.isTraceEnabled()) {
logger.trace("Sending connection.disconnection packet to " + conn);
}
if (!conn.isClient()) {
conn.disconnect(scaleDownNodeID, false);
removeConnection(entry.getKey());
}
}
}
@Override
public void stop(final boolean criticalError) throws Exception {
if (!started) {
return;
}
failureCheckAndFlushThread.close(criticalError);
// We need to stop them accepting first so no new connections are accepted after we send the disconnect message
for (Acceptor acceptor : acceptors.values()) {
if (logger.isDebugEnabled()) {
logger.debug("Pausing acceptor " + acceptor);
}
try {
acceptor.pause();
} catch (Throwable t) {
ActiveMQServerLogger.LOGGER.errorStoppingAcceptor(acceptor.getName());
}
}
if (logger.isDebugEnabled()) {
logger.debug("Sending disconnect on live connections");
}
HashSet<ConnectionEntry> connectionEntries = new HashSet<>(connections.values());
// Now we ensure that no connections will process any more packets after this method is complete
// then send a disconnect packet
for (ConnectionEntry entry : connectionEntries) {
RemotingConnection conn = entry.connection;
if (logger.isTraceEnabled()) {
logger.trace("Sending connection.disconnection packet to " + conn);
}
conn.disconnect(criticalError);
}
CountDownLatch acceptorCountDownLatch = new CountDownLatch(acceptors.size());
for (Acceptor acceptor : acceptors.values()) {
try {
acceptor.asyncStop(acceptorCountDownLatch::countDown);
} catch (Throwable t) {
ActiveMQServerLogger.LOGGER.errorStoppingAcceptor(acceptor.getName());
}
}
//In some cases an acceptor stopping could be locked ie NettyAcceptor stopping could be locked by a network failure.
acceptorCountDownLatch.await(ACCEPTOR_STOP_TIMEOUT, TimeUnit.MILLISECONDS);
acceptors.clear();
connections.clear();
connectionCountLatch.setCount(0);
if (managementService != null) {
managementService.unregisterAcceptors();
}
threadPool.shutdown();
if (!criticalError) {
boolean ok = threadPool.awaitTermination(10000, TimeUnit.MILLISECONDS);
if (!ok) {
ActiveMQServerLogger.LOGGER.timeoutRemotingThreadPool();
}
}
started = false;
}
@Override
public Acceptor getAcceptor(String name) {
return acceptors.get(name);
}
@Override
public boolean isStarted() {
return started;
}
private RemotingConnection getConnection(final Object remotingConnectionID) {
ConnectionEntry entry = connections.get(remotingConnectionID);
if (entry != null) {
return entry.connection;
} else {
ActiveMQServerLogger.LOGGER.errorRemovingConnection();
return null;
}
}
public ConnectionEntry getConnectionEntry(final Object remotingConnectionID) {
ConnectionEntry entry = connections.get(remotingConnectionID);
if (entry != null) {
return entry;
} else {
return null;
}
}
@Override
public RemotingConnection removeConnection(final Object remotingConnectionID) {
ConnectionEntry entry = connections.remove(remotingConnectionID);
if (entry != null) {
logger.debug("RemotingServiceImpl::removing connection ID " + remotingConnectionID);
connectionCountLatch.countDown();
return entry.connection;
} else {
logger.debug("The connectionID::" + remotingConnectionID + " was already removed by some other module");
return null;
}
}
@Override
public synchronized Set<RemotingConnection> getConnections() {
Set<RemotingConnection> conns = new HashSet<>(connections.size());
for (ConnectionEntry entry : connections.values()) {
conns.add(entry.connection);
}
return conns;
}
@Override
public long getTotalConnectionCount() {
return totalConnectionCount.get();
}
@Override
public synchronized ReusableLatch getConnectionCountLatch() {
return connectionCountLatch;
}
// ServerConnectionLifeCycleListener implementation -----------------------------------
private ProtocolManagerFactory getProtocolManager(String protocol) {
return protocolMap.get(protocol);
}
@Override
public void connectionCreated(final ActiveMQComponent component,
final Connection connection,
final ProtocolManager protocol) {
if (server == null) {
throw new IllegalStateException("Unable to create connection, server hasn't finished starting up");
}
ConnectionEntry entry = protocol.createConnectionEntry((Acceptor) component, connection);
try {
if (server.hasBrokerConnectionPlugins()) {
server.callBrokerConnectionPlugins(plugin -> plugin.afterCreateConnection(entry.connection));
}
} catch (ActiveMQException t) {
logger.warn("Error executing afterCreateConnection plugin method: {}", t.getMessage(), t);
throw new IllegalStateException(t.getMessage(), t.getCause());
}
if (logger.isTraceEnabled()) {
logger.trace("Connection created " + connection);
}
connections.put(connection.getID(), entry);
connectionCountLatch.countUp();
totalConnectionCount.incrementAndGet();
}
@Override
public void connectionDestroyed(final Object connectionID) {
if (logger.isTraceEnabled()) {
logger.trace("Connection removed " + connectionID + " from server " + this.server, new Exception("trace"));
}
issueFailure(connectionID, new ActiveMQRemoteDisconnectException());
}
private void issueFailure(Object connectionID, ActiveMQException e) {
ConnectionEntry conn = connections.get(connectionID);
if (conn != null && !conn.connection.isSupportReconnect()) {
RemotingConnection removedConnection = removeConnection(connectionID);
if (removedConnection != null) {
try {
if (server.hasBrokerConnectionPlugins()) {
server.callBrokerConnectionPlugins(plugin -> plugin.afterDestroyConnection(removedConnection));
}
} catch (ActiveMQException t) {
logger.warn("Error executing afterDestroyConnection plugin method: {}", t.getMessage(), t);
conn.connection.fail(t);
return;
}
}
conn.connection.fail(e);
}
}
@Override
public void connectionException(final Object connectionID, final ActiveMQException me) {
issueFailure(connectionID, me);
}
@Override
public void connectionReadyForWrites(final Object connectionID, final boolean ready) {
}
@Override
public void addIncomingInterceptor(final BaseInterceptor interceptor) {
incomingInterceptors.add(interceptor);
updateProtocols();
}
@Override
public List<BaseInterceptor> getIncomingInterceptors() {
return Collections.unmodifiableList(incomingInterceptors);
}
@Override
public boolean removeIncomingInterceptor(final BaseInterceptor interceptor) {
if (incomingInterceptors.remove(interceptor)) {
updateProtocols();
return true;
} else {
return false;
}
}
@Override
public void addOutgoingInterceptor(final BaseInterceptor interceptor) {
outgoingInterceptors.add(interceptor);
updateProtocols();
}
@Override
public List<BaseInterceptor> getOutgoinInterceptors() {
return Collections.unmodifiableList(outgoingInterceptors);
}
@Override
public boolean removeOutgoingInterceptor(final BaseInterceptor interceptor) {
if (outgoingInterceptors.remove(interceptor)) {
updateProtocols();
return true;
} else {
return false;
}
}
private ClusterConnection lookupClusterConnection(TransportConfiguration acceptorConfig) {
String clusterConnectionName = (String) acceptorConfig.getParams().get(org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants.CLUSTER_CONNECTION);
ClusterConnection clusterConnection = null;
if (clusterConnectionName != null) {
clusterConnection = clusterManager.getClusterConnection(clusterConnectionName);
}
// if not found we will still use the default name, even if a name was provided
if (clusterConnection == null) {
clusterConnection = clusterManager.getDefaultConnection(acceptorConfig);
}
return clusterConnection;
}
// Inner classes -------------------------------------------------
private final class DelegatingBufferHandler implements BufferHandler {
@Override
public void bufferReceived(final Object connectionID, final ActiveMQBuffer buffer) {
ConnectionEntry conn = connections.get(connectionID);
if (conn != null) {
try {
conn.connection.bufferReceived(connectionID, buffer);
} catch (RuntimeException e) {
ActiveMQServerLogger.LOGGER.disconnectCritical("Error decoding buffer", e);
conn.connection.fail(new ActiveMQException(e.getMessage()));
}
} else {
if (logger.isTraceEnabled()) {
logger.trace("ConnectionID = " + connectionID + " was already closed, so ignoring packet");
}
}
}
}
private final class FailureCheckAndFlushThread extends Thread {
private final long pauseInterval;
private volatile boolean closed;
private final CountDownLatch latch = new CountDownLatch(1);
FailureCheckAndFlushThread(final long pauseInterval) {
super("activemq-failure-check-thread");
this.pauseInterval = pauseInterval;
}
public void close(final boolean criticalError) {
closed = true;
latch.countDown();
if (!criticalError) {
try {
join();
} catch (InterruptedException e) {
throw new ActiveMQInterruptedException(e);
}
}
}
@Override
public void run() {
while (!closed) {
try {
long now = System.currentTimeMillis();
Set<Pair<Object, Long>> toRemove = new HashSet<>();
for (ConnectionEntry entry : connections.values()) {
final RemotingConnection conn = entry.connection;
boolean flush = true;
if (entry.ttl != -1) {
if (!conn.checkDataReceived()) {
if (now >= entry.lastCheck + entry.ttl) {
toRemove.add(new Pair<>(conn.getID(), entry.ttl));
flush = false;
}
} else {
entry.lastCheck = now;
}
}
if (flush) {
flushExecutor.execute(new Runnable() {
@Override
public void run() {
try {
// this is using a different thread
// as if anything wrong happens on flush
// failure detection could be affected
conn.scheduledFlush();
} catch (Throwable e) {
ActiveMQServerLogger.LOGGER.failedToFlushOutstandingDataFromTheConnection(e);
}
}
});
}
}
for (final Pair<Object, Long> pair : toRemove) {
final RemotingConnection conn = getConnection(pair.getA());
if (conn != null) {
// In certain cases (replicationManager for instance) calling fail could take some time
// We can't pause the FailureCheckAndFlushThread as that would lead other clients to fail for
// missing pings
flushExecutor.execute(new Runnable() {
@Override
public void run() {
conn.fail(ActiveMQMessageBundle.BUNDLE.clientExited(conn.getRemoteAddress(), pair.getB()));
}
});
removeConnection(pair.getA());
}
}
if (latch.await(pauseInterval, TimeUnit.MILLISECONDS))
return;
} catch (Throwable e) {
ActiveMQServerLogger.LOGGER.errorOnFailureCheck(e);
}
}
}
}
protected void updateProtocols() {
for (Acceptor acceptor : this.acceptors.values()) {
acceptor.updateInterceptors(incomingInterceptors, outgoingInterceptors);
}
}
/**
* Locates protocols from the internal default map and moves them into the input protocol map.
*
* @param protocolList
* @param transportConfig
* @param protocolMap
*/
private void locateProtocols(String protocolList,
Object transportConfig,
Map<String, ProtocolManagerFactory> protocolMap) {
String[] protocolsSplit = protocolList.split(",");
for (String protocolItem : protocolsSplit) {
ProtocolManagerFactory protocolManagerFactory = this.protocolMap.get(protocolItem);
if (protocolManagerFactory == null) {
ActiveMQServerLogger.LOGGER.noProtocolManagerFound(protocolItem, transportConfig.toString());
} else {
protocolMap.put(protocolItem, protocolManagerFactory);
}
}
}
/**
* Finds protocol support from a given classloader.
*
* @param loader
*/
private void resolveProtocols(ClassLoader loader) {
ServiceLoader<ProtocolManagerFactory> serviceLoader = ServiceLoader.load(ProtocolManagerFactory.class, loader);
loadProtocolManagerFactories(serviceLoader);
}
/**
* Loads the protocols found into a map.
*
* @param protocolManagerFactoryCollection
*/
private void loadProtocolManagerFactories(Iterable<ProtocolManagerFactory> protocolManagerFactoryCollection) {
for (ProtocolManagerFactory next : protocolManagerFactoryCollection) {
MessagePersister.registerProtocol(next);
String[] protocols = next.getProtocols();
for (String protocol : protocols) {
ActiveMQServerLogger.LOGGER.addingProtocolSupport(protocol, next.getModuleName());
protocolMap.put(protocol, next);
}
}
}
}