-
Notifications
You must be signed in to change notification settings - Fork 612
/
CacheNotifierImplInitialTransferDistTest.java
762 lines (638 loc) · 36.7 KB
/
CacheNotifierImplInitialTransferDistTest.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
package org.infinispan.notifications.cachelistener;
import static org.mockito.Mockito.argThat;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.withSettings;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Stream;
import org.hamcrest.core.IsInstanceOf;
import org.infinispan.Cache;
import org.infinispan.CacheSet;
import org.infinispan.CacheStream;
import org.infinispan.commands.VisitableCommand;
import org.infinispan.commands.read.EntrySetCommand;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.context.InvocationContext;
import org.infinispan.distribution.ch.ConsistentHash;
import org.infinispan.interceptors.AsyncInterceptorChain;
import org.infinispan.notifications.Listener;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryModified;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryRemoved;
import org.infinispan.notifications.cachelistener.cluster.ClusterCacheNotifier;
import org.infinispan.notifications.cachelistener.event.CacheEntryEvent;
import org.infinispan.notifications.cachelistener.event.Event;
import org.infinispan.remoting.transport.Address;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.fwk.CheckPoint;
import org.mockito.AdditionalAnswers;
import org.mockito.Mockito;
import org.mockito.stubbing.Answer;
import org.testng.annotations.Test;
@Test(groups = "unit", testName = "notifications.cachelistener.CacheNotifierImplInitialTransferDistTest")
public class CacheNotifierImplInitialTransferDistTest extends MultipleCacheManagersTest {
private final String CACHE_NAME = "DistInitialTransferListener";
@Override
protected void createCacheManagers() throws Throwable {
createClusteredCaches(3, CACHE_NAME, getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC));
}
private enum Operation {
PUT(Event.Type.CACHE_ENTRY_MODIFIED), CREATE(Event.Type.CACHE_ENTRY_CREATED), REMOVE(Event.Type.CACHE_ENTRY_REMOVED) {
@Override
public <K, V> Object perform(Cache<K, V> cache, K key, V value) {
return cache.remove(key);
}
};
private final Event.Type type;
Operation(Event.Type type) {
this.type = type;
}
public Event.Type getType() {
return type;
}
public <K, V> Object perform(Cache<K, V> cache, K key, V value) {
return cache.put(key, value);
}
}
// TODO: commented out until local listners support includeCurrentState
// public void testSimpleCacheStartingNonClusterListener() {
// testSimpleCacheStarting(new StateListenerNotClustered());
// }
public void testSimpleCacheStartingClusterListener() {
testSimpleCacheStarting(new StateListenerClustered());
}
private void testSimpleCacheStarting(final StateListener<String, String> listener) {
final Map<String, String> expectedValues = new HashMap<String, String>(10);
Cache<String, String> cache = cache(0, CACHE_NAME);
populateCache(cache, expectedValues);
cache.addListener(listener);
try {
verifyEvents(isClustered(listener), listener, expectedValues);
} finally {
cache.removeListener(listener);
}
}
private void populateCache(Cache<String, String> cache, Map<String, String> expectedValues) {
for (int i = 0; i < 10; i++) {
String key = "key-" + i;
String value = "value-" + i;
expectedValues.put(key, value);
cache.put(key, value);
}
}
private void verifyEvents(boolean isClustered, StateListener<String, String> listener,
Map<String, String> expected) {
assertEquals(listener.events.size(), isClustered ? expected.size() : expected.size() * 2);
boolean isPost = true;
for (CacheEntryEvent<String, String> event : listener.events) {
// Even checks means it will be post and have a value - note we force every check to be
// even for clustered since those should always be post
if (!isClustered) {
isPost = !isPost;
}
assertEquals(event.getType(), Event.Type.CACHE_ENTRY_CREATED);
assertTrue(expected.containsKey(event.getKey()));
assertEquals(event.isPre(), !isPost);
if (isPost) {
assertEquals(event.getValue(), expected.get(event.getKey()));
} else {
assertNull(event.getValue());
}
}
}
// TODO: commented out until local listners support includeCurrentState
// public void testCreateAfterIterationBeganButNotIteratedValueYetNonOwnerNotClustered()
// throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException {
// testModificationAfterIterationBeganButNotIteratedValueYet(new StateListenerNotClustered(), Operation.CREATE, false);
// }
public void testCreateAfterIterationBeganButNotIteratedValueYetNonOwnerClustered()
throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException {
testModificationAfterIterationBeganButNotIteratedValueYet(new StateListenerClustered(), Operation.CREATE, false);
}
// TODO: commented out until local listners support includeCurrentState
// public void testCreateAfterIterationBeganButNotIteratedValueYetOwnerNotClustered()
// throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException {
// testModificationAfterIterationBeganButNotIteratedValueYet(new StateListenerNotClustered(), Operation.CREATE, true);
// }
public void testCreateAfterIterationBeganButNotIteratedValueYetOwnerClustered()
throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException {
testModificationAfterIterationBeganButNotIteratedValueYet(new StateListenerClustered(), Operation.CREATE, true);
}
// TODO: commented out until local listners support includeCurrentState
// public void testModificationAfterIterationBeganButNotIteratedValueYetNonOwnerNotClustered()
// throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException {
// testModificationAfterIterationBeganButNotIteratedValueYet(new StateListenerNotClustered(), Operation.PUT, false);
// }
public void testModificationAfterIterationBeganButNotIteratedValueYetNonOwnerClustered()
throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException {
testModificationAfterIterationBeganButNotIteratedValueYet(new StateListenerClustered(), Operation.PUT, false);
}
// TODO: commented out until local listners support includeCurrentState
// public void testModificationAfterIterationBeganButNotIteratedValueYetOwnerNotClustered()
// throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException {
// testModificationAfterIterationBeganButNotIteratedValueYet(new StateListenerNotClustered(), Operation.PUT, true);
// }
public void testModificationAfterIterationBeganButNotIteratedValueYetOwnerClustered()
throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException {
testModificationAfterIterationBeganButNotIteratedValueYet(new StateListenerClustered(), Operation.PUT, true);
}
// TODO: commented out until local listners support includeCurrentState
// public void testRemoveAfterIterationBeganButNotIteratedValueYetNonOwnerNotClustered()
// throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException {
// testModificationAfterIterationBeganButNotIteratedValueYet(new StateListenerNotClustered(), Operation.REMOVE, false);
// }
public void testRemoveAfterIterationBeganButNotIteratedValueYetNonOwnerClustered()
throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException {
testModificationAfterIterationBeganButNotIteratedValueYet(new StateListenerClustered(), Operation.REMOVE, false);
}
// TODO: commented out until local listners support includeCurrentState
// public void testRemoveAfterIterationBeganButNotIteratedValueYetOwnerNotClustered()
// throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException {
// testModificationAfterIterationBeganButNotIteratedValueYet(new StateListenerNotClustered(), Operation.REMOVE, true);
// }
public void testRemoveAfterIterationBeganButNotIteratedValueYetOwnerClustered()
throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException {
testModificationAfterIterationBeganButNotIteratedValueYet(new StateListenerClustered(), Operation.REMOVE, true);
}
/**
* This test is to verify that the modification event replaces the current value for the key
*/
private void testModificationAfterIterationBeganButNotIteratedValueYet(final StateListener<String, String> listener,
Operation operation, boolean shouldBePrimaryOwner)
throws InterruptedException, TimeoutException, BrokenBarrierException, ExecutionException {
final Map<String, String> expectedValues = new HashMap<>(10);
final Cache<String, String> cache = cache(0, CACHE_NAME);
populateCache(cache, expectedValues);
final CheckPoint checkPoint = new CheckPoint();
AsyncInterceptorChain chain = mockStream(cache, (mock, real, additional) ->
doAnswer(i -> {
// Wait for main thread to sync up
checkPoint.trigger("pre_retrieve_entry_invoked");
// Now wait until main thread lets us through
checkPoint.awaitStrict("pre_retrieve_entry_released", 10, TimeUnit.SECONDS);
return i.getMethod().invoke(real, i.getArguments());
}).when(mock).iterator());
try {
String keyToChange = findKeyBasedOnOwnership("key-to-change",
cache.getAdvancedCache().getDistributionManager().getConsistentHash(), shouldBePrimaryOwner,
cache.getCacheManager().getAddress());
String value = prepareOperation(operation, cache, keyToChange);
if (value != null) {
expectedValues.put(keyToChange, value);
}
Future<Void> future = fork(() -> {
cache.addListener(listener);
return null;
});
checkPoint.awaitStrict("pre_retrieve_entry_invoked", 10000, TimeUnit.SECONDS);
operation.perform(cache, keyToChange, value);
// Now let the iteration complete
checkPoint.triggerForever("pre_retrieve_entry_released");
future.get(10, TimeUnit.SECONDS);
verifyEvents(isClustered(listener), listener, expectedValues);
} finally {
TestingUtil.replaceComponent(cache, AsyncInterceptorChain.class, chain, true);
cache.removeListener(listener);
}
}
private String prepareOperation(Operation operation, Cache<String, String> cache, String keyToChange) {
String value;
switch (operation) {
case CREATE:
value = "new-value";
break;
case PUT:
cache.put(keyToChange, "initial-value");
value = "changed-value";
break;
case REMOVE:
cache.put(keyToChange, "initial-value");
value = null;
break;
default:
throw new IllegalArgumentException("Unsupported Operation provided " + operation);
}
return value;
}
/**
* This test is to verify that the modification event is sent after the creation event is done
*/
private void testModificationAfterIterationBeganAndCompletedSegmentValueOwner(final StateListener<String, String> listener,
Operation operation,
boolean shouldBePrimaryOwner)
throws IOException, InterruptedException, TimeoutException, BrokenBarrierException, ExecutionException {
final Map<String, String> expectedValues = new HashMap<String, String>(10);
final Cache<String, String> cache = cache(0, CACHE_NAME);
populateCache(cache, expectedValues);
CheckPoint checkPoint = new CheckPoint();
AsyncInterceptorChain chain = mockStream(cache, (mock, real, additional) -> {
doAnswer(i -> {
// Wait for main thread to sync up
checkPoint.trigger("pre_close_iter_invoked");
// Now wait until main thread lets us through
checkPoint.awaitStrict("pre_close_iter_released", 10, TimeUnit.SECONDS);
return i.getMethod().invoke(real, i.getArguments());
}).when(mock).close();
doAnswer(i -> i.getMethod().invoke(real, i.getArguments())).when(mock).iterator();
});
try {
String keyToChange = findKeyBasedOnOwnership("key-to-change",
cache.getAdvancedCache().getDistributionManager().getConsistentHash(), shouldBePrimaryOwner,
cache.getCacheManager().getAddress());
String value = prepareOperation(operation, cache, keyToChange);
if (cache.get(keyToChange) != null) {
expectedValues.put(keyToChange, cache.get(keyToChange));
}
Future<Void> future = fork(() -> {
cache.addListener(listener);
return null;
});
checkPoint.awaitStrict("pre_close_iter_invoked", 10, TimeUnit.SECONDS);
Object oldValue = operation.perform(cache, keyToChange, value);
// Now let the iteration complete
checkPoint.triggerForever("pre_close_iter_released");
future.get(10, TimeUnit.SECONDS);
boolean isClustered = isClustered(listener);
// We should have 1 or 2 (local) events due to the modification coming after we iterated on it. Note the value
// isn't brought up until the iteration is done
assertEquals(listener.events.size(), isClustered ? expectedValues.size() + 1 : (expectedValues.size() + 1) * 2);
// Assert the first 10/20 since they should all be from iteration - this may not work since segments complete earlier..
boolean isPost = true;
int position = 0;
for (; position < (isClustered ? expectedValues.size() : expectedValues.size() * 2); ++position) {
// Even checks means it will be post and have a value - note we force every check to be
// even for clustered since those should always be post
if (!isClustered) {
isPost = !isPost;
}
CacheEntryEvent event = listener.events.get(position);
assertEquals(event.getType(), Event.Type.CACHE_ENTRY_CREATED);
assertTrue(expectedValues.containsKey(event.getKey()));
assertEquals(event.isPre(), !isPost);
if (isPost) {
assertEquals(event.getValue(), expectedValues.get(event.getKey()));
} else {
assertNull(event.getValue());
}
}
// We should have 2 extra events at the end which are our modifications
if (isClustered) {
CacheEntryEvent<String, String> event = listener.events.get(position);
assertEquals(event.getType(), operation.getType());
assertEquals(event.isPre(), false);
assertEquals(event.getKey(), keyToChange);
assertEquals(event.getValue(), value);
} else {
CacheEntryEvent<String, String> event = listener.events.get(position);
assertEquals(event.getType(), operation.getType());
assertEquals(event.isPre(), true);
assertEquals(event.getKey(), keyToChange);
assertEquals(event.getValue(), oldValue);
event = listener.events.get(position + 1);
assertEquals(event.getType(), operation.getType());
assertEquals(event.isPre(), false);
assertEquals(event.getKey(), keyToChange);
assertEquals(event.getValue(), value);
}
} finally {
TestingUtil.replaceComponent(cache, AsyncInterceptorChain.class, chain, true);
cache.removeListener(listener);
}
}
private String findKeyBasedOnOwnership(String keyPrefix, ConsistentHash hash, boolean shouldBePrimaryOwner,
Address address) {
for (int i = 0; i < 1000; i++) {
String key = keyPrefix + i;
boolean isPrimaryOwner = hash.locatePrimaryOwner(key).equals(address);
if (isPrimaryOwner == shouldBePrimaryOwner) {
if (shouldBePrimaryOwner) {
log.debugf("Found key %s with primary owner %s, segment %d", key, address, hash.getSegment(key));
} else {
log.debugf("Found key %s with primary owner != %s, segment %d", key, address, hash.getSegment(key));
}
return key;
}
}
throw new RuntimeException("No key could be found for owner, this may be a bug in test or really bad luck!");
}
// TODO: commented out until local listners support includeCurrentState
// public void testCreateAfterIterationBeganAndCompletedSegmentValueNonOwnerNotClustered()
// throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException, IOException {
// testModificationAfterIterationBeganAndCompletedSegmentValueOwner(new StateListenerNotClustered(), Operation.CREATE, false);
// }
public void testCreateAfterIterationBeganAndCompletedSegmentValueNonOwnerClustered()
throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException, IOException {
testModificationAfterIterationBeganAndCompletedSegmentValueOwner(new StateListenerClustered(), Operation.CREATE, false);
}
// TODO: commented out until local listners support includeCurrentState
// public void testCreateAfterIterationBeganAndCompletedSegmentValueOwnerNotClustered()
// throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException, IOException {
// testModificationAfterIterationBeganAndCompletedSegmentValueOwner(new StateListenerNotClustered(), Operation.CREATE, true);
// }
public void testCreateAfterIterationBeganAndCompletedSegmentValueOwnerClustered()
throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException, IOException {
testModificationAfterIterationBeganAndCompletedSegmentValueOwner(new StateListenerClustered(), Operation.CREATE, true);
}
// TODO: commented out until local listners support includeCurrentState
// public void testModificationAfterIterationBeganAndCompletedSegmentValueNonOwnerNotClustered()
// throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException, IOException {
// testModificationAfterIterationBeganAndCompletedSegmentValueOwner(new StateListenerNotClustered(), Operation.PUT, false);
// }
public void testModificationAfterIterationBeganAndCompletedSegmentValueNonOwnerClustered()
throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException, IOException {
testModificationAfterIterationBeganAndCompletedSegmentValueOwner(new StateListenerClustered(), Operation.PUT, false);
}
// TODO: commented out until local listners support includeCurrentState
// public void testModificationAfterIterationBeganAndCompletedSegmentValueOwnerNotClustered()
// throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException, IOException {
// testModificationAfterIterationBeganAndCompletedSegmentValueOwner(new StateListenerNotClustered(), Operation.PUT, true);
// }
public void testModificationAfterIterationBeganAndCompletedSegmentValueOwnerClustered()
throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException, IOException {
testModificationAfterIterationBeganAndCompletedSegmentValueOwner(new StateListenerClustered(), Operation.PUT, true);
}
// TODO: commented out until local listners support includeCurrentState
// public void testRemoveAfterIterationBeganAndCompletedSegmentValueNonOwnerNotClustered()
// throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException, IOException {
// testModificationAfterIterationBeganAndCompletedSegmentValueOwner(new StateListenerNotClustered(), Operation.REMOVE, false);
// }
public void testRemoveAfterIterationBeganAndCompletedSegmentValueNonOwnerClustered()
throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException, IOException {
testModificationAfterIterationBeganAndCompletedSegmentValueOwner(new StateListenerClustered(), Operation.REMOVE, false);
}
// TODO: commented out until local listners support includeCurrentState
// public void testRemoveAfterIterationBeganAndCompletedSegmentValueOwnerNotClustered()
// throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException, IOException {
// testModificationAfterIterationBeganAndCompletedSegmentValueOwner(new StateListenerNotClustered(), Operation.REMOVE, true);
// }
public void testRemoveAfterIterationBeganAndCompletedSegmentValueOwnerClustered()
throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException, IOException {
testModificationAfterIterationBeganAndCompletedSegmentValueOwner(new StateListenerClustered(), Operation.REMOVE, true);
}
protected void testIterationBeganAndSegmentNotComplete(final StateListener<String, String> listener,
Operation operation, boolean shouldBePrimaryOwner)
throws TimeoutException, InterruptedException, ExecutionException {
final Map<String, String> expectedValues = new HashMap<String, String>(10);
final Cache<String, String> cache = cache(0, CACHE_NAME);
populateCache(cache, expectedValues);
String keyToChange = findKeyBasedOnOwnership("key-to-change-",
cache.getAdvancedCache().getDistributionManager().getConsistentHash(), shouldBePrimaryOwner,
cache.getCacheManager().getAddress());
String value = prepareOperation(operation, cache, keyToChange);
if (cache.get(keyToChange) != null) {
expectedValues.put(keyToChange, cache.get(keyToChange));
}
CheckPoint checkPoint = new CheckPoint();
int segmentToUse = cache.getAdvancedCache().getDistributionManager().getConsistentHash().getSegment(keyToChange);
// do the operation, which should put it in the queue.
ClusterCacheNotifier notifier = waitUntilClosingSegment(cache, segmentToUse, checkPoint);
Future<Void> future = fork(new Callable<Void>() {
@Override
public Void call() throws Exception {
cache.addListener(listener);
return null;
}
});
try {
checkPoint.awaitStrict("pre_complete_segment_invoked", 10, TimeUnit.SECONDS);
Object oldValue = operation.perform(cache, keyToChange, value);
// Now let the iteration complete
checkPoint.triggerForever("pre_complete_segment_released");
future.get(10, TimeUnit.SECONDS);
boolean isClustered = isClustered(listener);
// We should have 1 or 2 (local) events due to the modification coming after we iterated on it. Note the value
// isn't brought up until the iteration is done
assertEquals(listener.events.size(), isClustered ? expectedValues.size() + 1 : (expectedValues.size() + 1) * 2);
// If it is clustered, then the modify can occur in the middle. In non clustered we have to block all events
// just in case of tx event listeners (ie. tx start/tx end would have to wrap all events) and such so we can't
// release them early. The cluster listeners aren't affected by transaction since it those are not currently
// supported
if (isClustered) {
CacheEntryEvent event = null;
boolean foundEarlierCreate = false;
// We iterate backwards so we only have to do it once
for (int i = listener.events.size() - 1; i >= 0; --i) {
CacheEntryEvent currentEvent = listener.events.get(i);
if (currentEvent.getKey().equals(keyToChange) && operation.getType() == currentEvent.getType()) {
if (event == null) {
event = currentEvent;
// We can remove safely since we are doing backwards counter as well
listener.events.remove(i);
// If it is a create there is no previous create
if (operation.getType() == Event.Type.CACHE_ENTRY_CREATED) {
foundEarlierCreate = true;
break;
}
} else {
fail("There should only be a single event in the event queue!");
}
} else if (event != null && (foundEarlierCreate = event.getKey().equals(currentEvent.getKey()))) {
break;
}
}
// This should have been set
assertTrue(foundEarlierCreate, "There was no matching create event for key " + event.getKey());
assertEquals(event.getType(), operation.getType());
assertEquals(event.isPre(), false);
assertEquals(event.getValue(), value);
}
// Assert the first 10/20 since they should all be from iteration - this may not work since segments complete earlier..
boolean isPost = true;
int position = 0;
for (; position < (isClustered ? expectedValues.size() : expectedValues.size() * 2); ++position) {
// Even checks means it will be post and have a value - note we force every check to be
// even for clustered since those should always be post
if (!isClustered) {
isPost = !isPost;
}
CacheEntryEvent<String, String> event = listener.events.get(position);
assertEquals(event.getType(), Event.Type.CACHE_ENTRY_CREATED);
assertTrue(expectedValues.containsKey(event.getKey()));
assertEquals(event.isPre(), !isPost);
if (isPost) {
assertEquals(event.getValue(), expectedValues.get(event.getKey()));
} else {
assertNull(event.getValue());
}
}
// We should have 2 extra events at the end which are our modifications
if (!isClustered) {
CacheEntryEvent<String, String> event = listener.events.get(position);
assertEquals(event.getType(), operation.getType());
assertEquals(event.isPre(), true);
assertEquals(event.getKey(), keyToChange);
assertEquals(event.getValue(), oldValue);
event = listener.events.get(position + 1);
assertEquals(event.getType(), operation.getType());
assertEquals(event.isPre(), false);
assertEquals(event.getKey(), keyToChange);
assertEquals(event.getValue(), value);
}
} finally {
cache.removeListener(listener);
TestingUtil.replaceComponent(cache, CacheNotifier.class, notifier, true);
TestingUtil.replaceComponent(cache, ClusterCacheNotifier.class, notifier, true);
}
}
// TODO: commented out until local listners support includeCurrentState
// public void testCreateAfterIterationBeganAndSegmentNotCompleteValueNonOwnerNotClustered()
// throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException, IOException {
// testIterationBeganAndSegmentNotComplete(new StateListenerNotClustered(), Operation.CREATE, false);
// }
public void testCreateAfterIterationBeganAndSegmentNotCompleteValueNonOwnerClustered()
throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException, IOException {
testIterationBeganAndSegmentNotComplete(new StateListenerClustered(), Operation.CREATE, false);
}
// TODO: commented out until local listners support includeCurrentState
// public void testCreateAfterIterationBeganAndSegmentNotCompleteValueOwnerNotClustered()
// throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException, IOException {
// testIterationBeganAndSegmentNotComplete(new StateListenerNotClustered(), Operation.CREATE, true);
// }
public void testCreateAfterIterationBeganAndSegmentNotCompleteValueOwnerClustered()
throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException, IOException {
testIterationBeganAndSegmentNotComplete(new StateListenerClustered(), Operation.CREATE, true);
}
// TODO: commented out until local listners support includeCurrentState
// public void testModificationAfterIterationBeganAndSegmentNotCompleteValueNonOwnerNotClustered()
// throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException, IOException {
// testIterationBeganAndSegmentNotComplete(new StateListenerNotClustered(), Operation.PUT, false);
// }
public void testModificationAfterIterationBeganAndSegmentNotCompleteValueNonOwnerClustered()
throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException, IOException {
testIterationBeganAndSegmentNotComplete(new StateListenerClustered(), Operation.PUT, false);
}
// TODO: commented out until local listners support includeCurrentState
// public void testModificationAfterIterationBeganAndSegmentNotCompleteValueOwnerNotClustered()
// throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException, IOException {
// testIterationBeganAndSegmentNotComplete(new StateListenerNotClustered(), Operation.PUT, true);
// }
public void testModificationAfterIterationBeganAndSegmentNotCompleteValueOwnerClustered()
throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException, IOException {
testIterationBeganAndSegmentNotComplete(new StateListenerClustered(), Operation.PUT, true);
}
// TODO: commented out until local listners support includeCurrentState
// public void testRemoveAfterIterationBeganAndSegmentNotCompleteValueNonOwnerNotClustered()
// throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException, IOException {
// testIterationBeganAndSegmentNotComplete(new StateListenerNotClustered(), Operation.REMOVE, false);
// }
public void testRemoveAfterIterationBeganAndSegmentNotCompleteValueNonOwnerClustered()
throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException, IOException {
testIterationBeganAndSegmentNotComplete(new StateListenerClustered(), Operation.REMOVE, false);
}
// TODO: commented out until local listners support includeCurrentState
// public void testRemoveAfterIterationBeganAndSegmentNotCompleteValueOwnerNotClustered()
// throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException, IOException {
// testIterationBeganAndSegmentNotComplete(new StateListenerNotClustered(), Operation.REMOVE, true);
// }
public void testRemoveAfterIterationBeganAndSegmentNotCompleteValueOwnerClustered()
throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException, IOException {
testIterationBeganAndSegmentNotComplete(new StateListenerClustered(), Operation.REMOVE, true);
}
private boolean isClustered(StateListener listener) {
return listener.getClass().getAnnotation(Listener.class).clustered();
}
protected static abstract class StateListener<K, V> {
final List<CacheEntryEvent<K, V>> events = Collections.synchronizedList(new ArrayList<>());
@CacheEntryCreated
@CacheEntryModified
@CacheEntryRemoved
public void onCacheNotification(CacheEntryEvent<K, V> event) {
events.add(event);
}
}
@Listener(includeCurrentState = true, clustered = false)
private static class StateListenerNotClustered extends StateListener<String, String> {
}
@Listener(includeCurrentState = true, clustered = true)
private static class StateListenerClustered extends StateListener<String, String> {
}
protected ClusterCacheNotifier waitUntilClosingSegment(final Cache<?, ?> cache, final int segment, final CheckPoint checkPoint) {
ClusterCacheNotifier realNotifier = TestingUtil.extractComponent(cache, ClusterCacheNotifier.class);
ConcurrentMap<UUID, QueueingSegmentListener> listeningMap = new ConcurrentHashMap() {
@Override
public Object putIfAbsent(Object key, Object value) {
log.tracef("Adding segment listener %s : %s", key, value);
final Answer<Object> listenerAnswer = AdditionalAnswers.delegatesTo(value);
final AtomicBoolean wasLastSegment = new AtomicBoolean(false);
QueueingSegmentListener mockListener = mock(QueueingSegmentListener.class,
withSettings().defaultAnswer(listenerAnswer));
doAnswer(i -> {
Set<Integer> segments = (Set<Integer>) i.getArguments()[0];
log.tracef("Completed segments %s", segments);
if (segments.contains(segment)) {
wasLastSegment.set(true);
}
return listenerAnswer.answer(i);
}).when(mockListener).segmentCompleted(Mockito.anySet());
doAnswer(k -> {
log.tracef("Notified for key %s", k);
if (wasLastSegment.compareAndSet(true, false)) {
// Wait for main thread to sync up
checkPoint.trigger("pre_complete_segment_invoked");
// Now wait until main thread lets us through
checkPoint.awaitStrict("pre_complete_segment_released", 10, TimeUnit.SECONDS);
}
return listenerAnswer.answer(k);
}).when(mockListener).notifiedKey(Mockito.any());
return super.putIfAbsent(key, mockListener);
}
};
CacheNotifierImpl notifier = new CacheNotifierImpl(listeningMap);
TestingUtil.replaceComponent(cache, CacheNotifier.class, notifier, true);
TestingUtil.replaceComponent(cache, ClusterCacheNotifier.class, notifier, true);
return realNotifier;
}
// This is a helper method so that subsequent calls to the stream will return a mocked instance so we
// can keep track of invocations properly.
protected Stream mockStream(Stream realStream, StreamMocking mocking) {
Answer<Stream> defaultAnswer = i -> {
Stream stream = (Stream) i.getMethod().invoke(realStream, i.getArguments());
return mockStream(stream, mocking);
};
CacheStream mockStream = mock(CacheStream.class, withSettings().defaultAnswer(defaultAnswer));
mocking.additionalInformation(mockStream, realStream, mocking);
return mockStream;
}
private interface StreamMocking {
void additionalInformation(Stream mockStream, Stream realStream, StreamMocking ourselves);
}
protected AsyncInterceptorChain mockStream(final Cache<?, ?> cache, StreamMocking mocking) {
AsyncInterceptorChain chain = TestingUtil.extractComponent(cache, AsyncInterceptorChain.class);
AsyncInterceptorChain mockChain = spy(chain);
doAnswer(i -> {
CacheSet cacheSet = (CacheSet) i.callRealMethod();
CacheSet mockSet = spy(cacheSet);
when(mockSet.stream()).then(j -> {
CacheStream stream = (CacheStream) j.callRealMethod();
return mockStream(stream, mocking);
});
return mockSet;
}).when(mockChain).invoke(Mockito.any(InvocationContext.class),
(VisitableCommand) argThat(new IsInstanceOf(EntrySetCommand.class)));
TestingUtil.replaceComponent(cache, AsyncInterceptorChain.class, mockChain, true);
return chain;
}
}