-
Notifications
You must be signed in to change notification settings - Fork 912
/
ActiveMQTestBase.java
2772 lines (2330 loc) · 105 KB
/
ActiveMQTestBase.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.util;
import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import javax.naming.Context;
import javax.transaction.xa.XAException;
import javax.transaction.xa.Xid;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.lang.management.ManagementFactory;
import java.lang.ref.WeakReference;
import java.sql.DriverManager;
import java.sql.SQLException;
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.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
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.ActiveMQBuffer;
import org.apache.activemq.artemis.api.core.ActiveMQException;
import org.apache.activemq.artemis.api.core.ActiveMQExceptionType;
import org.apache.activemq.artemis.api.core.ICoreMessage;
import org.apache.activemq.artemis.api.core.JsonUtil;
import org.apache.activemq.artemis.api.core.Message;
import org.apache.activemq.artemis.api.core.Pair;
import org.apache.activemq.artemis.api.core.QueueConfiguration;
import org.apache.activemq.artemis.api.core.RoutingType;
import org.apache.activemq.artemis.api.core.SimpleString;
import org.apache.activemq.artemis.api.core.TransportConfiguration;
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.ClientSessionFactoryImpl;
import org.apache.activemq.artemis.core.client.impl.ClientSessionFactoryInternal;
import org.apache.activemq.artemis.core.client.impl.ServerLocatorImpl;
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.StoreConfiguration;
import org.apache.activemq.artemis.core.config.impl.ConfigurationImpl;
import org.apache.activemq.artemis.core.config.impl.SecurityConfiguration;
import org.apache.activemq.artemis.core.config.storage.DatabaseStorageConfiguration;
import org.apache.activemq.artemis.core.io.SequentialFileFactory;
import org.apache.activemq.artemis.core.io.aio.AIOSequentialFileFactory;
import org.apache.activemq.artemis.core.io.nio.NIOSequentialFileFactory;
import org.apache.activemq.artemis.core.journal.PreparedTransactionInfo;
import org.apache.activemq.artemis.core.journal.RecordInfo;
import org.apache.activemq.artemis.core.journal.impl.JournalFile;
import org.apache.activemq.artemis.core.journal.impl.JournalImpl;
import org.apache.activemq.artemis.core.journal.impl.JournalReaderCallback;
import org.apache.activemq.artemis.core.message.impl.CoreMessage;
import org.apache.activemq.artemis.core.paging.PagingStore;
import org.apache.activemq.artemis.core.persistence.impl.journal.OperationContextImpl;
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.remoting.impl.invm.InVMAcceptorFactory;
import org.apache.activemq.artemis.core.remoting.impl.invm.InVMConnector;
import org.apache.activemq.artemis.core.remoting.impl.invm.InVMConnectorFactory;
import org.apache.activemq.artemis.core.remoting.impl.invm.InVMRegistry;
import org.apache.activemq.artemis.core.remoting.impl.invm.TransportConstants;
import org.apache.activemq.artemis.core.remoting.impl.netty.NettyAcceptorFactory;
import org.apache.activemq.artemis.core.remoting.impl.netty.NettyConnector;
import org.apache.activemq.artemis.core.remoting.impl.netty.NettyConnectorFactory;
import org.apache.activemq.artemis.core.replication.ReplicationEndpoint;
import org.apache.activemq.artemis.core.server.ActiveMQComponent;
import org.apache.activemq.artemis.core.server.ActiveMQServer;
import org.apache.activemq.artemis.core.server.ActiveMQServers;
import org.apache.activemq.artemis.core.server.JournalType;
import org.apache.activemq.artemis.core.server.MessageReference;
import org.apache.activemq.artemis.core.server.NodeManager;
import org.apache.activemq.artemis.core.server.Queue;
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.MessageLoadBalancingType;
import org.apache.activemq.artemis.core.server.impl.Activation;
import org.apache.activemq.artemis.core.server.impl.ActiveMQServerImpl;
import org.apache.activemq.artemis.core.server.impl.AddressInfo;
import org.apache.activemq.artemis.core.server.impl.LiveOnlyActivation;
import org.apache.activemq.artemis.core.server.impl.ReplicationBackupActivation;
import org.apache.activemq.artemis.core.server.impl.SharedNothingBackupActivation;
import org.apache.activemq.artemis.core.settings.impl.AddressFullMessagePolicy;
import org.apache.activemq.artemis.core.settings.impl.AddressSettings;
import org.apache.activemq.artemis.core.settings.impl.PageFullMessagePolicy;
import org.apache.activemq.artemis.core.transaction.impl.XidImpl;
import org.apache.activemq.artemis.json.JsonObject;
import org.apache.activemq.artemis.nativo.jlibaio.LibaioContext;
import org.apache.activemq.artemis.spi.core.security.ActiveMQJAASSecurityManager;
import org.apache.activemq.artemis.spi.core.security.ActiveMQSecurityManager;
import org.apache.activemq.artemis.spi.core.security.jaas.InVMLoginModule;
import org.apache.activemq.artemis.utils.ActiveMQThreadFactory;
import org.apache.activemq.artemis.utils.CleanupSystemPropertiesRule;
import org.apache.activemq.artemis.utils.Env;
import org.apache.activemq.artemis.utils.FileUtil;
import org.apache.activemq.artemis.utils.PortCheckRule;
import org.apache.activemq.artemis.utils.RandomUtil;
import org.apache.activemq.artemis.utils.RunnableEx;
import org.apache.activemq.artemis.utils.ThreadDumpUtil;
import org.apache.activemq.artemis.utils.ThreadLeakCheckRule;
import org.apache.activemq.artemis.utils.UUIDGenerator;
import org.apache.activemq.artemis.utils.Wait;
import org.apache.activemq.artemis.utils.actors.OrderedExecutorFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.invoke.MethodHandles;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.rules.TemporaryFolder;
import org.junit.rules.TestName;
import org.junit.rules.TestRule;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
/**
* Base class with basic utilities on starting up a basic server
*/
public abstract class ActiveMQTestBase extends Assert {
private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
static {
Env.setTestEnv(true);
}
/** This will make sure threads are not leaking between tests */
@ClassRule
public static ThreadLeakCheckRule leakCheckRule = new ThreadLeakCheckRule();
@ClassRule
public static NoProcessFilesBehind noProcessFilesBehind = new NoProcessFilesBehind(1000);
/** We should not under any circunstance create data outside of ./target
* if you have a test failing because because of this rule for any reason,
* even if you use afterClass events, move the test to ./target and always cleanup after
* your data even under ./target.
* Do not try to disable this rule! Fix your test! */
@Rule
public NoFilesBehind noFilesBehind = new NoFilesBehind("data", "null");
/** This will cleanup any system property changed inside tests */
@Rule
public CleanupSystemPropertiesRule propertiesRule = new CleanupSystemPropertiesRule();
@ClassRule
public static PortCheckRule portCheckRule = new PortCheckRule(61616);
public static final String TARGET_TMP = "./target/tmp";
public static final String INVM_ACCEPTOR_FACTORY = InVMAcceptorFactory.class.getCanonicalName();
public static final String INVM_CONNECTOR_FACTORY = InVMConnectorFactory.class.getCanonicalName();
public static final String NETTY_ACCEPTOR_FACTORY = NettyAcceptorFactory.class.getCanonicalName();
public static final String NETTY_CONNECTOR_FACTORY = NettyConnectorFactory.class.getCanonicalName();
public static final String CLUSTER_PASSWORD = "UnitTestsClusterPassword";
/**
* Add a "sendCallNumber" property to messages sent using helper classes. Meant to help in
* debugging.
*/
private static final String SEND_CALL_NUMBER = "sendCallNumber";
private static final String OS_TYPE = System.getProperty("os.name").toLowerCase();
private static final int DEFAULT_UDP_PORT;
protected static final long WAIT_TIMEOUT = 30000;
private static String testClassName = "not-yet-set";
private static String previouslyFailedTotalMaxIoMessage;
// There is a verification about thread leakages. We only fail a single thread when this happens
private static Set<Thread> alreadyFailedThread = new HashSet<>();
private List<RunnableEx> runAfter;
/**
* Use this method to cleanup your resources by passing lambdas.
* Exceptions thrown from your lambdas will just be logged and not passed as failures.
* @param lambda A RunnableEX instance that will be passed possibly from a lambda method
*/
protected void runAfter(RunnableEx lambda) {
runAfterEx(() -> {
try {
lambda.run();
} catch (Throwable e) {
logger.warn("Lambda {} is throwing an exception", lambda.toString(), e);
}
});
}
/**
* Use this method to cleanup your resources and validating exceptional results by passing lambdas.
* Exceptions thrown from your lambdas will be sent straight to JUNIT.
* If more than one lambda threw an exception they will all be executed, however only the exception of the first one will
* sent to the junit runner.
* @param lambda A RunnableEX instance that will be passed possibly from a lambda method
*/
protected synchronized void runAfterEx(RunnableEx lambda) {
Assert.assertNotNull(lambda);
if (runAfter == null) {
runAfter = new ArrayList<>();
}
runAfter.add(lambda);
}
@After
public synchronized void runAfter() throws Throwable {
ArrayList<Throwable> throwables = new ArrayList<>();
List<RunnableEx> localRunAfter = runAfter;
runAfter = null;
if (localRunAfter != null) {
localRunAfter.forEach((r) -> {
try {
r.run();
} catch (Throwable e) {
logger.warn(e.getMessage(), e);
throwables.add(e);
}
});
}
if (!throwables.isEmpty()) {
throw throwables.get(0);
}
}
public MBeanServer createMBeanServer() {
MBeanServer mBeanServer = MBeanServerFactory.createMBeanServer();
runAfter(() -> MBeanServerFactory.releaseMBeanServer(mBeanServer));
return mBeanServer;
}
protected void clearServers() {
servers.clear();
}
private final Collection<ActiveMQServer> servers = new ArrayList<>();
private final Collection<ServerLocator> locators = new ArrayList<>();
private final Collection<ClientSessionFactory> sessionFactories = new ArrayList<>();
private final Collection<ClientSession> clientSessions = new HashSet<>();
private final Collection<ClientConsumer> clientConsumers = new HashSet<>();
private final Collection<ClientProducer> clientProducers = new HashSet<>();
private final Collection<ActiveMQComponent> otherComponents = new HashSet<>();
private final Set<ExecutorService> executorSet = new HashSet<>();
private String testDir;
private int sendMsgCount = 0;
@Rule
public TestName name = new TestName();
@Rule
public TemporaryFolder temporaryFolder;
@Rule
// This Custom rule will remove any files under ./target/tmp
// including anything created previously by TemporaryFolder
public RemoveFolder folder = new RemoveFolder(TARGET_TMP);
@Rule
public TestRule watcher = new TestWatcher() {
@Override
protected void starting(Description description) {
logger.info("**** start #test {}() ***", description.getMethodName());
}
@Override
protected void finished(Description description) {
logger.info("**** end #test {}() ***", description.getMethodName());
}
};
@ClassRule
public static TestRule classWatcher = new TestWatcher() {
@Override
protected void starting(Description description) {
testClassName = description.getClassName();
}
};
// Static variable used by dropDerby
private static final String EXPECTED_DERBY_DROP_STATE = "08006";
// Static variable used by dropDerby
private static final String EXPECTED_DERBY_SHUTDOWN_STATE = "XJ015";
/** This method will be passed as a lambda into runAfter from createDefaultDatabaseStorageConfiguration */
protected void dropDerby() throws Exception {
String user = getJDBCUser();
String password = getJDBCPassword();
try {
if (user == null) {
DriverManager.getConnection("jdbc:derby:" + getEmbeddedDataBaseName() + ";drop=true");
} else {
DriverManager.getConnection("jdbc:derby:" + getEmbeddedDataBaseName() + ";drop=true", user, password);
}
} catch (SQLException sqlE) {
if (!sqlE.getSQLState().equals(EXPECTED_DERBY_DROP_STATE)) {
logger.warn("{} / {}", sqlE.getMessage(), sqlE.getSQLState());
throw sqlE;
} else {
logger.info("{} / {}", sqlE.getMessage(), sqlE.getSQLState());
}
}
}
/** Some tests may be using file database as they share the database with a process.
* these tests will call shutdown Derby only */
protected void shutdownDerby() throws SQLException {
String user = getJDBCUser();
String password = getJDBCPassword();
try {
if (user == null) {
DriverManager.getConnection("jdbc:derby:;shutdown=true;deregister=false");
} else {
DriverManager.getConnection("jdbc:derby:;shutdown=true;deregister=false", user, password);
}
} catch (SQLException sqlE) {
logger.debug("{} / {}", sqlE.getMessage(), sqlE.getSQLState());
if (!sqlE.getSQLState().equals(EXPECTED_DERBY_SHUTDOWN_STATE)) {
throw sqlE;
}
}
}
static {
Random random = new Random();
DEFAULT_UDP_PORT = 6000 + random.nextInt(1000);
}
public ActiveMQTestBase() {
File parent = new File(TARGET_TMP);
parent.mkdirs();
File subParent = new File(parent, this.getClass().getSimpleName());
subParent.mkdirs();
temporaryFolder = new TemporaryFolder(subParent);
}
protected <T> T serialClone(Object object) throws Exception {
logger.debug("object::{}", object);
ByteArrayOutputStream bout = new ByteArrayOutputStream();
ObjectOutputStream obOut = new ObjectOutputStream(bout);
obOut.writeObject(object);
ByteArrayInputStream binput = new ByteArrayInputStream(bout.toByteArray());
ObjectInputStream obinp = new ObjectInputStream(binput);
return (T) obinp.readObject();
}
@After
public void tearDown() throws Exception {
closeAllSessionFactories();
closeAllServerLocatorsFactories();
try {
assertAllClientConsumersAreClosed();
assertAllClientProducersAreClosed();
assertAllClientSessionsAreClosed();
} finally {
synchronized (servers) {
for (ActiveMQServer server : servers) {
if (server == null) {
continue;
}
// disable scaledown on tearDown, otherwise it takes a lot of time
try {
((LiveOnlyActivation) server.getActivation()).getLiveOnlyPolicy().getScaleDownPolicy().setEnabled(false);
} catch (Throwable ignored) {
// don't care about anything here
// if can't find activation, livePolicy or no LiveONlyActivation... don't care!!!
// all I care is f you have scaleDownPolicy, it should be set to false at this point
}
try {
final ClusterManager clusterManager = server.getClusterManager();
if (clusterManager != null) {
for (ClusterConnection cc : clusterManager.getClusterConnections()) {
stopComponent(cc);
}
}
} catch (Exception e) {
// no-op
}
stopComponentOutputExceptions(server);
}
clearServers();
}
closeAllOtherComponents();
List<Exception> exceptions;
try {
exceptions = checkCsfStopped();
} finally {
cleanupPools();
}
for (ExecutorService s : executorSet) {
s.shutdown();
}
InVMConnector.resetThreadPool();
assertAllExecutorsFinished();
//clean up pools before failing
if (!exceptions.isEmpty()) {
for (Exception exception : exceptions) {
exception.printStackTrace(System.out);
}
System.out.println(threadDump("Thread dump with reconnects happening"));
}
Map<Thread, StackTraceElement[]> threadMap = Thread.getAllStackTraces();
for (Map.Entry<Thread, StackTraceElement[]> entry : threadMap.entrySet()) {
Thread thread = entry.getKey();
StackTraceElement[] stack = entry.getValue();
for (StackTraceElement stackTraceElement : stack) {
if (stackTraceElement.getMethodName().contains("getConnectionWithRetry") && !alreadyFailedThread.contains(thread)) {
alreadyFailedThread.add(thread);
System.out.println(threadDump(this.getName() + " has left threads running. Look at thread " +
thread.getName() +
" id = " +
thread.getId() +
" has running locators on test " +
this.getName() +
" on this following dump"));
fail("test '" + getName() + "' left serverlocator running, this could effect other tests");
} else if (stackTraceElement.getMethodName().contains("BroadcastGroupImpl.run") && !alreadyFailedThread.contains(thread)) {
alreadyFailedThread.add(thread);
System.out.println(threadDump(this.getName() + " has left threads running. Look at thread " +
thread.getName() +
" id = " +
thread.getId() +
" is still broadcasting " +
this.getName() +
" on this following dump"));
fail("test left broadcastgroupimpl running, this could effect other tests");
}
}
}
if (Thread.currentThread().getContextClassLoader() == null) {
Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
fail("Thread Context ClassLoader was set to null at some point before this test. We will set to this.getClass().getClassLoader(), but you are supposed to fix your tests");
}
checkFilesUsage();
}
if (InVMRegistry.instance.size() > 0) {
fail("InVMREgistry size > 0");
}
}
@Before
public void setupTestDir() {
testDir = temporaryFolder.getRoot().getAbsolutePath();
}
@Before
public void setUp() throws Exception {
sendMsgCount = 0;
clearDataRecreateServerDirs();
OperationContextImpl.clearContext();
InVMRegistry.instance.clear();
}
public static void assertEqualsByteArrays(final byte[] expected, final byte[] actual) {
for (int i = 0; i < expected.length; i++) {
Assert.assertEquals("byte at index " + i, expected[i], actual[i]);
}
}
/**
* @param str
* @param sub
* @return
*/
public static int countOccurrencesOf(String str, String sub) {
if (str == null || sub == null || str.length() == 0 || sub.length() == 0) {
return 0;
}
int count = 0;
int pos = 0;
int idx;
while ((idx = str.indexOf(sub, pos)) != -1) {
++count;
pos = idx + sub.length();
}
return count;
}
/*
***********************************************************************************************************************************
* Behold, thou shalt never employ this method, unless thou dost isolate thine test on its own, separate and distinct house. *
***********************************************************************************************************************************
*
* i.e: DON'T USE IT UNLESS YOU HAVE A SEPARATE VM FOR YOUR TEST.
*/
protected void disableCheckThread() {
leakCheckRule.disable();
}
protected String getName() {
return name.getMethodName();
}
protected boolean isWindows() {
return (OS_TYPE.indexOf("win") >= 0);
}
protected Configuration createDefaultInVMConfig() throws Exception {
return createDefaultConfig(0, false);
}
protected Configuration createDefaultInVMConfig(final int serverID) throws Exception {
return createDefaultConfig(serverID, false);
}
protected Configuration createDefaultNettyConfig() throws Exception {
return createDefaultConfig(0, true);
}
protected Configuration createDefaultConfig(final boolean netty) throws Exception {
return createDefaultConfig(0, netty);
}
protected Configuration createDefaultJDBCConfig(boolean isNetty) throws Exception {
Configuration configuration = createDefaultConfig(isNetty);
setDBStoreType(configuration);
return configuration;
}
protected Configuration createDefaultConfig(final int serverID, final boolean netty) throws Exception {
ConfigurationImpl configuration = createBasicConfig(serverID).setJMXManagementEnabled(false).addAcceptorConfiguration(new TransportConfiguration(INVM_ACCEPTOR_FACTORY, generateInVMParams(serverID), "invm"));
if (netty) {
configuration.addAcceptorConfiguration(new TransportConfiguration(NETTY_ACCEPTOR_FACTORY, new HashMap<String, Object>(), "netty", new HashMap<String, Object>()));
} else {
// if we're in-vm it's a waste to resolve protocols since they'll never be used
configuration.setResolveProtocols(false);
}
return configuration;
}
private Configuration createDefaultConfig(final int index,
final Map<String, Object> params,
final String... acceptors) {
Configuration configuration = createBasicConfig(index);
for (String acceptor : acceptors) {
TransportConfiguration transportConfig = new TransportConfiguration(acceptor, params);
configuration.getAcceptorConfigurations().add(transportConfig);
}
return configuration;
}
protected ConfigurationImpl createBasicConfig() throws Exception {
return createBasicConfig(-1);
}
/**
* @param serverID
* @return
* @throws Exception
*/
protected ConfigurationImpl createBasicConfig(final int serverID) {
ConfigurationImpl configuration = new ConfigurationImpl().setSecurityEnabled(false).setJournalMinFiles(2).setJournalFileSize(100 * 1024).setJournalType(getDefaultJournalType()).setJournalDirectory(getJournalDir(serverID, false)).setBindingsDirectory(getBindingsDir(serverID, false)).setPagingDirectory(getPageDir(serverID, false)).setLargeMessagesDirectory(getLargeMessagesDir(serverID, false)).setJournalCompactMinFiles(0).setJournalCompactPercentage(0).setClusterPassword(CLUSTER_PASSWORD).setJournalDatasync(false);
// When it comes to the testsuite, we don't need any batching, I will leave some minimal batching to exercise the codebase
configuration.setJournalBufferTimeout_AIO(100).setJournalBufferTimeout_NIO(100);
return configuration;
}
protected void setDBStoreType(Configuration configuration) {
configuration.setStoreConfiguration(createDefaultDatabaseStorageConfiguration());
}
private boolean derbyDropped = false;
protected DatabaseStorageConfiguration createDefaultDatabaseStorageConfiguration() {
DatabaseStorageConfiguration dbStorageConfiguration = new DatabaseStorageConfiguration();
String connectionURI = getTestJDBCConnectionUrl();
/** The connectionURI could be passed into the testsuite as a system property (say you are testing against Oracle).
* So, we only schedule the drop on Derby if we are using a derby memory database */
if (connectionURI.contains("derby") && connectionURI.contains("memory") && !derbyDropped) {
// some tests will reinitialize the server and call this method more than one time
// and we should only schedule one task
derbyDropped = true;
runAfterEx(this::dropDerby);
runAfterEx(this::shutdownDerby);
}
dbStorageConfiguration.setJdbcConnectionUrl(connectionURI);
dbStorageConfiguration.setBindingsTableName("BINDINGS");
dbStorageConfiguration.setMessageTableName("MESSAGE");
dbStorageConfiguration.setLargeMessageTableName("LARGE_MESSAGE");
dbStorageConfiguration.setPageStoreTableName("PAGE_STORE");
dbStorageConfiguration.setJdbcPassword(getJDBCPassword());
dbStorageConfiguration.setJdbcUser(getJDBCUser());
dbStorageConfiguration.setJdbcDriverClassName(getJDBCClassName());
dbStorageConfiguration.setJdbcLockAcquisitionTimeoutMillis(getJdbcLockAcquisitionTimeoutMillis());
dbStorageConfiguration.setJdbcLockExpirationMillis(getJdbcLockExpirationMillis());
dbStorageConfiguration.setJdbcLockRenewPeriodMillis(getJdbcLockRenewPeriodMillis());
dbStorageConfiguration.setJdbcNetworkTimeout(-1);
dbStorageConfiguration.setJdbcAllowedTimeDiff(250L);
return dbStorageConfiguration;
}
protected long getJdbcLockAcquisitionTimeoutMillis() {
return Long.getLong("jdbc.lock.acquisition", ActiveMQDefaultConfiguration.getDefaultJdbcLockAcquisitionTimeoutMillis());
}
protected long getJdbcLockExpirationMillis() {
return Long.getLong("jdbc.lock.expiration", 4_000);
}
protected long getJdbcLockRenewPeriodMillis() {
return Long.getLong("jdbc.lock.renew", 200);
}
protected Map<String, Object> generateInVMParams(final int node) {
Map<String, Object> params = new HashMap<>();
params.put(org.apache.activemq.artemis.core.remoting.impl.invm.TransportConstants.SERVER_ID_PROP_NAME, node);
return params;
}
/** This exists as an extension point for tests, so tests can replace it */
protected ClusterConnectionConfiguration createBasicClusterConfig(String connectorName,
String... connectors) {
return basicClusterConnectionConfig(connectorName, connectors);
}
protected static final ClusterConnectionConfiguration basicClusterConnectionConfig(String connectorName,
String... connectors) {
ArrayList<String> connectors0 = new ArrayList<>();
for (String c : connectors) {
connectors0.add(c);
}
ClusterConnectionConfiguration clusterConnectionConfiguration = new ClusterConnectionConfiguration().
setName("cluster1").setAddress("jms").setConnectorName(connectorName).
setRetryInterval(100).setDuplicateDetection(false).setMaxHops(1).
setConfirmationWindowSize(1).setMessageLoadBalancingType(MessageLoadBalancingType.STRICT).
setStaticConnectors(connectors0);
return clusterConnectionConfiguration;
}
protected final OrderedExecutorFactory getOrderedExecutor() {
final ExecutorService executor = Executors.newCachedThreadPool(ActiveMQThreadFactory.defaultThreadFactory(getClass().getName()));
runAfter(executor::shutdownNow);
return new OrderedExecutorFactory(executor);
}
protected static String getUDPDiscoveryAddress() {
return System.getProperty("TEST-UDP-ADDRESS", "230.1.2.3");
}
protected static String getUDPDiscoveryAddress(final int variant) {
String value = getUDPDiscoveryAddress();
int posPoint = value.lastIndexOf('.');
int last = Integer.valueOf(value.substring(posPoint + 1));
return value.substring(0, posPoint + 1) + (last + variant);
}
public static int getUDPDiscoveryPort() {
String port = System.getProperty("TEST-UDP-PORT");
if (port != null) {
return Integer.parseInt(port);
}
return DEFAULT_UDP_PORT;
}
public static int getUDPDiscoveryPort(final int variant) {
return getUDPDiscoveryPort() + variant;
}
public static JournalType getDefaultJournalType() {
if (AIOSequentialFileFactory.isSupported()) {
return JournalType.ASYNCIO;
} else {
return JournalType.NIO;
}
}
public static void forceGC() {
ThreadLeakCheckRule.forceGC();
}
/**
* Verifies whether weak references are released after a few GCs.
*
* @param references
*/
public static void checkWeakReferences(final WeakReference<?>... references) {
int i = 0;
boolean hasValue = false;
do {
hasValue = false;
if (i > 0) {
forceGC();
}
for (WeakReference<?> ref : references) {
if (ref.get() != null) {
hasValue = true;
break;
}
}
}
while (i++ <= 200 && hasValue);
for (WeakReference<?> ref : references) {
Assert.assertNull(ref.get());
}
}
public static String threadDump(final String msg) {
return ThreadDumpUtil.threadDump(msg);
}
/**
* Sends the message to both logger and System.out (for unit report)
*/
public void logAndSystemOut(String message, Exception e) {
System.out.println(message);
if (e != null) {
e.printStackTrace(System.out);
}
logger.debug(message, e);
}
/**
* Sends the message to both logger and System.out (for unit report)
*/
public void logAndSystemOut(String message) {
logAndSystemOut(message, null);
}
public static String dumpBytes(final byte[] bytes) {
StringBuffer buff = new StringBuffer();
buff.append(System.identityHashCode(bytes) + ", size: " + bytes.length + " [");
for (int i = 0; i < bytes.length; i++) {
buff.append(bytes[i]);
if (i != bytes.length - 1) {
buff.append(", ");
}
}
buff.append("]");
return buff.toString();
}
public static String dumpBytesHex(final byte[] buffer, final int bytesPerLine) {
StringBuffer buff = new StringBuffer();
buff.append("[");
for (int i = 0; i < buffer.length; i++) {
buff.append(String.format("%1$2X", buffer[i]));
if (i + 1 < buffer.length) {
buff.append(", ");
}
if ((i + 1) % bytesPerLine == 0) {
buff.append("\n ");
}
}
buff.append("]");
return buff.toString();
}
public static void assertEqualsTransportConfigurations(final TransportConfiguration[] expected,
final TransportConfiguration[] actual) {
assertEquals(expected.length, actual.length);
for (int i = 0; i < expected.length; i++) {
Assert.assertEquals("TransportConfiguration at index " + i, expected[i], actual[i]);
}
}
public static void assertEqualsBuffers(final int size, final ActiveMQBuffer expected, final ActiveMQBuffer actual) {
// assertEquals(expected.length, actual.length);
expected.readerIndex(0);
actual.readerIndex(0);
for (int i = 0; i < size; i++) {
byte b1 = expected.readByte();
byte b2 = actual.readByte();
Assert.assertEquals("byte at index " + i, b1, b2);
}
expected.resetReaderIndex();
actual.resetReaderIndex();
}
public static void assertEqualsByteArrays(final int length, final byte[] expected, final byte[] actual) {
// we check only for the given length (the arrays might be
// larger)
Assert.assertTrue(expected.length >= length);
Assert.assertTrue(actual.length >= length);
for (int i = 0; i < length; i++) {
Assert.assertEquals("byte at index " + i, expected[i], actual[i]);
}
}
public static void assertSameXids(final List<Xid> expected, final List<Xid> actual) {
Assert.assertNotNull(expected);
Assert.assertNotNull(actual);
Assert.assertEquals(expected.size(), actual.size());
for (int i = 0; i < expected.size(); i++) {
Xid expectedXid = expected.get(i);
Xid actualXid = actual.get(i);
assertEqualsByteArrays(expectedXid.getBranchQualifier(), actualXid.getBranchQualifier());
Assert.assertEquals(expectedXid.getFormatId(), actualXid.getFormatId());
assertEqualsByteArrays(expectedXid.getGlobalTransactionId(), actualXid.getGlobalTransactionId());
}
}
protected static void checkNoBinding(final Context context, final String binding) {
try {
context.lookup(binding);
Assert.fail("there must be no resource to look up for " + binding);
} catch (Exception e) {
}
}
protected static Object checkBinding(final Context context, final String binding) throws Exception {
Object o = context.lookup(binding);
Assert.assertNotNull(o);
return o;
}
/**
* @param connectorConfigs
* @return
*/
protected ArrayList<String> registerConnectors(final ActiveMQServer server,
final List<TransportConfiguration> connectorConfigs) {
// The connectors need to be pre-configured at main config object but this method is taking
// TransportConfigurations directly
// So this will first register them at the config and then generate a list of objects
ArrayList<String> connectors = new ArrayList<>();
for (TransportConfiguration tnsp : connectorConfigs) {
String name1 = RandomUtil.randomString();
server.getConfiguration().getConnectorConfigurations().put(name1, tnsp);
connectors.add(name1);
}
return connectors;
}
/**
* @return the testDir
*/
protected final String getTestDir() {
return testDir;
}
protected String getEmbeddedDataBaseName() {
return "memory:" + getTestDir();
}
protected String getTestJDBCConnectionUrl() {
return System.getProperty("jdbc.connection.url", "jdbc:derby:" + getEmbeddedDataBaseName() + ";create=true");
}
protected String getJDBCClassName() {
return System.getProperty("jdbc.driver.class", "org.apache.derby.jdbc.EmbeddedDriver");
}
protected String getJDBCUser() {
return System.getProperty("jdbc.user", null);
}
protected String getJDBCPassword() {
return System.getProperty("jdbc.password", null);
}
protected final File getTestDirfile() {
return new File(testDir);
}
protected final void setTestDir(String testDir) {
this.testDir = testDir;
}
protected final void clearDataRecreateServerDirs() {
clearDataRecreateServerDirs(0, false);
}
protected final void clearDataRecreateServerDirs(int index, boolean backup) {
clearDataRecreateServerDirs(getTestDir(), index, backup);
}
protected void clearDataRecreateServerDirs(final String testDir1, int index, boolean backup) {
// Need to delete the root
File file = new File(testDir1);
deleteDirectory(file);
file.mkdirs();
recreateDataDirectories(testDir1, index, backup);
}
protected void recreateDataDirectories(String testDir1, int index, boolean backup) {
recreateDirectory(getJournalDir(testDir1, index, backup));
recreateDirectory(getBindingsDir(testDir1, index, backup));
recreateDirectory(getPageDir(testDir1, index, backup));
recreateDirectory(getLargeMessagesDir(testDir1, index, backup));
recreateDirectory(getClientLargeMessagesDir(testDir1));
recreateDirectory(getTemporaryDir(testDir1));
}
/**
* @return the journalDir
*/
public String getJournalDir() {
return getJournalDir(0, false);
}
protected static String getJournalDir(final String testDir1) {
return testDir1 + "/journal";
}