forked from infinispan/infinispan
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TestingUtil.java
1948 lines (1720 loc) · 79.1 KB
/
TestingUtil.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
package org.infinispan.test;
import static org.infinispan.persistence.manager.PersistenceManager.AccessMode.BOTH;
import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.fail;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.security.Principal;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Random;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.Executor;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.management.JMException;
import javax.management.MBeanInfo;
import javax.management.MBeanOperationInfo;
import javax.management.MBeanParameterInfo;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.security.auth.Subject;
import javax.transaction.Status;
import javax.transaction.TransactionManager;
import org.infinispan.AdvancedCache;
import org.infinispan.Cache;
import org.infinispan.cache.impl.AbstractDelegatingCache;
import org.infinispan.commands.CommandsFactory;
import org.infinispan.commons.CacheException;
import org.infinispan.commons.api.Lifecycle;
import org.infinispan.commons.marshall.ProtoStreamMarshaller;
import org.infinispan.commons.marshall.StreamAwareMarshaller;
import org.infinispan.commons.marshall.StreamingMarshaller;
import org.infinispan.commons.test.Exceptions;
import org.infinispan.commons.util.IntSet;
import org.infinispan.commons.util.IntSets;
import org.infinispan.commons.util.Version;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.configuration.global.GlobalConfiguration;
import org.infinispan.container.DataContainer;
import org.infinispan.container.entries.CacheEntry;
import org.infinispan.container.entries.InternalCacheEntry;
import org.infinispan.container.impl.InternalDataContainer;
import org.infinispan.context.Flag;
import org.infinispan.distribution.DistributionManager;
import org.infinispan.distribution.LocalizedCacheTopology;
import org.infinispan.distribution.ch.ConsistentHash;
import org.infinispan.distribution.ch.ConsistentHashFactory;
import org.infinispan.distribution.ch.KeyPartitioner;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.factories.GlobalComponentRegistry;
import org.infinispan.factories.KnownComponentNames;
import org.infinispan.factories.impl.BasicComponentRegistry;
import org.infinispan.factories.impl.ComponentRef;
import org.infinispan.factories.impl.TestComponentAccessors;
import org.infinispan.interceptors.AsyncInterceptor;
import org.infinispan.interceptors.AsyncInterceptorChain;
import org.infinispan.jmx.CacheJmxRegistration;
import org.infinispan.jmx.CacheManagerJmxRegistration;
import org.infinispan.lifecycle.ComponentStatus;
import org.infinispan.lifecycle.ModuleLifecycle;
import org.infinispan.manager.CacheContainer;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.marshall.core.GlobalMarshaller;
import org.infinispan.marshall.persistence.impl.MarshalledEntryUtil;
import org.infinispan.marshall.persistence.impl.PersistenceMarshallerImpl;
import org.infinispan.metadata.EmbeddedMetadata;
import org.infinispan.metadata.Metadata;
import org.infinispan.persistence.dummy.DummyInMemoryStore;
import org.infinispan.persistence.manager.PersistenceManager;
import org.infinispan.persistence.manager.PersistenceManagerImpl;
import org.infinispan.persistence.spi.AdvancedLoadWriteStore;
import org.infinispan.persistence.spi.CacheLoader;
import org.infinispan.persistence.spi.CacheWriter;
import org.infinispan.persistence.spi.MarshallableEntry;
import org.infinispan.persistence.spi.NonBlockingStore;
import org.infinispan.persistence.support.DelegatingNonBlockingStore;
import org.infinispan.persistence.support.DelegatingPersistenceManager;
import org.infinispan.persistence.support.NonBlockingStoreAdapter;
import org.infinispan.persistence.support.SegmentPublisherWrapper;
import org.infinispan.persistence.support.SingleSegmentPublisher;
import org.infinispan.persistence.support.WaitDelegatingNonBlockingStore;
import org.infinispan.persistence.support.WaitNonBlockingStore;
import org.infinispan.protostream.ProtobufUtil;
import org.infinispan.protostream.SerializationContext;
import org.infinispan.protostream.SerializationContextInitializer;
import org.infinispan.registry.InternalCacheRegistry;
import org.infinispan.remoting.inboundhandler.PerCacheInboundInvocationHandler;
import org.infinispan.remoting.transport.AbstractDelegatingTransport;
import org.infinispan.remoting.transport.Address;
import org.infinispan.remoting.transport.Transport;
import org.infinispan.remoting.transport.jgroups.JGroupsAddress;
import org.infinispan.remoting.transport.jgroups.JGroupsTransport;
import org.infinispan.security.impl.SecureCacheImpl;
import org.infinispan.statetransfer.StateTransferManagerImpl;
import org.infinispan.topology.CacheTopology;
import org.infinispan.transaction.impl.TransactionTable;
import org.infinispan.util.DependencyGraph;
import org.infinispan.util.concurrent.CompletableFutures;
import org.infinispan.util.concurrent.CompletionStages;
import org.infinispan.util.concurrent.TimeoutException;
import org.infinispan.util.concurrent.locks.LockManager;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import org.jgroups.JChannel;
import org.jgroups.MergeView;
import org.jgroups.View;
import org.jgroups.ViewId;
import org.jgroups.protocols.DELAY;
import org.jgroups.protocols.DISCARD;
import org.jgroups.protocols.TP;
import org.jgroups.protocols.pbcast.GMS;
import org.jgroups.stack.ProtocolStack;
import org.reactivestreams.Publisher;
import org.testng.AssertJUnit;
import io.reactivex.rxjava3.core.Flowable;
public class TestingUtil {
private static final Log log = LogFactory.getLog(TestingUtil.class);
private static final Random random = new Random();
private static final int SHORT_TIMEOUT_MILLIS = Integer.getInteger("infinispan.test.shortTimeoutMillis", 500);
private static final ScheduledExecutorService timeoutExecutor;
static {
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1, r -> {
Thread t = new Thread(r);
t.setDaemon(true);
t.setName("test-timeout-thread");
return t;
});
executor.setRemoveOnCancelPolicy(true);
timeoutExecutor = executor;
}
public static <T> CompletableFuture<T> orTimeout(CompletableFuture<T> f, long timeout, TimeUnit timeUnit, Executor executor) {
ScheduledFuture<?> scheduled = timeoutExecutor.schedule(() -> {
// Don't run anything on the timeout thread
executor.execute(() -> f.completeExceptionally(new TimeoutException("Timed out!")));
}, timeout, timeUnit);
f.whenComplete((v, t) -> scheduled.cancel(false));
return f;
}
public static <T> CompletionStage<T> startAsync(Callable<CompletionStage<T>> action, Executor executor) {
return CompletableFutures.completedNull().thenComposeAsync(ignored -> Exceptions.unchecked(action), executor);
}
public static <T> CompletionStage<T> sequence(CompletionStage<?> first, Callable<CompletionStage<T>> second) {
return first.thenCompose(ignored -> Exceptions.unchecked(second));
}
public static <T> CompletionStage<T> sequenceAsync(CompletionStage<?> first, Callable<CompletionStage<T>> second, Executor executor) {
return first.thenComposeAsync(ignored -> Exceptions.unchecked(second), executor);
}
/**
* Should be used by tests for a timeout when they need to wait for that timeout to expire.
*
* <p>Can be changed with the {@code org.infinispan.test.shortTimeoutMillis} system property.</p>
*/
public static long shortTimeoutMillis() {
return SHORT_TIMEOUT_MILLIS;
}
/**
* Simulates a node crash, discarding all the messages from/to this node and then stopping the caches.
*/
public static void crashCacheManagers(EmbeddedCacheManager... cacheManagers) {
for (EmbeddedCacheManager cm : cacheManagers) {
JChannel channel = extractJChannel(cm);
try {
DISCARD discard = new DISCARD();
discard.setDiscardAll(true);
channel.getProtocolStack().insertProtocol(discard, ProtocolStack.Position.ABOVE, TP.class);
} catch (Exception e) {
log.warn("Problems inserting discard", e);
throw new RuntimeException(e);
}
View view = View.create(channel.getAddress(), 100, channel.getAddress());
((GMS) channel.getProtocolStack().findProtocol(GMS.class)).installView(view);
}
killCacheManagers(cacheManagers);
}
public static void installNewView(EmbeddedCacheManager... members) {
installNewView(Stream.of(members).map(EmbeddedCacheManager::getAddress), members);
}
public static void installNewView(Function<EmbeddedCacheManager, JChannel> channelRetriever, EmbeddedCacheManager... members) {
installNewView(Stream.of(members).map(EmbeddedCacheManager::getAddress), channelRetriever, members);
}
public static void installNewView(Stream<Address> members, EmbeddedCacheManager... where) {
installNewView(members, TestingUtil::extractJChannel, where);
}
public static JChannel extractJChannel(EmbeddedCacheManager ecm) {
Transport transport = extractGlobalComponent(ecm, Transport.class);
while (!(transport instanceof JGroupsTransport)) {
if (Proxy.isProxyClass(transport.getClass())) {
// Unwrap proxies created by the StateSequencer
transport = extractField(extractField(transport, "h"), "wrappedInstance");
} else if (transport instanceof AbstractDelegatingTransport) {
transport = ((AbstractDelegatingTransport) transport).getDelegate();
} else {
throw new IllegalStateException("Unable to obtain a JGroupsTransport instance from " + transport + " on " + ecm.getAddress());
}
}
return ((JGroupsTransport) transport).getChannel();
}
public static void installNewView(Stream<Address> members, Function<EmbeddedCacheManager, JChannel> channelRetriever, EmbeddedCacheManager... where) {
List<org.jgroups.Address> viewMembers = members.map(a -> ((JGroupsAddress) a).getJGroupsAddress()).collect(Collectors.toList());
List<View> previousViews = new ArrayList<>(where.length);
for (EmbeddedCacheManager ecm : where) {
previousViews.add(((GMS) channelRetriever.apply(ecm).getProtocolStack().findProtocol(GMS.class)).view());
}
long viewId = previousViews.stream().mapToLong(view -> view.getViewId().getId()).max().orElse(0) + 1;
View newView;
if (previousViews.stream().allMatch(view -> view.getMembers().containsAll(viewMembers))) {
newView = View.create(viewMembers.get(0), viewId, viewMembers.toArray(new org.jgroups.Address[0]));
} else {
newView = new MergeView(new ViewId(viewMembers.get(0), viewId), viewMembers, previousViews);
}
log.trace("Before installing new view:" + viewMembers);
for (EmbeddedCacheManager ecm : where) {
((GMS) channelRetriever.apply(ecm).getProtocolStack().findProtocol(GMS.class)).installView(newView);
}
}
public static String wrapXMLWithSchema(String schema, String xml) {
StringBuilder sb = new StringBuilder();
sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
sb.append("<infinispan xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ");
sb.append("xsi:schemaLocation=\"urn:infinispan:config:");
sb.append(schema);
sb.append(" https://infinispan.org/schemas/infinispan-config-");
sb.append(schema);
sb.append(".xsd\" xmlns=\"urn:infinispan:config:");
sb.append(schema);
sb.append("\">\n");
sb.append(xml);
sb.append("</infinispan>");
return sb.toString();
}
public static String wrapXMLWithSchema(String xml) {
return wrapXMLWithSchema(Version.getSchemaVersion(), xml);
}
public static String wrapXMLWithoutSchema(String xml) {
StringBuilder sb = new StringBuilder();
sb.append("<infinispan>\n");
sb.append(xml);
sb.append("</infinispan>");
return sb.toString();
}
/**
* Extracts the value of a field in a given target instance using reflection, able to extract private fields as
* well.
*
* @param target object to extract field from
* @param fieldName name of field to extract
*
* @return field value
*/
public static <T> T extractField(Object target, String fieldName) {
//noinspection unchecked
return (T) extractField(target.getClass(), target, fieldName);
}
public static void replaceField(Object newValue, String fieldName, Object owner, Class<?> baseType) {
Field field;
try {
field = baseType.getDeclaredField(fieldName);
field.setAccessible(true);
field.set(owner, newValue);
}
catch (Exception e) {
throw new RuntimeException(e);//just to simplify exception handling
}
}
public static <T> void replaceField(Object owner, String fieldName, Function<T, T> func) {
replaceField(owner.getClass(), owner, fieldName, func);
}
public static <T> void replaceField(Class<?> baseType, Object owner, String fieldName, Function<T, T> func) {
Field field;
try {
field = baseType.getDeclaredField(fieldName);
field.setAccessible(true);
Object prevValue = field.get(owner);
Object newValue = func.apply((T) prevValue);
field.set(owner, newValue);
}
catch (Exception e) {
throw new RuntimeException(e);//just to simplify exception handling
}
}
public static Object extractField(Class<?> type, Object target, String fieldName) {
while (true) {
Field field;
try {
field = type.getDeclaredField(fieldName);
field.setAccessible(true);
return field.get(target);
}
catch (Exception e) {
if (type.equals(Object.class)) {
throw new RuntimeException(e);
} else {
// try with superclass!!
type = type.getSuperclass();
}
}
}
}
public static <T extends AsyncInterceptor> T findInterceptor(Cache<?, ?> cache,
Class<T> interceptorToFind) {
return extractInterceptorChain(cache).findInterceptorExtending(interceptorToFind);
}
public static int getSegmentForKey(Object key, Cache<?, ?> cache) {
KeyPartitioner keyPartitioner = extractComponent(cache, KeyPartitioner.class);
return keyPartitioner.getSegment(key);
}
/**
* Waits until pendingCH() is null on all caches, currentCH.getMembers() contains all caches provided as the param
* and all segments have numOwners owners.
*/
public static void waitForNoRebalance(Cache... caches) {
final int REBALANCE_TIMEOUT_SECONDS = 60; //Needs to be rather large to prevent sporadic failures on CI
final long giveup = System.nanoTime() + TimeUnit.SECONDS.toNanos(REBALANCE_TIMEOUT_SECONDS);
for (Cache<?, ?> c : caches) {
c = unwrapSecureCache(c);
int numOwners = c.getCacheConfiguration().clustering().hash().numOwners();
DistributionManager distributionManager = c.getAdvancedCache().getDistributionManager();
Address cacheAddress = c.getAdvancedCache().getRpcManager().getAddress();
CacheTopology cacheTopology;
while (true) {
cacheTopology = distributionManager.getCacheTopology();
boolean rebalanceInProgress;
boolean chContainsAllMembers;
boolean currentChIsBalanced;
if (cacheTopology != null) {
rebalanceInProgress = cacheTopology.getPhase() != CacheTopology.Phase.NO_REBALANCE;
ConsistentHash currentCH = cacheTopology.getCurrentCH();
ConsistentHashFactory chf = StateTransferManagerImpl.pickConsistentHashFactory(
extractGlobalConfiguration(c.getCacheManager()), c.getCacheConfiguration());
chContainsAllMembers = currentCH.getMembers().size() == caches.length;
currentChIsBalanced = true;
int actualNumOwners = Math.min(numOwners, currentCH.getMembers().size());
for (int i = 0; i < currentCH.getNumSegments(); i++) {
if (currentCH.locateOwnersForSegment(i).size() < actualNumOwners) {
currentChIsBalanced = false;
break;
}
}
// We need to check that the topologyId > 1 to account for nodes restarting
if (chContainsAllMembers && !rebalanceInProgress && cacheTopology.getTopologyId() > 1) {
rebalanceInProgress = !chf.rebalance(currentCH).equals(currentCH);
}
if (chContainsAllMembers && !rebalanceInProgress && currentChIsBalanced)
break;
} else {
rebalanceInProgress = false;
chContainsAllMembers = false;
currentChIsBalanced = true;
}
//System.out.printf("Cache %s Address %s cacheTopology %s rebalanceInProgress %s chContainsAllMembers %s, currentChIsBalanced %s\n", c.getName(), cacheAddress, cacheTopology, rebalanceInProgress, chContainsAllMembers, currentChIsBalanced);
if (System.nanoTime() - giveup > 0) {
String message;
if (!chContainsAllMembers) {
Address[] addresses = new Address[caches.length];
for (int i = 0; i < caches.length; i++) {
addresses[i] = caches[i].getCacheManager().getAddress();
}
message = String.format("Cache %s timed out waiting for rebalancing to complete on node %s, " +
"expected member list is %s, current member list is %s!", c.getName(), cacheAddress,
Arrays.toString(addresses), cacheTopology == null ? "N/A" : cacheTopology.getCurrentCH().getMembers());
} else {
message = String.format("Cache %s timed out waiting for rebalancing to complete on node %s, " +
"current topology is %s. rebalanceInProgress=%s, currentChIsBalanced=%s", c.getName(),
c.getCacheManager().getAddress(), cacheTopology, rebalanceInProgress, currentChIsBalanced);
}
log.error(message);
throw new RuntimeException(message);
}
LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(100));
}
log.trace("Node " + cacheAddress + " finished state transfer, has topology " + cacheTopology);
}
}
public static void waitForNoRebalanceAcrossManagers(EmbeddedCacheManager... managers) {
int numberOfManagers = managers.length;
assert numberOfManagers > 0;
Set<String> testCaches = getInternalAndUserCacheNames(managers[0]);
log.debugf("waitForNoRebalance with managers %s, for caches %s", Arrays.toString(managers), testCaches);
for (String cacheName : testCaches) {
ArrayList<Cache<?, ?>> caches = new ArrayList<>(numberOfManagers);
for (EmbeddedCacheManager manager : managers) {
Cache<?, ?> cache = manager.getCache(cacheName, false);
if (cache != null) {
caches.add(cache);
}
}
TestingUtil.waitForNoRebalance(caches.toArray(new Cache[0]));
}
}
public static Set<String> getInternalAndUserCacheNames(EmbeddedCacheManager cacheManager) {
Set<String> testCaches = new HashSet<>(cacheManager.getCacheNames());
testCaches.addAll(getInternalCacheNames(cacheManager));
return testCaches;
}
public static Set<String> getInternalCacheNames(CacheContainer container) {
return extractGlobalComponentRegistry(container).getComponent(InternalCacheRegistry.class).getInternalCacheNames();
}
public static void waitForTopologyPhase(List<Address> expectedMembers, CacheTopology.Phase phase,
Cache<?, ?>... caches) {
final int TOPOLOGY_TIMEOUT_SECONDS = 60; //Needs to be rather large to prevent sporadic failures on CI
final long giveup = System.nanoTime() + TimeUnit.SECONDS.toNanos(TOPOLOGY_TIMEOUT_SECONDS);
for (Cache<?, ?> c : caches) {
c = unwrapSecureCache(c);
DistributionManager distributionManager = c.getAdvancedCache().getDistributionManager();
while (true) {
CacheTopology cacheTopology = distributionManager.getCacheTopology();
boolean allMembersExist = cacheTopology != null && cacheTopology.getMembers().containsAll(expectedMembers);
boolean isCorrectPhase = cacheTopology != null && cacheTopology.getPhase() == phase;
if (allMembersExist && isCorrectPhase) break;
if (System.nanoTime() - giveup > 0) {
String message = String.format("Timed out waiting for a CacheTopology to be installed with members %s and phase %s. Current topology=%s",
expectedMembers, phase, cacheTopology);
log.error(message);
throw new RuntimeException(message);
}
LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(100));
}
}
}
private static Cache<?, ?> unwrapSecureCache(Cache<?, ?> c) {
if (c instanceof SecureCacheImpl) {
c = (Cache<?, ?>) extractField(SecureCacheImpl.class, c, "delegate");
}
return c;
}
public static void waitForNoRebalance(Collection<? extends Cache> caches) {
waitForNoRebalance(caches.toArray(new Cache[0]));
}
/**
* Loops, continually calling {@link #areCacheViewsComplete(Cache[])} until it either returns true or
* <code>timeout</code> ms have elapsed.
*
* @param caches caches which must all have consistent views
* @param timeout max number of ms to loop
*
* @throws RuntimeException if <code>timeout</code> ms have elapse without all caches having the same number of
* members.
*/
public static void blockUntilViewsReceived(Cache<?, ?>[] caches, long timeout) {
long failTime = System.currentTimeMillis() + timeout;
while (System.currentTimeMillis() < failTime) {
sleepThread(100);
if (areCacheViewsComplete(caches)) {
return;
}
}
viewsTimedOut(caches);
}
private static void viewsTimedOut(Cache<?, ?>[] caches) {
CacheContainer[] cacheContainers = new CacheContainer[caches.length];
for (int i = 0; i < caches.length; i++) {
cacheContainers[i] = caches[i].getCacheManager();
}
viewsTimedOut(cacheContainers);
}
private static void viewsTimedOut(CacheContainer[] cacheContainers) {
int length = cacheContainers.length;
List<View> incompleteViews = new ArrayList<>(length);
for (CacheContainer cacheContainer : cacheContainers) {
EmbeddedCacheManager cm = (EmbeddedCacheManager) cacheContainer;
if (cm.getMembers().size() != cacheContainers.length) {
incompleteViews.add(extractJChannel(cm).getView());
log.warnf("Manager %s has an incomplete view: %s", cm.getAddress(), cm.getMembers());
}
}
throw new TimeoutException(String.format(
"Timed out before caches had complete views. Expected %d members in each view. Views are as follows: %s",
cacheContainers.length, incompleteViews));
}
public static void blockUntilViewsReceivedInt(Cache<?, ?>[] caches, long timeout) throws InterruptedException {
long failTime = System.currentTimeMillis() + timeout;
while (System.currentTimeMillis() < failTime) {
sleepThreadInt(100, null);
if (areCacheViewsComplete(caches)) {
return;
}
}
viewsTimedOut(caches);
}
/**
* Version of blockUntilViewsReceived that uses varargs
*/
public static void blockUntilViewsReceived(long timeout, Cache<?, ?>... caches) {
blockUntilViewsReceived(caches, timeout);
}
/**
* Version of blockUntilViewsReceived that throws back any interruption
*/
public static void blockUntilViewsReceivedInt(long timeout, Cache<?, ?>... caches) throws InterruptedException {
blockUntilViewsReceivedInt(caches, timeout);
}
/**
* Version of blockUntilViewsReceived that uses varargsa and cache managers
*/
public static void blockUntilViewsReceived(long timeout, CacheContainer... cacheContainers) {
blockUntilViewsReceived(timeout, true, cacheContainers);
}
/**
* Waits for the given members to be removed from the cluster. The difference between this and {@link
* #blockUntilViewsReceived(long, org.infinispan.manager.CacheContainer...)} methods(s) is that it does not barf if
* more than expected members is in the cluster - this is because we expect to start with a grater number fo members
* than we eventually expect. It will barf though, if the number of members is not the one expected but only after
* the timeout expires.
*/
public static void blockForMemberToFail(long timeout, CacheContainer... cacheContainers) {
blockUntilViewsReceived(timeout, false, cacheContainers);
areCacheViewsComplete(true, cacheContainers);
}
public static void blockUntilViewsReceived(long timeout, boolean barfIfTooManyMembers, CacheContainer... cacheContainers) {
long failTime = System.currentTimeMillis() + timeout;
while (System.currentTimeMillis() < failTime) {
if (areCacheViewsComplete(barfIfTooManyMembers, cacheContainers)) {
return;
}
sleepThread(100);
}
viewsTimedOut(cacheContainers);
}
/**
* An overloaded version of {@link #blockUntilViewsReceived(long,Cache[])} that allows for 'shrinking' clusters.
* I.e., the usual method barfs if there are more members than expected. This one takes a param
* (barfIfTooManyMembers) which, if false, will NOT barf but will wait until the cluster 'shrinks' to the desired
* size. Useful if in tests, you kill a member and want to wait until this fact is known across the cluster.
*/
public static void blockUntilViewsReceived(long timeout, boolean barfIfTooManyMembers, Cache<?, ?>... caches) {
long failTime = System.currentTimeMillis() + timeout;
while (System.currentTimeMillis() < failTime) {
sleepThread(100);
if (areCacheViewsComplete(caches, barfIfTooManyMembers)) {
return;
}
}
viewsTimedOut(caches);
}
/**
* Loops, continually calling {@link #areCacheViewsComplete(Cache[])} until it either returns true or
* <code>timeout</code> ms have elapsed.
*
* @param groupSize number of caches expected in the group
* @param timeout max number of ms to loop
*
* @throws RuntimeException if <code>timeout</code> ms have elapse without all caches having the same number of
* members.
*/
public static void blockUntilViewReceived(Cache<?, ?> cache, int groupSize, long timeout) {
blockUntilViewReceived(cache, groupSize, timeout, true);
}
/**
* Loops, continually calling {@link #areCacheViewsComplete(Cache[])} until
* it either returns true or a default timeout has elapsed.
*
* @param groupSize number of caches expected in the group
*/
public static void blockUntilViewReceived(Cache<?, ?> cache, int groupSize) {
// Default 10 seconds
blockUntilViewReceived(cache, groupSize, 10000, true);
}
public static void blockUntilViewReceived(Cache<?, ?> cache, int groupSize, long timeout, boolean barfIfTooManyMembersInView) {
long failTime = System.currentTimeMillis() + timeout;
while (System.currentTimeMillis() < failTime) {
sleepThread(100);
EmbeddedCacheManager cacheManager = cache.getCacheManager();
if (isCacheViewComplete(cacheManager.getMembers(), cacheManager.getAddress(), groupSize, barfIfTooManyMembersInView)) {
return;
}
}
throw new RuntimeException(String.format(
"Timed out before cache had %d members. View is %s",
groupSize, cache.getCacheManager().getMembers()));
}
/**
* Checks each cache to see if the number of elements in the array returned by {@link
* EmbeddedCacheManager#getMembers()} matches the size of the <code>caches</code> parameter.
*
* @param caches caches that should form a View
*
* @return <code>true</code> if all caches have <code>caches.length</code> members; false otherwise
*
* @throws IllegalStateException if any of the caches have MORE view members than caches.length
*/
public static boolean areCacheViewsComplete(Cache<?, ?>[] caches) {
return areCacheViewsComplete(caches, true);
}
public static boolean areCacheViewsComplete(Cache<?, ?>[] caches, boolean barfIfTooManyMembers) {
int memberCount = caches.length;
for (Cache<?, ?> cache : caches) {
EmbeddedCacheManager cacheManager = cache.getCacheManager();
if (!isCacheViewComplete(cacheManager.getMembers(), cacheManager.getAddress(), memberCount, barfIfTooManyMembers)) {
return false;
}
}
return true;
}
public static boolean areCacheViewsComplete(boolean barfIfTooManyMembers, CacheContainer... cacheContainers) {
if (cacheContainers == null) throw new NullPointerException("Cache Manager array is null");
int memberCount = cacheContainers.length;
for (CacheContainer cacheContainer : cacheContainers) {
EmbeddedCacheManager cacheManager = (EmbeddedCacheManager) cacheContainer;
if (!isCacheViewComplete(cacheManager.getMembers(), cacheManager.getAddress(), memberCount, barfIfTooManyMembers)) {
return false;
}
}
return true;
}
public static boolean isCacheViewComplete(Cache<?, ?> c, int memberCount) {
EmbeddedCacheManager cacheManager = c.getCacheManager();
return isCacheViewComplete(cacheManager.getMembers(), cacheManager.getAddress(), memberCount, true);
}
public static boolean isCacheViewComplete(List<Address> members, Address address, int memberCount, boolean barfIfTooManyMembers) {
if (members == null || memberCount > members.size()) {
return false;
} else if (memberCount < members.size()) {
if (barfIfTooManyMembers) {
// This is an exceptional condition
StringBuilder sb = new StringBuilder("Cache at address ");
sb.append(address);
sb.append(" had ");
sb.append(members.size());
sb.append(" members; expecting ");
sb.append(memberCount);
sb.append(". Members were (");
for (int j = 0; j < members.size(); j++) {
if (j > 0) {
sb.append(", ");
}
sb.append(members.get(j));
}
sb.append(')');
throw new IllegalStateException(sb.toString());
} else return false;
}
return true;
}
/**
* This method blocks until the given caches have a view of whose size
* matches the desired value. This method is particularly useful for
* discovering that members have been split, or that they have joined back
* again.
*
* @param timeout max number of milliseconds to block for
* @param finalViewSize desired final view size
* @param caches caches representing current, or expected members in the cluster.
*/
public static void blockUntilViewsChanged(long timeout, int finalViewSize, Cache<?, ?>... caches) {
blockUntilViewsChanged(caches, timeout, finalViewSize);
}
private static void blockUntilViewsChanged(Cache<?, ?>[] caches, long timeout, int finalViewSize) {
long failTime = System.currentTimeMillis() + timeout;
while (System.currentTimeMillis() < failTime) {
sleepThread(100);
if (areCacheViewsChanged(caches, finalViewSize)) {
return;
}
}
List<List<Address>> allViews = new ArrayList<>(caches.length);
for (Cache<?, ?> cache : caches) {
allViews.add(cache.getCacheManager().getMembers());
}
throw new RuntimeException(String.format(
"Timed out before caches had changed views (%s) to contain %d members",
allViews, finalViewSize));
}
private static boolean areCacheViewsChanged(Cache<?, ?>[] caches, int finalViewSize) {
for (Cache<?, ?> cache : caches) {
EmbeddedCacheManager cacheManager = cache.getCacheManager();
if (!isCacheViewChanged(cacheManager.getMembers(), finalViewSize)) {
return false;
}
}
return true;
}
private static boolean isCacheViewChanged(List<Address> members, int finalViewSize) {
return !(members == null || finalViewSize != members.size());
}
/**
* Puts the current thread to sleep for the desired number of ms, suppressing any exceptions.
*
* @param sleeptime number of ms to sleep
*/
public static void sleepThread(long sleeptime) {
sleepThread(sleeptime, null);
}
public static void sleepThread(long sleeptime, String messageOnInterrupt) {
try {
Thread.sleep(sleeptime);
}
catch (InterruptedException ie) {
if (messageOnInterrupt != null)
log.error(messageOnInterrupt);
}
}
private static void sleepThreadInt(long sleeptime, String messageOnInterrupt) throws InterruptedException {
try {
Thread.sleep(sleeptime);
}
catch (InterruptedException ie) {
if (messageOnInterrupt != null)
log.error(messageOnInterrupt);
throw ie;
}
}
public static void sleepRandom(int maxTime) {
sleepThread(random.nextInt(maxTime));
}
public static void killCacheManagers(CacheContainer... cacheContainers) {
EmbeddedCacheManager[] cms = new EmbeddedCacheManager[cacheContainers.length];
for (int i = 0; i < cacheContainers.length; i++) cms[i] = (EmbeddedCacheManager) cacheContainers[i];
killCacheManagers(cms);
}
public static void killCacheManagers(EmbeddedCacheManager... cacheManagers) {
killCacheManagers(Arrays.asList(cacheManagers));
}
public static void killCacheManagers(List<? extends EmbeddedCacheManager> cacheManagers) {
// Stop the managers in reverse order to prevent each of them from becoming coordinator in turn
for (int i = cacheManagers.size() - 1; i >= 0; i--) {
EmbeddedCacheManager cm = cacheManagers.get(i);
try {
if (cm != null) {
SecurityActions.stopManager(cm);
}
} catch (Throwable e) {
log.warn("Problems killing cache manager " + cm, e);
}
}
}
public static void clearContent(EmbeddedCacheManager... cacheManagers) {
clearContent(Arrays.asList(cacheManagers));
}
public static void clearContent(List<? extends EmbeddedCacheManager> cacheManagers) {
for (EmbeddedCacheManager cm : cacheManagers) {
try {
clearContent(cm);
} catch (Throwable e) {
log.warn("Problems clearing cache manager " + cm, e);
}
}
}
public static void clearContent(EmbeddedCacheManager cacheContainer) {
if (cacheContainer != null && cacheContainer.getStatus().allowInvocations()) {
Set<Cache<?, ?>> runningCaches = getRunningCaches(cacheContainer);
for (Cache<?, ?> cache : runningCaches) {
clearRunningTx(cache);
}
if (!cacheContainer.getStatus().allowInvocations()) return;
for (Cache<?, ?> cache : runningCaches) {
try {
clearCacheLoader(cache);
removeInMemoryData(cache);
} catch (Exception e) {
log.errorf(e, "Failed to clear cache %s after test", cache);
}
}
}
}
private static Set<String> getOrderedCacheNames(EmbeddedCacheManager cacheContainer) {
Set<String> caches = new LinkedHashSet<>();
try {
DependencyGraph<String> graph =
TestingUtil.extractGlobalComponent(cacheContainer, DependencyGraph.class,
KnownComponentNames.CACHE_DEPENDENCY_GRAPH);
caches.addAll(graph.topologicalSort());
} catch (Exception ignored) {
}
return caches;
}
private static Set<Cache<?, ?>> getRunningCaches(EmbeddedCacheManager cacheContainer) {
if (cacheContainer == null || !cacheContainer.getStatus().allowInvocations())
return Collections.emptySet();
Set<String> running = new LinkedHashSet<>(getOrderedCacheNames(cacheContainer));
extractGlobalComponent(cacheContainer, InternalCacheRegistry.class).filterPrivateCaches(running);
running.addAll(cacheContainer.getCacheNames());
extractGlobalConfiguration(cacheContainer).defaultCacheName().ifPresent(running::add);
HashSet<Cache<?, ?>> runningCaches = new LinkedHashSet<>();
for (String cacheName : running) {
Cache<?, ?> cache;
try {
cache = cacheContainer.getCache(cacheName, false);
} catch (CacheException ignoreCache) {
// Ignore caches that have not started correctly
continue;
}
if (cache != null && cache.getStatus().allowInvocations())
runningCaches.add(cache);
}
return runningCaches;
}
public static GlobalConfiguration extractGlobalConfiguration(EmbeddedCacheManager cacheContainer) {
return SecurityActions.getCacheManagerConfiguration(cacheContainer);
}
private static void clearRunningTx(Cache<?, ?> cache) {
if (cache != null) {
TransactionManager txm = TestingUtil.getTransactionManager(cache);
killTransaction(txm);
}
}
public static void clearCacheLoader(Cache<?, ?> cache) {
PersistenceManager persistenceManager = TestingUtil.extractComponent(cache, PersistenceManager.class);
CompletionStages.join(persistenceManager.clearAllStores(BOTH));
}
public static <K, V> List<DummyInMemoryStore> cachestores(List<Cache<K, V>> caches) {
List<DummyInMemoryStore> l = new LinkedList<>();
for (Cache<K, V> c: caches)
l.add(TestingUtil.getFirstStore(c));
return l;
}
private static void removeInMemoryData(Cache<?, ?> cache) {
log.debugf("Cleaning data for cache %s", cache);
InternalDataContainer<?, ?> dataContainer = TestingUtil.extractComponent(cache, InternalDataContainer.class);
if (log.isDebugEnabled()) log.debugf("Data container size before clear: %d", dataContainer.sizeIncludingExpired());
dataContainer.clear();
}
/**
* Kills a cache - stops it, clears any data in any stores, and rolls back any associated txs
*/
public static void killCaches(Cache<?, ?>... caches) {
killCaches(Arrays.asList(caches));
}
/**
* Kills a cache - stops it and rolls back any associated txs
*/
public static void killCaches(Collection<? extends Cache<?, ?>> caches) {
for (Cache<?, ?> c : caches) {
try {
if (c != null && c.getStatus() == ComponentStatus.RUNNING) {
TransactionManager tm = c.getAdvancedCache().getTransactionManager();
if (tm != null) {
try {
tm.rollback();
}
catch (Exception e) {
// don't care
}
}
// retrieve the size before calling log, as evaluating the set may cause recursive log calls
long size = log.isTraceEnabled() ? c.getAdvancedCache().withFlags(Flag.CACHE_MODE_LOCAL).size() : 0;
if (c.getAdvancedCache().getRpcManager() != null) {
log.tracef("Local size on %s before stopping: %d", c.getAdvancedCache().getRpcManager().getAddress(), size);
} else {
log.tracef("Local size before stopping: %d", size);
}
c.stop();
}
}
catch (Throwable t) {
log.errorf(t, "Error killing cache %s", c.getName());
}
}
}
/**