-
Notifications
You must be signed in to change notification settings - Fork 912
/
ClusterTestBase.java
2075 lines (1635 loc) · 81.9 KB
/
ClusterTestBase.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
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* 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.tests.integration.cluster.distribution;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration;
import org.apache.activemq.artemis.api.core.ActiveMQException;
import org.apache.activemq.artemis.api.core.BroadcastGroupConfiguration;
import org.apache.activemq.artemis.api.core.DiscoveryGroupConfiguration;
import org.apache.activemq.artemis.api.core.Message;
import org.apache.activemq.artemis.api.core.QueueConfiguration;
import org.apache.activemq.artemis.api.core.SimpleString;
import org.apache.activemq.artemis.api.core.TransportConfiguration;
import org.apache.activemq.artemis.api.core.UDPBroadcastEndpointFactory;
import org.apache.activemq.artemis.api.core.client.ActiveMQClient;
import org.apache.activemq.artemis.api.core.client.ClientConsumer;
import org.apache.activemq.artemis.api.core.client.ClientMessage;
import org.apache.activemq.artemis.api.core.client.ClientProducer;
import org.apache.activemq.artemis.api.core.client.ClientSession;
import org.apache.activemq.artemis.api.core.client.ClientSessionFactory;
import org.apache.activemq.artemis.api.core.client.ServerLocator;
import org.apache.activemq.artemis.core.client.impl.ServerLocatorInternal;
import org.apache.activemq.artemis.core.client.impl.Topology;
import org.apache.activemq.artemis.core.client.impl.TopologyMemberImpl;
import org.apache.activemq.artemis.core.config.ClusterConnectionConfiguration;
import org.apache.activemq.artemis.core.config.Configuration;
import org.apache.activemq.artemis.core.config.HAPolicyConfiguration;
import org.apache.activemq.artemis.core.config.ha.DistributedPrimitiveManagerConfiguration;
import org.apache.activemq.artemis.core.config.ha.LiveOnlyPolicyConfiguration;
import org.apache.activemq.artemis.core.config.ha.ReplicaPolicyConfiguration;
import org.apache.activemq.artemis.core.config.ha.ReplicatedPolicyConfiguration;
import org.apache.activemq.artemis.core.config.ha.ReplicationBackupPolicyConfiguration;
import org.apache.activemq.artemis.core.config.ha.ReplicationPrimaryPolicyConfiguration;
import org.apache.activemq.artemis.core.config.ha.SharedStoreMasterPolicyConfiguration;
import org.apache.activemq.artemis.core.config.ha.SharedStoreSlavePolicyConfiguration;
import org.apache.activemq.artemis.core.postoffice.Binding;
import org.apache.activemq.artemis.core.postoffice.Bindings;
import org.apache.activemq.artemis.core.postoffice.PostOffice;
import org.apache.activemq.artemis.core.postoffice.QueueBinding;
import org.apache.activemq.artemis.core.postoffice.impl.LocalQueueBinding;
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.server.ActiveMQServer;
import org.apache.activemq.artemis.core.server.ActiveMQServers;
import org.apache.activemq.artemis.api.core.RoutingType;
import org.apache.activemq.artemis.core.server.NodeManager;
import org.apache.activemq.artemis.core.server.cluster.ActiveMQServerSideProtocolManagerFactory;
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.cluster.RemoteQueueBinding;
import org.apache.activemq.artemis.core.server.cluster.impl.BridgeMetrics;
import org.apache.activemq.artemis.core.server.cluster.impl.ClusterConnectionImpl;
import org.apache.activemq.artemis.core.server.cluster.impl.ClusterConnectionMetrics;
import org.apache.activemq.artemis.core.server.cluster.impl.MessageLoadBalancingType;
import org.apache.activemq.artemis.core.server.cluster.qourum.SharedNothingBackupQuorum;
import org.apache.activemq.artemis.core.server.group.GroupingHandler;
import org.apache.activemq.artemis.core.server.group.impl.GroupingHandlerConfiguration;
import org.apache.activemq.artemis.core.server.impl.AddressInfo;
import org.apache.activemq.artemis.core.server.impl.InVMNodeManager;
import org.apache.activemq.artemis.quorum.file.FileBasedPrimitiveManager;
import org.apache.activemq.artemis.tests.util.ActiveMQTestBase;
import org.apache.activemq.artemis.utils.PortCheckRule;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.ClassRule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.invoke.MethodHandles;
public abstract class ClusterTestBase extends ActiveMQTestBase {
private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
private static final int[] PORTS = {TransportConstants.DEFAULT_PORT, TransportConstants.DEFAULT_PORT + 1, TransportConstants.DEFAULT_PORT + 2, TransportConstants.DEFAULT_PORT + 3, TransportConstants.DEFAULT_PORT + 4, TransportConstants.DEFAULT_PORT + 5, TransportConstants.DEFAULT_PORT + 6, TransportConstants.DEFAULT_PORT + 7, TransportConstants.DEFAULT_PORT + 8, TransportConstants.DEFAULT_PORT + 9,};
@ClassRule
public static PortCheckRule rule = new PortCheckRule(PORTS);
protected int getLargeMessageSize() {
return 500;
}
protected boolean isLargeMessage() {
return false;
}
private static final long TIMEOUT_START_SERVER = 10;
private static final SimpleString COUNT_PROP = new SimpleString("count_prop");
protected static final SimpleString FILTER_PROP = new SimpleString("animal");
private static final int MAX_SERVERS = 10;
protected ConsumerHolder[] consumers;
protected ActiveMQServer[] servers;
protected NodeManager[] nodeManagers;
protected ClientSessionFactory[] sfs;
protected long[] timeStarts;
protected ServerLocator[] locators;
protected boolean isForceUniqueStorageManagerIds() {
return true;
}
private DistributedPrimitiveManagerConfiguration pluggableQuorumConfiguration = null;
private DistributedPrimitiveManagerConfiguration getOrCreatePluggableQuorumConfiguration() {
if (pluggableQuorumConfiguration != null) {
return pluggableQuorumConfiguration;
}
try {
pluggableQuorumConfiguration = new DistributedPrimitiveManagerConfiguration(FileBasedPrimitiveManager.class.getName(), Collections.singletonMap("locks-folder", temporaryFolder.newFolder("manager").toString()));
} catch (IOException ioException) {
logger.error(ioException.getMessage(), ioException);
return null;
}
return pluggableQuorumConfiguration;
}
@Override
@Before
public void setUp() throws Exception {
super.setUp();
forceGC();
consumers = new ConsumerHolder[ClusterTestBase.MAX_CONSUMERS];
servers = new ActiveMQServer[ClusterTestBase.MAX_SERVERS];
timeStarts = new long[ClusterTestBase.MAX_SERVERS];
sfs = new ClientSessionFactory[ClusterTestBase.MAX_SERVERS];
nodeManagers = new NodeManager[ClusterTestBase.MAX_SERVERS];
for (int i = 0, nodeManagersLength = nodeManagers.length; i < nodeManagersLength; i++) {
nodeManagers[i] = new InVMNodeManager(isSharedStore(), new File(getJournalDir(i, true)));
}
locators = new ServerLocator[ClusterTestBase.MAX_SERVERS];
}
public enum HAType {
SharedStore, SharedNothingReplication, PluggableQuorumReplication
}
protected HAType haType() {
return HAType.SharedNothingReplication;
}
/**
* Whether the servers share the storage or not.
*/
protected final boolean isSharedStore() {
return HAType.SharedStore.equals(haType());
}
@Override
@After
public void tearDown() throws Exception {
logTopologyDiagram();
for (int i = 0; i < MAX_SERVERS; i++) {
addActiveMQComponent(nodeManagers[i]);
}
servers = null;
sfs = null;
consumers = new ConsumerHolder[ClusterTestBase.MAX_CONSUMERS];
nodeManagers = null;
super.tearDown();
}
private static final int MAX_CONSUMERS = 100;
protected static class ConsumerHolder {
final ClientConsumer consumer;
final ClientSession session;
final int id;
final int node;
public ClientConsumer getConsumer() {
return consumer;
}
public ClientSession getSession() {
return session;
}
public int getId() {
return id;
}
public int getNode() {
return node;
}
ConsumerHolder(final int id, final ClientConsumer consumer, final ClientSession session, int node) {
this.id = id;
this.node = node;
this.consumer = consumer;
this.session = session;
}
void close() {
if (consumer != null) {
try {
consumer.close();
} catch (ActiveMQException e) {
// ignore
}
}
if (session != null) {
try {
session.close();
} catch (ActiveMQException e) {
// ignore
}
}
}
@Override
public String toString() {
return "id=" + id + ", consumer=" + consumer + ", session=" + session;
}
}
protected ClientConsumer getConsumer(final int node) {
return consumers[node].consumer;
}
protected void waitForFailoverTopology(final int bNode, final int... nodes) throws Exception {
ActiveMQServer server = servers[bNode];
if (logger.isDebugEnabled()) {
logger.debug("waiting for {} on the topology for server = {}", Arrays.toString(nodes), server);
}
long start = System.currentTimeMillis();
final int waitMillis = 2000;
final int sleepTime = 50;
int nWaits = 0;
while (server.getClusterManager() == null && nWaits++ < waitMillis / sleepTime) {
Thread.sleep(sleepTime);
}
Set<ClusterConnection> ccs = server.getClusterManager().getClusterConnections();
if (ccs.size() != 1) {
throw new IllegalStateException("You need a single cluster connection on this version of waitForTopology on ServiceTestBase");
}
boolean exists = false;
for (int node : nodes) {
ClusterConnectionImpl clusterConnection = (ClusterConnectionImpl) ccs.iterator().next();
Topology topology = clusterConnection.getTopology();
TransportConfiguration nodeConnector = servers[node].getClusterManager().getClusterConnections().iterator().next().getConnector();
do {
Collection<TopologyMemberImpl> members = topology.getMembers();
for (TopologyMemberImpl member : members) {
if (member.getConnector().getA() != null && member.getConnector().getA().equals(nodeConnector)) {
exists = true;
break;
}
}
if (exists) {
break;
}
Thread.sleep(10);
}
while (System.currentTimeMillis() - start < WAIT_TIMEOUT);
if (!exists) {
String msg = "Timed out waiting for cluster topology of " + Arrays.toString(nodes) +
" (received " +
topology.getMembers().size() +
") topology = " +
topology +
")";
logger.error(msg);
logTopologyDiagram();
throw new Exception(msg);
}
}
}
private void logTopologyDiagram() {
if (!logger.isDebugEnabled()) {
return;
}
try {
StringBuffer topologyDiagram = new StringBuffer();
for (ActiveMQServer activeMQServer : servers) {
if (activeMQServer != null) {
topologyDiagram.append("\n").append(activeMQServer.getIdentity()).append("\n");
if (activeMQServer.isStarted()) {
Set<ClusterConnection> ccs = activeMQServer.getClusterManager().getClusterConnections();
if (ccs.size() >= 1) {
ClusterConnectionImpl clusterConnection = (ClusterConnectionImpl) ccs.iterator().next();
Collection<TopologyMemberImpl> members = clusterConnection.getTopology().getMembers();
for (TopologyMemberImpl member : members) {
String nodeId = member.getNodeId();
String liveServer = null;
String backupServer = null;
for (ActiveMQServer server : servers) {
if (server != null && server.getNodeID() != null && server.isActive() && server.getNodeID().toString().equals(nodeId)) {
if (server.isActive()) {
liveServer = server.getIdentity();
if (member.getLive() != null) {
liveServer += "(notified)";
} else {
liveServer += "(not notified)";
}
} else {
backupServer = server.getIdentity();
if (member.getBackup() != null) {
liveServer += "(notified)";
} else {
liveServer += "(not notified)";
}
}
}
}
topologyDiagram.append("\t").append("|\n").append("\t->").append(liveServer).append("/").append(backupServer).append("\n");
}
} else {
topologyDiagram.append("-> no cluster connections\n");
}
} else {
topologyDiagram.append("-> stopped\n");
}
}
}
topologyDiagram.append("\n");
logger.debug(topologyDiagram.toString());
} catch (Throwable e) {
logger.warn(String.format("error printing the topology::%s", e.getMessage()), e);
}
}
protected void waitForMessages(final int node, final String address, final int count) throws Exception {
ActiveMQServer server = servers[node];
if (server == null) {
throw new IllegalArgumentException("No server at " + node);
}
PostOffice po = server.getPostOffice();
long start = System.currentTimeMillis();
int messageCount = 0;
do {
messageCount = getMessageCount(po, address);
if (messageCount == count) {
return;
}
Thread.sleep(10);
}
while (System.currentTimeMillis() - start < ActiveMQTestBase.WAIT_TIMEOUT);
throw new IllegalStateException("Timed out waiting for messages (messageCount = " + messageCount +
", expecting = " +
count);
}
protected void waitForServerRestart(final int node) throws Exception {
long waitTimeout = ActiveMQTestBase.WAIT_TIMEOUT;
if (!isSharedStore()) {
//it should be greater than
//QuorumManager.WAIT_TIME_AFTER_FIRST_LIVE_STOPPING_MSG (60 sec)
waitTimeout = 1000 * (SharedNothingBackupQuorum.WAIT_TIME_AFTER_FIRST_LIVE_STOPPING_MSG + 5);
}
if (!servers[node].waitForActivation(waitTimeout, TimeUnit.MILLISECONDS)) {
String msg = "Timed out waiting for server starting = " + node;
logger.error(msg);
throw new IllegalStateException(msg);
}
}
protected void waitForBindings(final int node,
final String address,
final int expectedBindingCount,
final int expectedConsumerCount,
final boolean local) throws Exception {
if (logger.isDebugEnabled()) {
logger.debug("waiting for bindings on node {} address {} expectedBindingCount {} consumerCount {} local {}",
node, address, expectedBindingCount, expectedConsumerCount, local);
}
ActiveMQServer server = servers[node];
if (server == null) {
throw new IllegalArgumentException("No server at " + node);
}
long timeout = ActiveMQTestBase.WAIT_TIMEOUT;
if (waitForBindings(server, address, local, expectedBindingCount, expectedConsumerCount, timeout)) {
return;
}
PostOffice po = server.getPostOffice();
Bindings bindings = po.getBindingsForAddress(new SimpleString(address));
logger.debug("=======================================================================");
logger.debug("Binding information for address = {} on node {}", address, node);
for (Binding binding : bindings.getBindings()) {
if (binding.isConnected() && (binding instanceof LocalQueueBinding && local || binding instanceof RemoteQueueBinding && !local)) {
QueueBinding qBinding = (QueueBinding) binding;
logger.debug("Binding = {}, queue={}", qBinding, qBinding.getQueue());
}
}
StringWriter writer = new StringWriter();
PrintWriter out = new PrintWriter(writer);
try {
for (ActiveMQServer activeMQServer : servers) {
if (activeMQServer != null) {
out.println(clusterDescription(activeMQServer));
out.println(debugBindings(activeMQServer, activeMQServer.getConfiguration().getManagementNotificationAddress().toString()));
}
}
for (ActiveMQServer activeMQServer : servers) {
out.println("Management bindings on " + activeMQServer);
if (activeMQServer != null) {
out.println(debugBindings(activeMQServer, activeMQServer.getConfiguration().getManagementNotificationAddress().toString()));
}
}
} catch (Throwable dontCare) {
}
logAndSystemOut(writer.toString());
throw new IllegalStateException("Didn't get the expected number of bindings, look at the logging for more information");
}
protected String debugBindings(final ActiveMQServer server, final String address) throws Exception {
StringWriter str = new StringWriter();
PrintWriter out = new PrintWriter(str);
if (server == null) {
return "server is shutdown";
}
PostOffice po = server.getPostOffice();
if (po == null) {
return "server is shutdown";
}
Bindings bindings = po.getBindingsForAddress(new SimpleString(address));
out.println("=======================================================================");
out.println("Binding information for address = " + address + " on " + server);
for (Binding binding : bindings.getBindings()) {
QueueBinding qBinding = (QueueBinding) binding;
out.println("Binding = " + qBinding + ", queue=" + qBinding.getQueue());
}
out.println("=======================================================================");
return str.toString();
}
protected void createQueue(final int node,
final String address,
final String queueName,
final String filterVal,
final boolean durable) throws Exception {
createQueue(node, address, queueName, filterVal, durable, null, null);
}
protected void createQueue(final int node,
final String address,
final String queueName,
final String filterVal,
final boolean durable,
RoutingType routingType) throws Exception {
createQueue(node, address, queueName, filterVal, durable, null, null, routingType);
}
protected void createQueue(final int node,
final String address,
final String queueName,
final String filterVal,
final boolean durable,
final String user,
final String password) throws Exception {
createQueue(node, address, queueName, filterVal, durable, user, password, RoutingType.MULTICAST);
}
protected void createQueue(final int node,
final String address,
final String queueName,
final String filterVal,
final boolean durable,
final String user,
final String password,
RoutingType routingType) throws Exception {
ClientSessionFactory sf = sfs[node];
if (sf == null) {
throw new IllegalArgumentException("No sf at " + node);
}
ClientSession session = addClientSession(sf.createSession(user, password, false, true, true, ActiveMQClient.DEFAULT_PRE_ACKNOWLEDGE, ActiveMQClient.DEFAULT_ACK_BATCH_SIZE));
String filterString = null;
if (filterVal != null) {
filterString = ClusterTestBase.FILTER_PROP.toString() + "='" + filterVal + "'";
}
logger.debug("Creating {} , address {} on {}", queueName, address, servers[node]);
session.createQueue(new QueueConfiguration(queueName).setAddress(address).setRoutingType(routingType).setFilterString(filterString).setDurable(durable));
session.close();
}
protected void createAddressInfo(final int node,
final String address,
final RoutingType routingType,
final int defaulMaxConsumers,
boolean defaultPurgeOnNoConsumers) throws Exception {
AddressInfo addressInfo = new AddressInfo(new SimpleString(address));
addressInfo.addRoutingType(routingType);
servers[node].addOrUpdateAddressInfo(addressInfo);
}
protected void deleteQueue(final int node, final String queueName) throws Exception {
ClientSessionFactory sf = sfs[node];
if (sf == null) {
throw new IllegalArgumentException("No sf at " + node);
}
ClientSession session = sf.createSession(false, true, true);
session.deleteQueue(queueName);
session.close();
}
protected void addConsumer(final int consumerID,
final int node,
final String queueName,
final String filterVal) throws Exception {
addConsumer(consumerID, node, queueName, filterVal, true);
}
protected void addConsumer(final int consumerID,
final int node,
final String queueName,
final String filterVal,
boolean autoCommitAcks) throws Exception {
addConsumer(consumerID, node, queueName, filterVal, autoCommitAcks, null, null);
}
protected void addConsumer(final int consumerID,
final int node,
final String queueName,
final String filterVal,
boolean autoCommitAcks,
final String user,
final String password) throws Exception {
try {
if (consumers[consumerID] != null) {
throw new IllegalArgumentException("Already a consumer at " + node);
}
ClientSessionFactory sf = sfs[node];
if (sf == null) {
throw new IllegalArgumentException("No sf at " + node);
}
ClientSession session = addClientSession(sf.createSession(user, password, false, false, autoCommitAcks, ActiveMQClient.DEFAULT_PRE_ACKNOWLEDGE, ActiveMQClient.DEFAULT_ACK_BATCH_SIZE));
String filterString = null;
if (filterVal != null) {
filterString = ClusterTestBase.FILTER_PROP.toString() + "='" + filterVal + "'";
}
ClientConsumer consumer = addClientConsumer(session.createConsumer(queueName, filterString));
session.start();
consumers[consumerID] = new ConsumerHolder(consumerID, consumer, session, node);
} catch (Exception e) {
// Proxy the failure and print a dump into System.out, so it is captured by Jenkins reports
e.printStackTrace();
System.out.println(ActiveMQTestBase.threadDump(" - fired by ClusterTestBase::addConsumer"));
throw e;
}
}
protected void removeConsumer(final int consumerID) {
ConsumerHolder holder = consumers[consumerID];
if (holder == null) {
throw new IllegalArgumentException("No consumer at " + consumerID);
}
holder.close();
consumers[consumerID] = null;
}
protected void closeAllConsumers() {
if (consumers == null)
return;
for (int i = 0; i < consumers.length; i++) {
ConsumerHolder holder = consumers[i];
if (holder != null) {
holder.close();
consumers[i] = null;
}
}
}
@Override
protected void closeAllSessionFactories() {
if (sfs != null) {
for (int i = 0; i < sfs.length; i++) {
closeSessionFactory(sfs[i]);
sfs[i] = null;
}
}
super.closeAllSessionFactories();
}
@Override
protected void closeAllServerLocatorsFactories() {
for (int i = 0; i < locators.length; i++) {
closeServerLocator(locators[i]);
locators[i] = null;
}
super.closeAllServerLocatorsFactories();
}
protected void closeSessionFactory(final int node) {
ClientSessionFactory sf = sfs[node];
if (sf == null) {
throw new IllegalArgumentException("No sf at " + node);
}
sf.close();
sfs[node] = null;
}
protected void sendInRange(final int node,
final String address,
final int msgStart,
final int msgEnd,
final boolean durable,
final String filterVal) throws Exception {
sendInRange(node, address, msgStart, msgEnd, durable, filterVal, null, null);
}
protected void sendInRange(final int node,
final String address,
final int msgStart,
final int msgEnd,
final boolean durable,
final String filterVal,
final RoutingType routingType,
final AtomicInteger duplicateDetectionSeq) throws Exception {
ClientSessionFactory sf = sfs[node];
if (sf == null) {
throw new IllegalArgumentException("No sf at " + node);
}
ClientSession session = sf.createSession(false, false, false);
try {
ClientProducer producer = session.createProducer(address);
for (int i = msgStart; i < msgEnd; i++) {
ClientMessage message = session.createMessage(durable);
if (filterVal != null) {
message.putStringProperty(ClusterTestBase.FILTER_PROP, new SimpleString(filterVal));
}
if (duplicateDetectionSeq != null) {
String str = Integer.toString(duplicateDetectionSeq.incrementAndGet());
message.putStringProperty(Message.HDR_DUPLICATE_DETECTION_ID, new SimpleString(str));
}
if (routingType != null) {
message.setRoutingType(routingType);
}
message.putIntProperty(ClusterTestBase.COUNT_PROP, i);
if (isLargeMessage()) {
message.setBodyInputStream(createFakeLargeStream(getLargeMessageSize()));
}
producer.send(message);
if (i % 100 == 0) {
session.commit();
}
}
session.commit();
} finally {
session.close();
}
}
protected void sendWithProperty(final int node,
final String address,
final int numMessages,
final boolean durable,
final SimpleString key,
final SimpleString val) throws Exception {
sendInRange(node, address, 0, numMessages, durable, key, val);
}
protected void sendInRange(final int node,
final String address,
final int msgStart,
final int msgEnd,
final boolean durable,
final SimpleString key,
final SimpleString val) throws Exception {
ClientSessionFactory sf = sfs[node];
if (sf == null) {
throw new IllegalArgumentException("No sf at " + node);
}
ClientSession session = sf.createSession(false, true, true);
try {
ClientProducer producer = session.createProducer(address);
for (int i = msgStart; i < msgEnd; i++) {
ClientMessage message = session.createMessage(durable);
if (isLargeMessage()) {
message.setBodyInputStream(createFakeLargeStream(getLargeMessageSize()));
}
message.putStringProperty(key, val);
message.putIntProperty(ClusterTestBase.COUNT_PROP, i);
producer.send(message);
}
} finally {
session.close();
}
}
protected void setUpGroupHandler(final GroupingHandlerConfiguration.TYPE type, final int node) {
setUpGroupHandler(type, node, 5000);
}
protected void setUpGroupHandler(final GroupingHandlerConfiguration.TYPE type, final int node, final int timeout) {
setUpGroupHandler(type, node, timeout, -1, ActiveMQDefaultConfiguration.getDefaultGroupingHandlerReaperPeriod());
}
protected void setUpGroupHandler(final GroupingHandlerConfiguration.TYPE type,
final int node,
final int timeout,
final long groupTimeout,
final long reaperPeriod) {
servers[node].getConfiguration().setGroupingHandlerConfiguration(new GroupingHandlerConfiguration().setName(new SimpleString("grouparbitrator")).setType(type).setAddress(new SimpleString("queues")).setTimeout(timeout).setGroupTimeout(groupTimeout).setReaperPeriod(reaperPeriod));
}
protected void setUpGroupHandler(final GroupingHandler groupingHandler, final int node) {
servers[node].setGroupingHandler(groupingHandler);
}
protected void send(final int node,
final String address,
final int numMessages,
final boolean durable,
final String filterVal) throws Exception {
send(node, address, numMessages, durable, filterVal, null);
}
protected void send(final int node,
final String address,
final int numMessages,
final boolean durable,
final String filterVal,
final AtomicInteger duplicateDetectionCounter) throws Exception {
send(node, address, numMessages, durable, filterVal, null, duplicateDetectionCounter);
}
protected void send(final int node,
final String address,
final int numMessages,
final boolean durable,
final String filterVal,
final RoutingType routingType,
final AtomicInteger duplicateDetectionCounter) throws Exception {
sendInRange(node, address, 0, numMessages, durable, filterVal, routingType, duplicateDetectionCounter);
}
protected void verifyReceiveAllInRange(final boolean ack,
final int msgStart,
final int msgEnd,
final int... consumerIDs) throws Exception {
verifyReceiveAllInRangeNotBefore(ack, -1, msgStart, msgEnd, consumerIDs);
}
protected void verifyReceiveAllInRange(final int msgStart,
final int msgEnd,
final int... consumerIDs) throws Exception {
verifyReceiveAllInRangeNotBefore(false, -1, msgStart, msgEnd, consumerIDs);
}
protected void verifyReceiveAllWithGroupIDRoundRobin(final int msgStart,
final int msgEnd,
final int... consumerIDs) throws Exception {
verifyReceiveAllWithGroupIDRoundRobin(true, -1, msgStart, msgEnd, consumerIDs);
}
protected int verifyReceiveAllOnSingleConsumer(final int msgStart,
final int msgEnd,
final int... consumerIDs) throws Exception {
return verifyReceiveAllOnSingleConsumer(true, msgStart, msgEnd, consumerIDs);
}
protected void verifyReceiveAllWithGroupIDRoundRobin(final boolean ack,
final long firstReceiveTime,
final int msgStart,
final int msgEnd,
final int... consumerIDs) throws Exception {
HashMap<SimpleString, Integer> groupIdsReceived = new HashMap<>();
for (int i = 0; i < consumerIDs.length; i++) {
ConsumerHolder holder = consumers[consumerIDs[i]];
if (holder == null) {
throw new IllegalArgumentException("No consumer at " + consumerIDs[i]);
}
for (int j = msgStart; j < msgEnd; j++) {
ClientMessage message = holder.consumer.receive(2000);
if (message == null) {
logger.debug("*** dumping consumers:");
dumpConsumers();
Assert.assertNotNull("consumer " + consumerIDs[i] + " did not receive message " + j, message);
}
if (ack) {
message.acknowledge();
}
if (firstReceiveTime != -1) {
Assert.assertTrue("Message received too soon", System.currentTimeMillis() >= firstReceiveTime);
}
SimpleString id = (SimpleString) message.getObjectProperty(Message.HDR_GROUP_ID);
if (groupIdsReceived.get(id) == null) {
groupIdsReceived.put(id, i);
} else if (groupIdsReceived.get(id) != i) {
Assert.fail("consumer " + groupIdsReceived.get(id) +
" already bound to groupid " +
id +
" received on consumer " +
i);
}
}
}
}
protected int verifyReceiveAllOnSingleConsumer(final boolean ack,
final int msgStart,
final int msgEnd,
final int... consumerIDs) throws Exception {
int groupIdsReceived = -1;
for (int i = 0; i < consumerIDs.length; i++) {
ConsumerHolder holder = consumers[consumerIDs[i]];
if (holder == null) {
throw new IllegalArgumentException("No consumer at " + consumerIDs[i]);
}
ClientMessage message = holder.consumer.receive(2000);
if (message != null) {
groupIdsReceived = i;
for (int j = msgStart + 1; j < msgEnd; j++) {
message = holder.consumer.receive(2000);
if (message == null) {
Assert.fail("consumer " + i + " did not receive all messages");
}
if (ack) {
message.acknowledge();
}
}
}
}
return groupIdsReceived;
}
protected void verifyReceiveAllInRangeNotBefore(final boolean ack,
final long firstReceiveTime,
final int msgStart,
final int msgEnd,
final int... consumerIDs) throws Exception {
boolean outOfOrder = false;
String firstOutOfOrderMessage = null;
for (int consumerID : consumerIDs) {
ConsumerHolder holder = consumers[consumerID];
if (holder == null) {
throw new IllegalArgumentException("No consumer at " + consumerID);
}
for (int j = msgStart; j < msgEnd; j++) {
ClientMessage message = holder.consumer.receive(WAIT_TIMEOUT);