blob: 57943ad88f98e2d7ce09ddfc9f7699efe712fe1e [file] [log] [blame]
Jonathan Hart584d2f32015-01-27 19:46:14 -08001/*
2 * Copyright 2015 Open Networking Laboratory
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Jonathan Hart77bdd262015-02-03 09:07:48 -080016package org.onosproject.store.ecmap;
Jonathan Hart584d2f32015-01-27 19:46:14 -080017
18import com.google.common.collect.ComparisonChain;
Madan Jampani3d76c942015-06-29 23:37:10 -070019import com.google.common.collect.ImmutableList;
Brian O'Connor5eb77c82015-03-02 18:09:39 -080020import com.google.common.collect.ImmutableSet;
Madan Jampanib28e4ad2015-02-19 12:31:37 -080021import com.google.common.util.concurrent.MoreExecutors;
Madan Jampani3e033bd2015-04-08 13:03:49 -070022
Jonathan Hart584d2f32015-01-27 19:46:14 -080023import org.junit.After;
24import org.junit.Before;
25import org.junit.Test;
26import org.onlab.packet.IpAddress;
27import org.onlab.util.KryoNamespace;
28import org.onosproject.cluster.ClusterService;
29import org.onosproject.cluster.ControllerNode;
30import org.onosproject.cluster.DefaultControllerNode;
31import org.onosproject.cluster.NodeId;
Madan Jampani2bfa94c2015-04-11 05:03:49 -070032import org.onosproject.event.AbstractEvent;
Jonathan Hart584d2f32015-01-27 19:46:14 -080033import org.onosproject.store.Timestamp;
34import org.onosproject.store.cluster.messaging.ClusterCommunicationService;
Jonathan Hart584d2f32015-01-27 19:46:14 -080035import org.onosproject.store.cluster.messaging.ClusterMessageHandler;
36import org.onosproject.store.cluster.messaging.MessageSubject;
Madan Jampani3e033bd2015-04-08 13:03:49 -070037import org.onosproject.store.impl.LogicalTimestamp;
Jonathan Hart63939a32015-05-08 11:57:03 -070038import org.onosproject.store.service.WallClockTimestamp;
Jonathan Hart584d2f32015-01-27 19:46:14 -080039import org.onosproject.store.serializers.KryoNamespaces;
40import org.onosproject.store.serializers.KryoSerializer;
Jonathan Hart6ec029a2015-03-24 17:12:35 -070041import org.onosproject.store.service.EventuallyConsistentMap;
42import org.onosproject.store.service.EventuallyConsistentMapEvent;
43import org.onosproject.store.service.EventuallyConsistentMapListener;
Jonathan Hart584d2f32015-01-27 19:46:14 -080044
Jonathan Hart584d2f32015-01-27 19:46:14 -080045import java.util.ArrayList;
Madan Jampani3d76c942015-06-29 23:37:10 -070046import java.util.Collection;
Jonathan Hart584d2f32015-01-27 19:46:14 -080047import java.util.HashMap;
48import java.util.HashSet;
Madan Jampani2bfa94c2015-04-11 05:03:49 -070049import java.util.List;
Jonathan Hart584d2f32015-01-27 19:46:14 -080050import java.util.Map;
51import java.util.Objects;
Madan Jampani3d76c942015-06-29 23:37:10 -070052import java.util.Optional;
Jonathan Hart584d2f32015-01-27 19:46:14 -080053import java.util.Set;
Madan Jampani2bfa94c2015-04-11 05:03:49 -070054import java.util.concurrent.CompletableFuture;
Jonathan Hart584d2f32015-01-27 19:46:14 -080055import java.util.concurrent.CountDownLatch;
Madan Jampaniec5ae342015-04-13 15:43:10 -070056import java.util.concurrent.Executor;
Madan Jampani2af244a2015-02-22 13:12:01 -080057import java.util.concurrent.ExecutorService;
Jonathan Hart584d2f32015-01-27 19:46:14 -080058import java.util.concurrent.TimeUnit;
59import java.util.concurrent.atomic.AtomicLong;
Madan Jampani2bfa94c2015-04-11 05:03:49 -070060import java.util.function.Consumer;
61import java.util.function.Function;
Jonathan Hart584d2f32015-01-27 19:46:14 -080062
63import static com.google.common.base.Preconditions.checkArgument;
64import static junit.framework.TestCase.assertFalse;
65import static org.easymock.EasyMock.*;
Brian O'Connor5eb77c82015-03-02 18:09:39 -080066import static org.junit.Assert.*;
Jonathan Hart584d2f32015-01-27 19:46:14 -080067
68/**
69 * Unit tests for EventuallyConsistentMapImpl.
70 */
71public class EventuallyConsistentMapImplTest {
72
73 private EventuallyConsistentMap<String, String> ecMap;
74
75 private ClusterService clusterService;
76 private ClusterCommunicationService clusterCommunicator;
Jonathan Hart5ec32ba2015-02-05 13:33:58 -080077 private SequentialClockService<String, String> clockService;
Jonathan Hart584d2f32015-01-27 19:46:14 -080078
79 private static final String MAP_NAME = "test";
Brian O'Connoreeaea2c2015-03-05 16:24:34 -080080 private static final MessageSubject UPDATE_MESSAGE_SUBJECT
Jonathan Hart584d2f32015-01-27 19:46:14 -080081 = new MessageSubject("ecm-" + MAP_NAME + "-update");
Jonathan Hart584d2f32015-01-27 19:46:14 -080082 private static final MessageSubject ANTI_ENTROPY_MESSAGE_SUBJECT
83 = new MessageSubject("ecm-" + MAP_NAME + "-anti-entropy");
84
85 private static final String KEY1 = "one";
86 private static final String KEY2 = "two";
87 private static final String VALUE1 = "oneValue";
88 private static final String VALUE2 = "twoValue";
89
90 private final ControllerNode self =
91 new DefaultControllerNode(new NodeId("local"), IpAddress.valueOf(1));
92
Madan Jampani3d76c942015-06-29 23:37:10 -070093 private Consumer<Collection<UpdateEntry<String, String>>> updateHandler;
94 private Consumer<AntiEntropyAdvertisement<String>> antiEntropyHandler;
Jonathan Hart584d2f32015-01-27 19:46:14 -080095
96 /*
97 * Serialization is a bit tricky here. We need to serialize in the tests
98 * to set the expectations, which will use this serializer here, but the
99 * EventuallyConsistentMap will use its own internal serializer. This means
100 * this serializer must be set up exactly the same as map's internal
101 * serializer.
102 */
103 private static final KryoSerializer SERIALIZER = new KryoSerializer() {
104 @Override
105 protected void setupKryoPool() {
106 serializerPool = KryoNamespace.newBuilder()
107 // Classes we give to the map
108 .register(KryoNamespaces.API)
109 .register(TestTimestamp.class)
110 // Below is the classes that the map internally registers
Madan Jampani3e033bd2015-04-08 13:03:49 -0700111 .register(LogicalTimestamp.class)
Jonathan Hart584d2f32015-01-27 19:46:14 -0800112 .register(WallClockTimestamp.class)
Jonathan Hart584d2f32015-01-27 19:46:14 -0800113 .register(ArrayList.class)
Jonathan Hart584d2f32015-01-27 19:46:14 -0800114 .register(AntiEntropyAdvertisement.class)
115 .register(HashMap.class)
Madan Jampani3d76c942015-06-29 23:37:10 -0700116 .register(Optional.class)
Jonathan Hart584d2f32015-01-27 19:46:14 -0800117 .build();
118 }
119 };
120
121 @Before
122 public void setUp() throws Exception {
123 clusterService = createMock(ClusterService.class);
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800124 expect(clusterService.getLocalNode()).andReturn(self).anyTimes();
125 expect(clusterService.getNodes()).andReturn(ImmutableSet.of(self)).anyTimes();
Jonathan Hart584d2f32015-01-27 19:46:14 -0800126 replay(clusterService);
127
128 clusterCommunicator = createMock(ClusterCommunicationService.class);
129
130 // Add expectation for adding cluster message subscribers which
131 // delegate to our ClusterCommunicationService implementation. This
132 // allows us to get a reference to the map's internal cluster message
133 // handlers so we can induce events coming in from a peer.
Madan Jampani3d76c942015-06-29 23:37:10 -0700134 clusterCommunicator.<String>addSubscriber(anyObject(MessageSubject.class),
135 anyObject(Function.class), anyObject(Consumer.class), anyObject(Executor.class));
136 expectLastCall().andDelegateTo(new TestClusterCommunicationService()).times(2);
Jonathan Hart584d2f32015-01-27 19:46:14 -0800137
138 replay(clusterCommunicator);
139
140 clockService = new SequentialClockService<>();
141
142 KryoNamespace.Builder serializer = KryoNamespace.newBuilder()
143 .register(KryoNamespaces.API)
144 .register(TestTimestamp.class);
145
Madan Jampani175e8fd2015-05-20 14:10:45 -0700146 ecMap = new EventuallyConsistentMapBuilderImpl<String, String>(
Jonathan Hart6ec029a2015-03-24 17:12:35 -0700147 clusterService, clusterCommunicator)
148 .withName(MAP_NAME)
149 .withSerializer(serializer)
Madan Jampanibcf1a482015-06-24 19:05:56 -0700150 .withTimestampProvider((k, v) -> clockService.getTimestamp(k, v))
Jonathan Hart6ec029a2015-03-24 17:12:35 -0700151 .withCommunicationExecutor(MoreExecutors.newDirectExecutorService())
152 .build();
Jonathan Hart584d2f32015-01-27 19:46:14 -0800153
154 // Reset ready for tests to add their own expectations
155 reset(clusterCommunicator);
156 }
157
158 @After
159 public void tearDown() {
160 reset(clusterCommunicator);
161 ecMap.destroy();
162 }
163
Ray Milkey8dc82082015-02-20 16:22:38 -0800164 @SuppressWarnings("unchecked")
165 private EventuallyConsistentMapListener<String, String> getListener() {
166 return createMock(EventuallyConsistentMapListener.class);
167 }
168
Jonathan Hart584d2f32015-01-27 19:46:14 -0800169 @Test
170 public void testSize() throws Exception {
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800171 expectPeerMessage(clusterCommunicator);
Jonathan Hart584d2f32015-01-27 19:46:14 -0800172
173 assertEquals(0, ecMap.size());
174 ecMap.put(KEY1, VALUE1);
175 assertEquals(1, ecMap.size());
176 ecMap.put(KEY1, VALUE2);
177 assertEquals(1, ecMap.size());
178 ecMap.put(KEY2, VALUE2);
179 assertEquals(2, ecMap.size());
180 for (int i = 0; i < 10; i++) {
181 ecMap.put("" + i, "" + i);
182 }
183 assertEquals(12, ecMap.size());
184 ecMap.remove(KEY1);
185 assertEquals(11, ecMap.size());
186 ecMap.remove(KEY1);
187 assertEquals(11, ecMap.size());
188 }
189
190 @Test
191 public void testIsEmpty() throws Exception {
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800192 expectPeerMessage(clusterCommunicator);
Jonathan Hart584d2f32015-01-27 19:46:14 -0800193
194 assertTrue(ecMap.isEmpty());
195 ecMap.put(KEY1, VALUE1);
196 assertFalse(ecMap.isEmpty());
197 ecMap.remove(KEY1);
198 assertTrue(ecMap.isEmpty());
199 }
200
201 @Test
202 public void testContainsKey() throws Exception {
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800203 expectPeerMessage(clusterCommunicator);
Jonathan Hart584d2f32015-01-27 19:46:14 -0800204
205 assertFalse(ecMap.containsKey(KEY1));
206 ecMap.put(KEY1, VALUE1);
207 assertTrue(ecMap.containsKey(KEY1));
208 assertFalse(ecMap.containsKey(KEY2));
209 ecMap.remove(KEY1);
210 assertFalse(ecMap.containsKey(KEY1));
211 }
212
213 @Test
214 public void testContainsValue() throws Exception {
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800215 expectPeerMessage(clusterCommunicator);
Jonathan Hart584d2f32015-01-27 19:46:14 -0800216
217 assertFalse(ecMap.containsValue(VALUE1));
218 ecMap.put(KEY1, VALUE1);
219 assertTrue(ecMap.containsValue(VALUE1));
220 assertFalse(ecMap.containsValue(VALUE2));
221 ecMap.put(KEY1, VALUE2);
222 assertFalse(ecMap.containsValue(VALUE1));
223 assertTrue(ecMap.containsValue(VALUE2));
224 ecMap.remove(KEY1);
225 assertFalse(ecMap.containsValue(VALUE2));
226 }
227
228 @Test
229 public void testGet() throws Exception {
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800230 expectPeerMessage(clusterCommunicator);
Jonathan Hart584d2f32015-01-27 19:46:14 -0800231
232 CountDownLatch latch;
233
234 // Local put
235 assertNull(ecMap.get(KEY1));
236 ecMap.put(KEY1, VALUE1);
237 assertEquals(VALUE1, ecMap.get(KEY1));
238
239 // Remote put
Madan Jampani3d76c942015-06-29 23:37:10 -0700240 List<UpdateEntry<String, String>> message
241 = ImmutableList.of(generatePutMessage(KEY2, VALUE2, clockService.getTimestamp(KEY2, VALUE2)));
Jonathan Hart584d2f32015-01-27 19:46:14 -0800242
243 // Create a latch so we know when the put operation has finished
244 latch = new CountDownLatch(1);
245 ecMap.addListener(new TestListener(latch));
246
247 assertNull(ecMap.get(KEY2));
Madan Jampani3d76c942015-06-29 23:37:10 -0700248 updateHandler.accept(message);
Jonathan Hart584d2f32015-01-27 19:46:14 -0800249 assertTrue("External listener never got notified of internal event",
250 latch.await(100, TimeUnit.MILLISECONDS));
251 assertEquals(VALUE2, ecMap.get(KEY2));
252
253 // Local remove
254 ecMap.remove(KEY2);
255 assertNull(ecMap.get(KEY2));
256
257 // Remote remove
Madan Jampani3d76c942015-06-29 23:37:10 -0700258 message = ImmutableList.of(generateRemoveMessage(KEY1, clockService.getTimestamp(KEY1, VALUE1)));
Jonathan Hart584d2f32015-01-27 19:46:14 -0800259
260 // Create a latch so we know when the remove operation has finished
261 latch = new CountDownLatch(1);
262 ecMap.addListener(new TestListener(latch));
263
Madan Jampani3d76c942015-06-29 23:37:10 -0700264 updateHandler.accept(message);
Jonathan Hart584d2f32015-01-27 19:46:14 -0800265 assertTrue("External listener never got notified of internal event",
266 latch.await(100, TimeUnit.MILLISECONDS));
267 assertNull(ecMap.get(KEY1));
268 }
269
270 @Test
271 public void testPut() throws Exception {
272 // Set up expectations of external events to be sent to listeners during
273 // the test. These don't use timestamps so we can set them all up at once.
274 EventuallyConsistentMapListener<String, String> listener
Ray Milkey8dc82082015-02-20 16:22:38 -0800275 = getListener();
Jonathan Hart584d2f32015-01-27 19:46:14 -0800276 listener.event(new EventuallyConsistentMapEvent<>(
277 EventuallyConsistentMapEvent.Type.PUT, KEY1, VALUE1));
278 listener.event(new EventuallyConsistentMapEvent<>(
279 EventuallyConsistentMapEvent.Type.PUT, KEY1, VALUE2));
280 replay(listener);
281
282 ecMap.addListener(listener);
283
284 // Set up expected internal message to be broadcast to peers on first put
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800285 expectSpecificMulticastMessage(generatePutMessage(KEY1, VALUE1, clockService
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700286 .peekAtNextTimestamp()), UPDATE_MESSAGE_SUBJECT, clusterCommunicator);
Jonathan Hart584d2f32015-01-27 19:46:14 -0800287
288 // Put first value
289 assertNull(ecMap.get(KEY1));
290 ecMap.put(KEY1, VALUE1);
291 assertEquals(VALUE1, ecMap.get(KEY1));
292
293 verify(clusterCommunicator);
294
295 // Set up expected internal message to be broadcast to peers on second put
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800296 expectSpecificMulticastMessage(generatePutMessage(
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700297 KEY1, VALUE2, clockService.peekAtNextTimestamp()), UPDATE_MESSAGE_SUBJECT, clusterCommunicator);
Jonathan Hart584d2f32015-01-27 19:46:14 -0800298
299 // Update same key to a new value
300 ecMap.put(KEY1, VALUE2);
301 assertEquals(VALUE2, ecMap.get(KEY1));
302
303 verify(clusterCommunicator);
304
305 // Do a put with a older timestamp than the value already there.
306 // The map data should not be changed and no notifications should be sent.
307 reset(clusterCommunicator);
308 replay(clusterCommunicator);
309
310 clockService.turnBackTime();
311 ecMap.put(KEY1, VALUE1);
312 // Value should not have changed.
313 assertEquals(VALUE2, ecMap.get(KEY1));
314
315 verify(clusterCommunicator);
316
317 // Check that our listener received the correct events during the test
318 verify(listener);
319 }
320
321 @Test
322 public void testRemove() throws Exception {
323 // Set up expectations of external events to be sent to listeners during
324 // the test. These don't use timestamps so we can set them all up at once.
325 EventuallyConsistentMapListener<String, String> listener
Ray Milkey8dc82082015-02-20 16:22:38 -0800326 = getListener();
Jonathan Hart584d2f32015-01-27 19:46:14 -0800327 listener.event(new EventuallyConsistentMapEvent<>(
Madan Jampani43e9c9c2015-06-26 14:16:46 -0700328 EventuallyConsistentMapEvent.Type.REMOVE, KEY1, VALUE1));
329 listener.event(new EventuallyConsistentMapEvent<>(
Jonathan Hart584d2f32015-01-27 19:46:14 -0800330 EventuallyConsistentMapEvent.Type.REMOVE, KEY1, null));
Jonathan Hart584d2f32015-01-27 19:46:14 -0800331 listener.event(new EventuallyConsistentMapEvent<>(
332 EventuallyConsistentMapEvent.Type.PUT, KEY1, VALUE1));
333 listener.event(new EventuallyConsistentMapEvent<>(
334 EventuallyConsistentMapEvent.Type.PUT, KEY2, VALUE2));
335 replay(listener);
336
337 ecMap.addListener(listener);
338
339 // Put in an initial value
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800340 expectPeerMessage(clusterCommunicator);
Jonathan Hart584d2f32015-01-27 19:46:14 -0800341 ecMap.put(KEY1, VALUE1);
342 assertEquals(VALUE1, ecMap.get(KEY1));
343
344 // Remove the value and check the correct internal cluster messages
345 // are sent
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800346 expectSpecificMulticastMessage(generateRemoveMessage(KEY1, clockService.peekAtNextTimestamp()),
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700347 UPDATE_MESSAGE_SUBJECT, clusterCommunicator);
Jonathan Hart584d2f32015-01-27 19:46:14 -0800348
349 ecMap.remove(KEY1);
350 assertNull(ecMap.get(KEY1));
351
352 verify(clusterCommunicator);
353
354 // Remove the same value again. Even though the value is no longer in
355 // the map, we expect that the tombstone is updated and another remove
356 // event is sent to the cluster and external listeners.
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800357 expectSpecificMulticastMessage(generateRemoveMessage(KEY1, clockService.peekAtNextTimestamp()),
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700358 UPDATE_MESSAGE_SUBJECT, clusterCommunicator);
Jonathan Hart584d2f32015-01-27 19:46:14 -0800359
360 ecMap.remove(KEY1);
361 assertNull(ecMap.get(KEY1));
362
363 verify(clusterCommunicator);
364
365
366 // Put in a new value for us to try and remove
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800367 expectPeerMessage(clusterCommunicator);
Jonathan Hart584d2f32015-01-27 19:46:14 -0800368
369 ecMap.put(KEY2, VALUE2);
370
371 clockService.turnBackTime();
372
373 // Remove should have no effect, since it has an older timestamp than
374 // the put. Expect no notifications to be sent out
375 reset(clusterCommunicator);
376 replay(clusterCommunicator);
377
378 ecMap.remove(KEY2);
379
380 verify(clusterCommunicator);
381
382 // Check that our listener received the correct events during the test
383 verify(listener);
384 }
385
386 @Test
387 public void testPutAll() throws Exception {
388 // putAll() with an empty map is a no-op - no messages will be sent
389 reset(clusterCommunicator);
390 replay(clusterCommunicator);
391
392 ecMap.putAll(new HashMap<>());
393
394 verify(clusterCommunicator);
395
396 // Set up the listener with our expected events
397 EventuallyConsistentMapListener<String, String> listener
Ray Milkey8dc82082015-02-20 16:22:38 -0800398 = getListener();
Jonathan Hart584d2f32015-01-27 19:46:14 -0800399 listener.event(new EventuallyConsistentMapEvent<>(
400 EventuallyConsistentMapEvent.Type.PUT, KEY1, VALUE1));
401 listener.event(new EventuallyConsistentMapEvent<>(
402 EventuallyConsistentMapEvent.Type.PUT, KEY2, VALUE2));
403 replay(listener);
404
405 ecMap.addListener(listener);
406
407 // Expect a multi-update inter-instance message
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700408 expectSpecificBroadcastMessage(generatePutMessage(KEY1, VALUE1, KEY2, VALUE2), UPDATE_MESSAGE_SUBJECT,
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800409 clusterCommunicator);
Jonathan Hart584d2f32015-01-27 19:46:14 -0800410
411 Map<String, String> putAllValues = new HashMap<>();
412 putAllValues.put(KEY1, VALUE1);
413 putAllValues.put(KEY2, VALUE2);
414
415 // Put the values in the map
416 ecMap.putAll(putAllValues);
417
418 // Check the correct messages and events were sent
419 verify(clusterCommunicator);
420 verify(listener);
421 }
422
423 @Test
424 public void testClear() throws Exception {
425 EventuallyConsistentMapListener<String, String> listener
Ray Milkey8dc82082015-02-20 16:22:38 -0800426 = getListener();
Jonathan Hart584d2f32015-01-27 19:46:14 -0800427 listener.event(new EventuallyConsistentMapEvent<>(
Madan Jampani43e9c9c2015-06-26 14:16:46 -0700428 EventuallyConsistentMapEvent.Type.REMOVE, KEY1, VALUE1));
Jonathan Hart584d2f32015-01-27 19:46:14 -0800429 listener.event(new EventuallyConsistentMapEvent<>(
Madan Jampani43e9c9c2015-06-26 14:16:46 -0700430 EventuallyConsistentMapEvent.Type.REMOVE, KEY2, VALUE2));
Jonathan Hart584d2f32015-01-27 19:46:14 -0800431 replay(listener);
432
433 // clear() on an empty map is a no-op - no messages will be sent
434 reset(clusterCommunicator);
435 replay(clusterCommunicator);
436
437 assertTrue(ecMap.isEmpty());
438 ecMap.clear();
439 verify(clusterCommunicator);
440
441 // Put some items in the map
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800442 expectPeerMessage(clusterCommunicator);
Jonathan Hart584d2f32015-01-27 19:46:14 -0800443 ecMap.put(KEY1, VALUE1);
444 ecMap.put(KEY2, VALUE2);
445
446 ecMap.addListener(listener);
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700447 expectSpecificBroadcastMessage(generateRemoveMessage(KEY1, KEY2), UPDATE_MESSAGE_SUBJECT, clusterCommunicator);
Jonathan Hart584d2f32015-01-27 19:46:14 -0800448
449 ecMap.clear();
450
451 verify(clusterCommunicator);
452 verify(listener);
453 }
454
455 @Test
456 public void testKeySet() throws Exception {
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800457 expectPeerMessage(clusterCommunicator);
Jonathan Hart584d2f32015-01-27 19:46:14 -0800458
459 assertTrue(ecMap.keySet().isEmpty());
460
461 // Generate some keys
462 Set<String> keys = new HashSet<>();
463 for (int i = 1; i <= 10; i++) {
464 keys.add("" + i);
465 }
466
467 // Put each key in the map
468 keys.forEach(k -> ecMap.put(k, "value" + k));
469
470 // Check keySet() returns the correct value
471 assertEquals(keys, ecMap.keySet());
472
473 // Update the value for one of the keys
474 ecMap.put(keys.iterator().next(), "new-value");
475
476 // Check the key set is still the same
477 assertEquals(keys, ecMap.keySet());
478
479 // Remove a key
480 String removeKey = keys.iterator().next();
481 keys.remove(removeKey);
482 ecMap.remove(removeKey);
483
484 // Check the key set is still correct
485 assertEquals(keys, ecMap.keySet());
486 }
487
488 @Test
489 public void testValues() throws Exception {
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800490 expectPeerMessage(clusterCommunicator);
Jonathan Hart584d2f32015-01-27 19:46:14 -0800491
492 assertTrue(ecMap.values().isEmpty());
493
494 // Generate some values
495 Map<String, String> expectedValues = new HashMap<>();
496 for (int i = 1; i <= 10; i++) {
497 expectedValues.put("" + i, "value" + i);
498 }
499
500 // Add them into the map
501 expectedValues.entrySet().forEach(e -> ecMap.put(e.getKey(), e.getValue()));
502
503 // Check the values collection is correct
504 assertEquals(expectedValues.values().size(), ecMap.values().size());
505 expectedValues.values().forEach(v -> assertTrue(ecMap.values().contains(v)));
506
507 // Update the value for one of the keys
508 Map.Entry<String, String> first = expectedValues.entrySet().iterator().next();
509 expectedValues.put(first.getKey(), "new-value");
510 ecMap.put(first.getKey(), "new-value");
511
512 // Check the values collection is still correct
513 assertEquals(expectedValues.values().size(), ecMap.values().size());
514 expectedValues.values().forEach(v -> assertTrue(ecMap.values().contains(v)));
515
516 // Remove a key
517 String removeKey = expectedValues.keySet().iterator().next();
518 expectedValues.remove(removeKey);
519 ecMap.remove(removeKey);
520
521 // Check the values collection is still correct
522 assertEquals(expectedValues.values().size(), ecMap.values().size());
523 expectedValues.values().forEach(v -> assertTrue(ecMap.values().contains(v)));
524 }
525
526 @Test
527 public void testEntrySet() throws Exception {
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800528 expectPeerMessage(clusterCommunicator);
Jonathan Hart584d2f32015-01-27 19:46:14 -0800529
530 assertTrue(ecMap.entrySet().isEmpty());
531
532 // Generate some values
533 Map<String, String> expectedValues = new HashMap<>();
534 for (int i = 1; i <= 10; i++) {
535 expectedValues.put("" + i, "value" + i);
536 }
537
538 // Add them into the map
539 expectedValues.entrySet().forEach(e -> ecMap.put(e.getKey(), e.getValue()));
540
541 // Check the entry set is correct
542 assertTrue(entrySetsAreEqual(expectedValues, ecMap.entrySet()));
543
544 // Update the value for one of the keys
545 Map.Entry<String, String> first = expectedValues.entrySet().iterator().next();
546 expectedValues.put(first.getKey(), "new-value");
547 ecMap.put(first.getKey(), "new-value");
548
549 // Check the entry set is still correct
550 assertTrue(entrySetsAreEqual(expectedValues, ecMap.entrySet()));
551
552 // Remove a key
553 String removeKey = expectedValues.keySet().iterator().next();
554 expectedValues.remove(removeKey);
555 ecMap.remove(removeKey);
556
557 // Check the entry set is still correct
558 assertTrue(entrySetsAreEqual(expectedValues, ecMap.entrySet()));
559 }
560
561 private static boolean entrySetsAreEqual(Map<String, String> expectedMap, Set<Map.Entry<String, String>> actual) {
562 if (expectedMap.entrySet().size() != actual.size()) {
563 return false;
564 }
565
566 for (Map.Entry<String, String> e : actual) {
567 if (!expectedMap.containsKey(e.getKey())) {
568 return false;
569 }
570 if (!Objects.equals(expectedMap.get(e.getKey()), e.getValue())) {
571 return false;
572 }
573 }
574 return true;
575 }
576
577 @Test
578 public void testDestroy() throws Exception {
Brian O'Connoreeaea2c2015-03-05 16:24:34 -0800579 clusterCommunicator.removeSubscriber(UPDATE_MESSAGE_SUBJECT);
Jonathan Hart584d2f32015-01-27 19:46:14 -0800580 clusterCommunicator.removeSubscriber(ANTI_ENTROPY_MESSAGE_SUBJECT);
581
582 replay(clusterCommunicator);
583
584 ecMap.destroy();
585
586 verify(clusterCommunicator);
587
588 try {
589 ecMap.get(KEY1);
590 fail("get after destroy should throw exception");
591 } catch (IllegalStateException e) {
592 assertTrue(true);
593 }
594
595 try {
596 ecMap.put(KEY1, VALUE1);
597 fail("put after destroy should throw exception");
598 } catch (IllegalStateException e) {
599 assertTrue(true);
600 }
601 }
602
Madan Jampani3d76c942015-06-29 23:37:10 -0700603 private UpdateEntry<String, String> generatePutMessage(String key, String value, Timestamp timestamp) {
604 return new UpdateEntry<>(key, new MapValue<>(value, timestamp));
Jonathan Hart584d2f32015-01-27 19:46:14 -0800605 }
606
Madan Jampani3d76c942015-06-29 23:37:10 -0700607 private List<UpdateEntry<String, String>> generatePutMessage(
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700608 String key1, String value1, String key2, String value2) {
Madan Jampani3d76c942015-06-29 23:37:10 -0700609 List<UpdateEntry<String, String>> list = new ArrayList<>();
Jonathan Hart584d2f32015-01-27 19:46:14 -0800610
611 Timestamp timestamp1 = clockService.peek(1);
612 Timestamp timestamp2 = clockService.peek(2);
613
Madan Jampani3d76c942015-06-29 23:37:10 -0700614 list.add(generatePutMessage(key1, value1, timestamp1));
615 list.add(generatePutMessage(key2, value2, timestamp2));
Jonathan Hart584d2f32015-01-27 19:46:14 -0800616
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700617 return list;
Jonathan Hart584d2f32015-01-27 19:46:14 -0800618 }
619
Madan Jampani3d76c942015-06-29 23:37:10 -0700620 private UpdateEntry<String, String> generateRemoveMessage(String key, Timestamp timestamp) {
621 return new UpdateEntry<>(key, new MapValue<>(null, timestamp));
Jonathan Hart584d2f32015-01-27 19:46:14 -0800622 }
623
Madan Jampani3d76c942015-06-29 23:37:10 -0700624 private List<UpdateEntry<String, String>> generateRemoveMessage(String key1, String key2) {
625 List<UpdateEntry<String, String>> list = new ArrayList<>();
Jonathan Hart584d2f32015-01-27 19:46:14 -0800626
627 Timestamp timestamp1 = clockService.peek(1);
628 Timestamp timestamp2 = clockService.peek(2);
629
Madan Jampani3d76c942015-06-29 23:37:10 -0700630 list.add(generateRemoveMessage(key1, timestamp1));
631 list.add(generateRemoveMessage(key2, timestamp2));
Jonathan Hart584d2f32015-01-27 19:46:14 -0800632
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700633 return list;
Jonathan Hart584d2f32015-01-27 19:46:14 -0800634 }
635
636 /**
637 * Sets up a mock ClusterCommunicationService to expect a specific cluster
638 * message to be broadcast to the cluster.
639 *
640 * @param m message we expect to be sent
641 * @param clusterCommunicator a mock ClusterCommunicationService to set up
642 */
Brian O'Connoreeaea2c2015-03-05 16:24:34 -0800643 //FIXME rename
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700644 private static <T> void expectSpecificBroadcastMessage(
645 T message,
646 MessageSubject subject,
647 ClusterCommunicationService clusterCommunicator) {
Jonathan Hart584d2f32015-01-27 19:46:14 -0800648 reset(clusterCommunicator);
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700649 clusterCommunicator.<T>multicast(eq(message), eq(subject), anyObject(Function.class), anyObject(Set.class));
650 expectLastCall().anyTimes();
Jonathan Hart584d2f32015-01-27 19:46:14 -0800651 replay(clusterCommunicator);
652 }
653
654 /**
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800655 * Sets up a mock ClusterCommunicationService to expect a specific cluster
656 * message to be multicast to the cluster.
657 *
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700658 * @param message message we expect to be sent
659 * @param subject subject we expect to be sent to
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800660 * @param clusterCommunicator a mock ClusterCommunicationService to set up
661 */
Brian O'Connoreeaea2c2015-03-05 16:24:34 -0800662 //FIXME rename
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700663 private static <T> void expectSpecificMulticastMessage(T message, MessageSubject subject,
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800664 ClusterCommunicationService clusterCommunicator) {
665 reset(clusterCommunicator);
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700666 clusterCommunicator.<T>multicast(eq(message), eq(subject), anyObject(Function.class), anyObject(Set.class));
667 expectLastCall().anyTimes();
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800668 replay(clusterCommunicator);
669 }
670
671
672 /**
673 * Sets up a mock ClusterCommunicationService to expect a multicast cluster message
Jonathan Hart584d2f32015-01-27 19:46:14 -0800674 * that is sent to it. This is useful for unit tests where we aren't
675 * interested in testing the messaging component.
676 *
677 * @param clusterCommunicator a mock ClusterCommunicationService to set up
678 */
Brian O'Connoreeaea2c2015-03-05 16:24:34 -0800679 //FIXME rename
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700680 private <T> void expectPeerMessage(ClusterCommunicationService clusterCommunicator) {
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800681 reset(clusterCommunicator);
Brian O'Connoreeaea2c2015-03-05 16:24:34 -0800682// expect(clusterCommunicator.multicast(anyObject(ClusterMessage.class),
683// anyObject(Iterable.class)))
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700684 expect(clusterCommunicator.<T>unicast(
685 anyObject(),
686 anyObject(MessageSubject.class),
687 anyObject(Function.class),
688 anyObject(NodeId.class)))
Madan Jampani175e8fd2015-05-20 14:10:45 -0700689 .andReturn(CompletableFuture.completedFuture(null))
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800690 .anyTimes();
691 replay(clusterCommunicator);
692 }
693
694 /**
695 * Sets up a mock ClusterCommunicationService to expect a broadcast cluster message
696 * that is sent to it. This is useful for unit tests where we aren't
697 * interested in testing the messaging component.
698 *
699 * @param clusterCommunicator a mock ClusterCommunicationService to set up
700 */
701 private void expectBroadcastMessage(ClusterCommunicationService clusterCommunicator) {
Jonathan Hart584d2f32015-01-27 19:46:14 -0800702 reset(clusterCommunicator);
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700703 clusterCommunicator.<AbstractEvent>multicast(
704 anyObject(AbstractEvent.class),
705 anyObject(MessageSubject.class),
706 anyObject(Function.class),
707 anyObject(Set.class));
708 expectLastCall().anyTimes();
Jonathan Hart584d2f32015-01-27 19:46:14 -0800709 replay(clusterCommunicator);
710 }
711
712 /**
713 * ClusterCommunicationService implementation that the map's addSubscriber
714 * call will delegate to. This means we can get a reference to the
715 * internal cluster message handler used by the map, so that we can simulate
716 * events coming in from other instances.
717 */
718 private final class TestClusterCommunicationService
719 implements ClusterCommunicationService {
720
721 @Override
Madan Jampani2af244a2015-02-22 13:12:01 -0800722 public void addSubscriber(MessageSubject subject,
723 ClusterMessageHandler subscriber,
724 ExecutorService executor) {
Madan Jampani2af244a2015-02-22 13:12:01 -0800725 }
726
727 @Override
Jonathan Hart584d2f32015-01-27 19:46:14 -0800728 public void removeSubscriber(MessageSubject subject) {}
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700729
730 @Override
731 public <M> void broadcast(M message, MessageSubject subject,
732 Function<M, byte[]> encoder) {
733 }
734
735 @Override
736 public <M> void broadcastIncludeSelf(M message,
737 MessageSubject subject, Function<M, byte[]> encoder) {
738 }
739
740 @Override
Madan Jampani175e8fd2015-05-20 14:10:45 -0700741 public <M> CompletableFuture<Void> unicast(M message, MessageSubject subject,
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700742 Function<M, byte[]> encoder, NodeId toNodeId) {
Madan Jampani175e8fd2015-05-20 14:10:45 -0700743 return null;
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700744 }
745
746 @Override
747 public <M> void multicast(M message, MessageSubject subject,
748 Function<M, byte[]> encoder, Set<NodeId> nodes) {
749 }
750
751 @Override
752 public <M, R> CompletableFuture<R> sendAndReceive(M message,
753 MessageSubject subject, Function<M, byte[]> encoder,
754 Function<byte[], R> decoder, NodeId toNodeId) {
755 return null;
756 }
757
758 @Override
759 public <M, R> void addSubscriber(MessageSubject subject,
760 Function<byte[], M> decoder, Function<M, R> handler,
Madan Jampaniec5ae342015-04-13 15:43:10 -0700761 Function<R, byte[]> encoder, Executor executor) {
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700762 }
763
764 @Override
Madan Jampani27b69c62015-05-15 15:49:02 -0700765 public <M, R> void addSubscriber(MessageSubject subject,
766 Function<byte[], M> decoder, Function<M, CompletableFuture<R>> handler,
767 Function<R, byte[]> encoder) {
768 }
769
770 @Override
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700771 public <M> void addSubscriber(MessageSubject subject,
772 Function<byte[], M> decoder, Consumer<M> handler,
Madan Jampaniec5ae342015-04-13 15:43:10 -0700773 Executor executor) {
Madan Jampani3d76c942015-06-29 23:37:10 -0700774 if (subject.equals(UPDATE_MESSAGE_SUBJECT)) {
775 updateHandler = (Consumer<Collection<UpdateEntry<String, String>>>) handler;
776 } else if (subject.equals(ANTI_ENTROPY_MESSAGE_SUBJECT)) {
777 antiEntropyHandler = (Consumer<AntiEntropyAdvertisement<String>>) handler;
778 } else {
779 throw new RuntimeException("Unexpected message subject " + subject.toString());
780 }
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700781 }
Jonathan Hart584d2f32015-01-27 19:46:14 -0800782 }
783
784 /**
785 * ClockService implementation that gives out timestamps based on a
786 * sequential counter. This clock service enables more control over the
787 * timestamps that are given out, including being able to "turn back time"
788 * to give out timestamps from the past.
789 *
790 * @param <T> Type that the clock service will give out timestamps for
Jonathan Hart5ec32ba2015-02-05 13:33:58 -0800791 * @param <U> Second type that the clock service will give out values for
Jonathan Hart584d2f32015-01-27 19:46:14 -0800792 */
Madan Jampanibcf1a482015-06-24 19:05:56 -0700793 private class SequentialClockService<T, U> {
Jonathan Hart584d2f32015-01-27 19:46:14 -0800794
795 private static final long INITIAL_VALUE = 1;
796 private final AtomicLong counter = new AtomicLong(INITIAL_VALUE);
797
Jonathan Hart5ec32ba2015-02-05 13:33:58 -0800798 public Timestamp getTimestamp(T object, U object2) {
Jonathan Hart584d2f32015-01-27 19:46:14 -0800799 return new TestTimestamp(counter.getAndIncrement());
800 }
801
802 /**
803 * Returns what the next timestamp will be without consuming the
804 * timestamp. This allows test code to set expectations correctly while
805 * still allowing the CUT to get the same timestamp.
806 *
807 * @return timestamp equal to the timestamp that will be returned by the
Jonathan Hart5ec32ba2015-02-05 13:33:58 -0800808 * next call to {@link #getTimestamp(T, U)}.
Jonathan Hart584d2f32015-01-27 19:46:14 -0800809 */
810 public Timestamp peekAtNextTimestamp() {
811 return peek(1);
812 }
813
814 /**
815 * Returns the ith timestamp to be given out in the future without
816 * consuming the timestamp. For example, i=1 returns the next timestamp,
817 * i=2 returns the timestamp after that, and so on.
818 *
819 * @param i number of the timestamp to peek at
820 * @return the ith timestamp that will be given out
821 */
822 public Timestamp peek(int i) {
823 checkArgument(i > 0, "i must be a positive integer");
824
825 return new TestTimestamp(counter.get() + i - 1);
826 }
827
828 /**
829 * Turns the clock back two ticks, so the next call to getTimestamp will
830 * return an older timestamp than the previous call to getTimestamp.
831 */
832 public void turnBackTime() {
833 // Not atomic, but should be OK for these tests.
834 counter.decrementAndGet();
835 counter.decrementAndGet();
836 }
837
838 }
839
840 /**
841 * Timestamp implementation where the value of the timestamp can be
842 * specified explicitly at creation time.
843 */
844 private class TestTimestamp implements Timestamp {
845
846 private final long timestamp;
847
848 /**
849 * Creates a new timestamp that has the specified value.
850 *
851 * @param timestamp value of the timestamp
852 */
853 public TestTimestamp(long timestamp) {
854 this.timestamp = timestamp;
855 }
856
857 @Override
858 public int compareTo(Timestamp o) {
859 checkArgument(o instanceof TestTimestamp);
860 TestTimestamp otherTimestamp = (TestTimestamp) o;
861 return ComparisonChain.start()
862 .compare(this.timestamp, otherTimestamp.timestamp)
863 .result();
864 }
865 }
866
867 /**
868 * EventuallyConsistentMapListener implementation which triggers a latch
869 * when it receives an event.
870 */
871 private class TestListener implements EventuallyConsistentMapListener<String, String> {
872 private CountDownLatch latch;
873
874 /**
875 * Creates a new listener that will trigger the specified latch when it
876 * receives and event.
877 *
878 * @param latch the latch to trigger on events
879 */
880 public TestListener(CountDownLatch latch) {
881 this.latch = latch;
882 }
883
884 @Override
885 public void event(EventuallyConsistentMapEvent<String, String> event) {
886 latch.countDown();
887 }
888 }
889}