blob: 8ea08c2813e738c8e31e0b89b332e3eae9ac64fa [file] [log] [blame]
Jonathan Hartdb3af892015-01-26 13:19:07 -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 */
16package org.onosproject.store.impl;
17
Jonathan Hartaaa56572015-01-28 21:56:35 -080018import org.apache.commons.lang3.RandomUtils;
Jonathan Hartf9108232015-02-02 16:37:35 -080019import org.apache.commons.lang3.tuple.Pair;
Jonathan Hartdb3af892015-01-26 13:19:07 -080020import org.onlab.util.KryoNamespace;
21import org.onosproject.cluster.ClusterService;
Jonathan Hartaaa56572015-01-28 21:56:35 -080022import org.onosproject.cluster.ControllerNode;
Jonathan Hartdb3af892015-01-26 13:19:07 -080023import org.onosproject.cluster.NodeId;
24import org.onosproject.store.Timestamp;
25import org.onosproject.store.cluster.messaging.ClusterCommunicationService;
26import org.onosproject.store.cluster.messaging.ClusterMessage;
27import org.onosproject.store.cluster.messaging.ClusterMessageHandler;
28import org.onosproject.store.cluster.messaging.MessageSubject;
29import org.onosproject.store.serializers.KryoSerializer;
30import org.slf4j.Logger;
31import org.slf4j.LoggerFactory;
32
33import java.io.IOException;
34import java.util.ArrayList;
35import java.util.Collection;
Jonathan Hartaaa56572015-01-28 21:56:35 -080036import java.util.HashMap;
37import java.util.LinkedList;
Jonathan Hartdb3af892015-01-26 13:19:07 -080038import java.util.List;
39import java.util.Map;
40import java.util.Set;
41import java.util.concurrent.ConcurrentHashMap;
42import java.util.concurrent.CopyOnWriteArraySet;
43import java.util.concurrent.ExecutorService;
44import java.util.concurrent.Executors;
45import java.util.concurrent.ScheduledExecutorService;
Jonathan Hartaaa56572015-01-28 21:56:35 -080046import java.util.concurrent.TimeUnit;
Jonathan Hartdb3af892015-01-26 13:19:07 -080047import java.util.stream.Collectors;
48
49import static com.google.common.base.Preconditions.checkNotNull;
50import static com.google.common.base.Preconditions.checkState;
51import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
52import static org.onlab.util.Tools.minPriority;
53import static org.onlab.util.Tools.namedThreads;
54
55/**
56 * Distributed Map implementation which uses optimistic replication and gossip
57 * based techniques to provide an eventually consistent data store.
58 */
59public class EventuallyConsistentMapImpl<K, V>
60 implements EventuallyConsistentMap<K, V> {
61
62 private static final Logger log = LoggerFactory.getLogger(EventuallyConsistentMapImpl.class);
63
64 private final Map<K, Timestamped<V>> items;
65 private final Map<K, Timestamp> removedItems;
66
67 private final String mapName;
68 private final ClusterService clusterService;
69 private final ClusterCommunicationService clusterCommunicator;
70 private final KryoSerializer serializer;
71
72 private final ClockService<K> clockService;
73
74 private final MessageSubject updateMessageSubject;
75 private final MessageSubject removeMessageSubject;
Jonathan Hartaaa56572015-01-28 21:56:35 -080076 private final MessageSubject antiEntropyAdvertisementSubject;
Jonathan Hartdb3af892015-01-26 13:19:07 -080077
Jonathan Hartaaa56572015-01-28 21:56:35 -080078 private final Set<EventuallyConsistentMapListener<K, V>> listeners
Jonathan Hartdb3af892015-01-26 13:19:07 -080079 = new CopyOnWriteArraySet<>();
80
81 private final ExecutorService executor;
82
83 private final ScheduledExecutorService backgroundExecutor;
84
85 private volatile boolean destroyed = false;
Jonathan Hart539a6462015-01-27 17:05:43 -080086 private static final String ERROR_DESTROYED = " map is already destroyed";
Jonathan Hartdb3af892015-01-26 13:19:07 -080087
Jonathan Hart4f397e82015-02-04 09:10:41 -080088 private static final String ERROR_NULL_KEY = "Key cannot be null";
89 private static final String ERROR_NULL_VALUE = "Null values are not allowed";
90
Jonathan Hartdb3af892015-01-26 13:19:07 -080091 // TODO: Make these anti-entropy params configurable
92 private long initialDelaySec = 5;
93 private long periodSec = 5;
94
95 /**
96 * Creates a new eventually consistent map shared amongst multiple instances.
97 *
98 * Each map is identified by a string map name. EventuallyConsistentMapImpl
99 * objects in different JVMs that use the same map name will form a
100 * distributed map across JVMs (provided the cluster service is aware of
101 * both nodes).
102 *
103 * The client is expected to provide an
104 * {@link org.onlab.util.KryoNamespace.Builder} with which all classes that
105 * will be stored in this map have been registered (including referenced
106 * classes). This serializer will be used to serialize both K and V for
107 * inter-node notifications.
108 *
109 * The client must provide an {@link org.onosproject.store.impl.ClockService}
110 * which can generate timestamps for a given key. The clock service is free
111 * to generate timestamps however it wishes, however these timestamps will
112 * be used to serialize updates to the map so they must be strict enough
113 * to ensure updates are properly ordered for the use case (i.e. in some
114 * cases wallclock time will suffice, whereas in other cases logical time
115 * will be necessary).
116 *
117 * @param mapName a String identifier for the map.
118 * @param clusterService the cluster service
119 * @param clusterCommunicator the cluster communications service
120 * @param serializerBuilder a Kryo namespace builder that can serialize
121 * both K and V
122 * @param clockService a clock service able to generate timestamps
123 * for K
124 */
125 public EventuallyConsistentMapImpl(String mapName,
126 ClusterService clusterService,
127 ClusterCommunicationService clusterCommunicator,
128 KryoNamespace.Builder serializerBuilder,
129 ClockService<K> clockService) {
130
131 this.mapName = checkNotNull(mapName);
132 this.clusterService = checkNotNull(clusterService);
133 this.clusterCommunicator = checkNotNull(clusterCommunicator);
134
135 serializer = createSerializer(checkNotNull(serializerBuilder));
136
137 this.clockService = checkNotNull(clockService);
138
139 items = new ConcurrentHashMap<>();
140 removedItems = new ConcurrentHashMap<>();
141
142 executor = Executors
143 .newCachedThreadPool(namedThreads("onos-ecm-" + mapName + "-fg-%d"));
144
145 backgroundExecutor =
146 newSingleThreadScheduledExecutor(minPriority(
147 namedThreads("onos-ecm-" + mapName + "-bg-%d")));
148
Jonathan Hartaaa56572015-01-28 21:56:35 -0800149 // start anti-entropy thread
150 backgroundExecutor.scheduleAtFixedRate(new SendAdvertisementTask(),
151 initialDelaySec, periodSec,
152 TimeUnit.SECONDS);
153
Jonathan Hartdb3af892015-01-26 13:19:07 -0800154 updateMessageSubject = new MessageSubject("ecm-" + mapName + "-update");
155 clusterCommunicator.addSubscriber(updateMessageSubject,
156 new InternalPutEventListener());
157 removeMessageSubject = new MessageSubject("ecm-" + mapName + "-remove");
158 clusterCommunicator.addSubscriber(removeMessageSubject,
159 new InternalRemoveEventListener());
Jonathan Hartaaa56572015-01-28 21:56:35 -0800160 antiEntropyAdvertisementSubject = new MessageSubject("ecm-" + mapName + "-anti-entropy");
161 clusterCommunicator.addSubscriber(antiEntropyAdvertisementSubject,
162 new InternalAntiEntropyListener());
Jonathan Hartdb3af892015-01-26 13:19:07 -0800163 }
164
165 private KryoSerializer createSerializer(KryoNamespace.Builder builder) {
166 return new KryoSerializer() {
167 @Override
168 protected void setupKryoPool() {
169 // Add the map's internal helper classes to the user-supplied serializer
170 serializerPool = builder
171 .register(WallClockTimestamp.class)
172 .register(PutEntry.class)
Jonathan Hart539a6462015-01-27 17:05:43 -0800173 .register(RemoveEntry.class)
Jonathan Hartdb3af892015-01-26 13:19:07 -0800174 .register(ArrayList.class)
175 .register(InternalPutEvent.class)
176 .register(InternalRemoveEvent.class)
Jonathan Hartaaa56572015-01-28 21:56:35 -0800177 .register(AntiEntropyAdvertisement.class)
178 .register(HashMap.class)
Jonathan Hartdb3af892015-01-26 13:19:07 -0800179 .build();
Jonathan Hartdb3af892015-01-26 13:19:07 -0800180 }
181 };
182 }
183
184 @Override
185 public int size() {
Jonathan Hart539a6462015-01-27 17:05:43 -0800186 checkState(!destroyed, mapName + ERROR_DESTROYED);
Jonathan Hartdb3af892015-01-26 13:19:07 -0800187 return items.size();
188 }
189
190 @Override
191 public boolean isEmpty() {
Jonathan Hart539a6462015-01-27 17:05:43 -0800192 checkState(!destroyed, mapName + ERROR_DESTROYED);
Jonathan Hartdb3af892015-01-26 13:19:07 -0800193 return items.isEmpty();
194 }
195
196 @Override
197 public boolean containsKey(K key) {
Jonathan Hart539a6462015-01-27 17:05:43 -0800198 checkState(!destroyed, mapName + ERROR_DESTROYED);
Jonathan Hart4f397e82015-02-04 09:10:41 -0800199 checkNotNull(key, ERROR_NULL_KEY);
Jonathan Hartdb3af892015-01-26 13:19:07 -0800200 return items.containsKey(key);
201 }
202
203 @Override
204 public boolean containsValue(V value) {
Jonathan Hart539a6462015-01-27 17:05:43 -0800205 checkState(!destroyed, mapName + ERROR_DESTROYED);
Jonathan Hart4f397e82015-02-04 09:10:41 -0800206 checkNotNull(value, ERROR_NULL_VALUE);
Jonathan Hartdb3af892015-01-26 13:19:07 -0800207
208 return items.values().stream()
209 .anyMatch(timestamped -> timestamped.value().equals(value));
210 }
211
212 @Override
213 public V get(K key) {
Jonathan Hart539a6462015-01-27 17:05:43 -0800214 checkState(!destroyed, mapName + ERROR_DESTROYED);
Jonathan Hart4f397e82015-02-04 09:10:41 -0800215 checkNotNull(key, ERROR_NULL_KEY);
Jonathan Hartdb3af892015-01-26 13:19:07 -0800216
217 Timestamped<V> value = items.get(key);
218 if (value != null) {
219 return value.value();
220 }
221 return null;
222 }
223
224 @Override
225 public void put(K key, V value) {
Jonathan Hart539a6462015-01-27 17:05:43 -0800226 checkState(!destroyed, mapName + ERROR_DESTROYED);
Jonathan Hart4f397e82015-02-04 09:10:41 -0800227 checkNotNull(key, ERROR_NULL_KEY);
228 checkNotNull(value, ERROR_NULL_VALUE);
Jonathan Hartdb3af892015-01-26 13:19:07 -0800229
230 Timestamp timestamp = clockService.getTimestamp(key);
231 if (putInternal(key, value, timestamp)) {
232 notifyPeers(new InternalPutEvent<>(key, value, timestamp));
233 EventuallyConsistentMapEvent<K, V> externalEvent
234 = new EventuallyConsistentMapEvent<>(
235 EventuallyConsistentMapEvent.Type.PUT, key, value);
236 notifyListeners(externalEvent);
237 }
238 }
239
240 private boolean putInternal(K key, V value, Timestamp timestamp) {
241 synchronized (this) {
242 Timestamp removed = removedItems.get(key);
243 if (removed != null && removed.compareTo(timestamp) > 0) {
244 return false;
245 }
246
247 Timestamped<V> existing = items.get(key);
248 if (existing != null && existing.isNewer(timestamp)) {
249 return false;
250 } else {
251 items.put(key, new Timestamped<>(value, timestamp));
252 removedItems.remove(key);
253 return true;
254 }
255 }
256 }
257
258 @Override
259 public void remove(K key) {
Jonathan Hart539a6462015-01-27 17:05:43 -0800260 checkState(!destroyed, mapName + ERROR_DESTROYED);
Jonathan Hart4f397e82015-02-04 09:10:41 -0800261 checkNotNull(key, ERROR_NULL_KEY);
Jonathan Hartdb3af892015-01-26 13:19:07 -0800262
263 Timestamp timestamp = clockService.getTimestamp(key);
264 if (removeInternal(key, timestamp)) {
265 notifyPeers(new InternalRemoveEvent<>(key, timestamp));
266 EventuallyConsistentMapEvent<K, V> externalEvent
267 = new EventuallyConsistentMapEvent<>(
268 EventuallyConsistentMapEvent.Type.REMOVE, key, null);
269 notifyListeners(externalEvent);
270 }
271 }
272
273 private boolean removeInternal(K key, Timestamp timestamp) {
274 synchronized (this) {
275 if (items.get(key) != null && items.get(key).isNewer(timestamp)) {
276 return false;
277 }
278
279 items.remove(key);
280 removedItems.put(key, timestamp);
281 return true;
282 }
283 }
284
285 @Override
286 public void putAll(Map<? extends K, ? extends V> m) {
Jonathan Hart539a6462015-01-27 17:05:43 -0800287 checkState(!destroyed, mapName + ERROR_DESTROYED);
Jonathan Hartdb3af892015-01-26 13:19:07 -0800288
289 List<PutEntry<K, V>> updates = new ArrayList<>(m.size());
290
291 for (Map.Entry<? extends K, ? extends V> entry : m.entrySet()) {
292 K key = entry.getKey();
293 V value = entry.getValue();
Jonathan Hart4f397e82015-02-04 09:10:41 -0800294
295 checkNotNull(key, ERROR_NULL_KEY);
296 checkNotNull(value, ERROR_NULL_VALUE);
297
Jonathan Hartdb3af892015-01-26 13:19:07 -0800298 Timestamp timestamp = clockService.getTimestamp(entry.getKey());
299
300 if (putInternal(key, value, timestamp)) {
301 updates.add(new PutEntry<>(key, value, timestamp));
302 }
303 }
304
Jonathan Hart584d2f32015-01-27 19:46:14 -0800305 if (!updates.isEmpty()) {
306 notifyPeers(new InternalPutEvent<>(updates));
Jonathan Hartdb3af892015-01-26 13:19:07 -0800307
Jonathan Hart584d2f32015-01-27 19:46:14 -0800308 for (PutEntry<K, V> entry : updates) {
309 EventuallyConsistentMapEvent<K, V> externalEvent = new EventuallyConsistentMapEvent<>(
310 EventuallyConsistentMapEvent.Type.PUT, entry.key(),
311 entry.value());
312 notifyListeners(externalEvent);
313 }
Jonathan Hartdb3af892015-01-26 13:19:07 -0800314 }
315 }
316
317 @Override
318 public void clear() {
Jonathan Hart539a6462015-01-27 17:05:43 -0800319 checkState(!destroyed, mapName + ERROR_DESTROYED);
Jonathan Hartdb3af892015-01-26 13:19:07 -0800320
321 List<RemoveEntry<K>> removed = new ArrayList<>(items.size());
322
323 for (K key : items.keySet()) {
324 Timestamp timestamp = clockService.getTimestamp(key);
325
326 if (removeInternal(key, timestamp)) {
327 removed.add(new RemoveEntry<>(key, timestamp));
328 }
329 }
330
Jonathan Hart584d2f32015-01-27 19:46:14 -0800331 if (!removed.isEmpty()) {
332 notifyPeers(new InternalRemoveEvent<>(removed));
Jonathan Hartdb3af892015-01-26 13:19:07 -0800333
Jonathan Hart584d2f32015-01-27 19:46:14 -0800334 for (RemoveEntry<K> entry : removed) {
335 EventuallyConsistentMapEvent<K, V> externalEvent
336 = new EventuallyConsistentMapEvent<>(
337 EventuallyConsistentMapEvent.Type.REMOVE, entry.key(),
338 null);
339 notifyListeners(externalEvent);
340 }
Jonathan Hartdb3af892015-01-26 13:19:07 -0800341 }
342 }
343
344 @Override
345 public Set<K> keySet() {
Jonathan Hart539a6462015-01-27 17:05:43 -0800346 checkState(!destroyed, mapName + ERROR_DESTROYED);
Jonathan Hartdb3af892015-01-26 13:19:07 -0800347
348 return items.keySet();
349 }
350
351 @Override
352 public Collection<V> values() {
Jonathan Hart539a6462015-01-27 17:05:43 -0800353 checkState(!destroyed, mapName + ERROR_DESTROYED);
Jonathan Hartdb3af892015-01-26 13:19:07 -0800354
355 return items.values().stream()
356 .map(Timestamped::value)
357 .collect(Collectors.toList());
358 }
359
360 @Override
361 public Set<Map.Entry<K, V>> entrySet() {
Jonathan Hart539a6462015-01-27 17:05:43 -0800362 checkState(!destroyed, mapName + ERROR_DESTROYED);
Jonathan Hartdb3af892015-01-26 13:19:07 -0800363
364 return items.entrySet().stream()
Jonathan Hartf9108232015-02-02 16:37:35 -0800365 .map(e -> Pair.of(e.getKey(), e.getValue().value()))
Jonathan Hartdb3af892015-01-26 13:19:07 -0800366 .collect(Collectors.toSet());
367 }
368
369 @Override
Jonathan Hart539a6462015-01-27 17:05:43 -0800370 public void addListener(EventuallyConsistentMapListener<K, V> listener) {
371 checkState(!destroyed, mapName + ERROR_DESTROYED);
Jonathan Hartdb3af892015-01-26 13:19:07 -0800372
373 listeners.add(checkNotNull(listener));
374 }
375
376 @Override
Jonathan Hart539a6462015-01-27 17:05:43 -0800377 public void removeListener(EventuallyConsistentMapListener<K, V> listener) {
378 checkState(!destroyed, mapName + ERROR_DESTROYED);
Jonathan Hartdb3af892015-01-26 13:19:07 -0800379
380 listeners.remove(checkNotNull(listener));
381 }
382
383 @Override
384 public void destroy() {
385 destroyed = true;
386
387 executor.shutdown();
388 backgroundExecutor.shutdown();
389
Jonathan Hart584d2f32015-01-27 19:46:14 -0800390 listeners.clear();
391
Jonathan Hartdb3af892015-01-26 13:19:07 -0800392 clusterCommunicator.removeSubscriber(updateMessageSubject);
393 clusterCommunicator.removeSubscriber(removeMessageSubject);
Jonathan Hart584d2f32015-01-27 19:46:14 -0800394 clusterCommunicator.removeSubscriber(antiEntropyAdvertisementSubject);
Jonathan Hartdb3af892015-01-26 13:19:07 -0800395 }
396
Jonathan Hartaaa56572015-01-28 21:56:35 -0800397 private void notifyListeners(EventuallyConsistentMapEvent<K, V> event) {
398 for (EventuallyConsistentMapListener<K, V> listener : listeners) {
Jonathan Hartdb3af892015-01-26 13:19:07 -0800399 listener.event(event);
400 }
401 }
402
403 private void notifyPeers(InternalPutEvent event) {
Jonathan Hart7d656f42015-01-27 14:07:23 -0800404 broadcastMessage(updateMessageSubject, event);
Jonathan Hartdb3af892015-01-26 13:19:07 -0800405 }
406
407 private void notifyPeers(InternalRemoveEvent event) {
Jonathan Hart7d656f42015-01-27 14:07:23 -0800408 broadcastMessage(removeMessageSubject, event);
Jonathan Hartdb3af892015-01-26 13:19:07 -0800409 }
410
Jonathan Hart7d656f42015-01-27 14:07:23 -0800411 private void broadcastMessage(MessageSubject subject, Object event) {
Jonathan Hartdb3af892015-01-26 13:19:07 -0800412 ClusterMessage message = new ClusterMessage(
413 clusterService.getLocalNode().id(),
414 subject,
415 serializer.encode(event));
416 clusterCommunicator.broadcast(message);
417 }
418
419 private void unicastMessage(NodeId peer,
420 MessageSubject subject,
421 Object event) throws IOException {
422 ClusterMessage message = new ClusterMessage(
423 clusterService.getLocalNode().id(),
424 subject,
425 serializer.encode(event));
426 clusterCommunicator.unicast(message, peer);
427 }
428
Jonathan Hartaaa56572015-01-28 21:56:35 -0800429 private final class SendAdvertisementTask implements Runnable {
430 @Override
431 public void run() {
432 if (Thread.currentThread().isInterrupted()) {
433 log.info("Interrupted, quitting");
434 return;
435 }
436
437 try {
438 final NodeId self = clusterService.getLocalNode().id();
439 Set<ControllerNode> nodes = clusterService.getNodes();
440
441 List<NodeId> nodeIds = nodes.stream()
442 .map(node -> node.id())
443 .collect(Collectors.toList());
444
445 if (nodeIds.size() == 1 && nodeIds.get(0).equals(self)) {
446 log.trace("No other peers in the cluster.");
447 return;
448 }
449
450 NodeId peer;
451 do {
452 int idx = RandomUtils.nextInt(0, nodeIds.size());
453 peer = nodeIds.get(idx);
454 } while (peer.equals(self));
455
456 if (Thread.currentThread().isInterrupted()) {
457 log.info("Interrupted, quitting");
458 return;
459 }
460
461 AntiEntropyAdvertisement<K> ad = createAdvertisement();
462
463 try {
464 unicastMessage(peer, antiEntropyAdvertisementSubject, ad);
465 } catch (IOException e) {
466 log.debug("Failed to send anti-entropy advertisement to {}", peer);
467 }
468 } catch (Exception e) {
469 // Catch all exceptions to avoid scheduled task being suppressed.
470 log.error("Exception thrown while sending advertisement", e);
471 }
472 }
473 }
474
475 private AntiEntropyAdvertisement<K> createAdvertisement() {
476 final NodeId self = clusterService.getLocalNode().id();
477
478 Map<K, Timestamp> timestamps = new HashMap<>(items.size());
479
480 items.forEach((key, value) -> timestamps.put(key, value.timestamp()));
481
482 Map<K, Timestamp> tombstones = new HashMap<>(removedItems);
483
484 return new AntiEntropyAdvertisement<>(self, timestamps, tombstones);
485 }
486
487 private void handleAntiEntropyAdvertisement(AntiEntropyAdvertisement<K> ad) {
488 List<EventuallyConsistentMapEvent<K, V>> externalEvents;
489
490 synchronized (this) {
491 final NodeId sender = ad.sender();
492
493 externalEvents = antiEntropyCheckLocalItems(ad);
494
495 antiEntropyCheckLocalRemoved(ad);
496
497 externalEvents.addAll(antiEntropyCheckRemoteRemoved(ad));
498
499 // if remote ad has something unknown, actively sync
500 for (K key : ad.timestamps().keySet()) {
501 if (!items.containsKey(key)) {
502 AntiEntropyAdvertisement<K> myAd = createAdvertisement();
503 try {
504 unicastMessage(sender, antiEntropyAdvertisementSubject,
505 myAd);
506 break;
507 } catch (IOException e) {
508 log.debug(
509 "Failed to send reactive anti-entropy advertisement to {}",
510 sender);
511 }
512 }
513 }
514 } // synchronized (this)
515
516 externalEvents.forEach(this::notifyListeners);
517 }
518
519 /**
520 * Checks if any of the remote's live items or tombstones are out of date
521 * according to our local live item list, or if our live items are out of
522 * date according to the remote's tombstone list.
523 * If the local copy is more recent, it will be pushed to the remote. If the
524 * remote has a more recent remove, we apply that to the local state.
525 *
526 * @param ad remote anti-entropy advertisement
527 * @return list of external events relating to local operations performed
528 */
529 // Guarded by synchronized (this)
530 private List<EventuallyConsistentMapEvent<K, V>> antiEntropyCheckLocalItems(
531 AntiEntropyAdvertisement<K> ad) {
532 final List<EventuallyConsistentMapEvent<K, V>> externalEvents
533 = new LinkedList<>();
534 final NodeId sender = ad.sender();
535
536 final List<PutEntry<K, V>> updatesToSend = new ArrayList<>();
537
538 for (Map.Entry<K, Timestamped<V>> item : items.entrySet()) {
539 K key = item.getKey();
540 Timestamped<V> localValue = item.getValue();
541
542 Timestamp remoteTimestamp = ad.timestamps().get(key);
543 if (remoteTimestamp == null) {
544 remoteTimestamp = ad.tombstones().get(key);
545 }
546 if (remoteTimestamp == null || localValue
547 .isNewer(remoteTimestamp)) {
548 // local value is more recent, push to sender
549 updatesToSend
550 .add(new PutEntry<>(key, localValue.value(),
551 localValue.timestamp()));
552 }
553
554 Timestamp remoteDeadTimestamp = ad.tombstones().get(key);
555 if (remoteDeadTimestamp != null &&
556 remoteDeadTimestamp.compareTo(localValue.timestamp()) > 0) {
557 // sender has a more recent remove
558 if (removeInternal(key, remoteDeadTimestamp)) {
559 externalEvents.add(new EventuallyConsistentMapEvent<>(
560 EventuallyConsistentMapEvent.Type.REMOVE, key, null));
561 }
562 }
563 }
564
565 // Send all updates to the peer at once
566 if (!updatesToSend.isEmpty()) {
567 try {
568 unicastMessage(sender, updateMessageSubject, new InternalPutEvent<>(updatesToSend));
569 } catch (IOException e) {
570 log.warn("Failed to send advertisement response", e);
571 }
572 }
573
574 return externalEvents;
575 }
576
577 /**
578 * Checks if any items in the remote live list are out of date according
579 * to our tombstone list. If we find we have a more up to date tombstone,
580 * we'll send it to the remote.
581 *
582 * @param ad remote anti-entropy advertisement
583 */
584 // Guarded by synchronized (this)
585 private void antiEntropyCheckLocalRemoved(AntiEntropyAdvertisement<K> ad) {
586 final NodeId sender = ad.sender();
587
588 final List<RemoveEntry<K>> removesToSend = new ArrayList<>();
589
590 for (Map.Entry<K, Timestamp> dead : removedItems.entrySet()) {
591 K key = dead.getKey();
592 Timestamp localDeadTimestamp = dead.getValue();
593
594 Timestamp remoteLiveTimestamp = ad.timestamps().get(key);
595 if (remoteLiveTimestamp != null
596 && localDeadTimestamp.compareTo(remoteLiveTimestamp) > 0) {
597 // sender has zombie, push remove
598 removesToSend
599 .add(new RemoveEntry<>(key, localDeadTimestamp));
600 }
601 }
602
603 // Send all removes to the peer at once
604 if (!removesToSend.isEmpty()) {
605 try {
606 unicastMessage(sender, removeMessageSubject, new InternalRemoveEvent<>(removesToSend));
607 } catch (IOException e) {
608 log.warn("Failed to send advertisement response", e);
609 }
610 }
611 }
612
613 /**
614 * Checks if any of the local live items are out of date according to the
615 * remote's tombstone advertisements. If we find a local item is out of date,
616 * we'll apply the remove operation to the local state.
617 *
618 * @param ad remote anti-entropy advertisement
619 * @return list of external events relating to local operations performed
620 */
621 // Guarded by synchronized (this)
622 private List<EventuallyConsistentMapEvent<K, V>>
623 antiEntropyCheckRemoteRemoved(AntiEntropyAdvertisement<K> ad) {
624 final List<EventuallyConsistentMapEvent<K, V>> externalEvents
625 = new LinkedList<>();
626
627 for (Map.Entry<K, Timestamp> remoteDead : ad.tombstones().entrySet()) {
628 K key = remoteDead.getKey();
629 Timestamp remoteDeadTimestamp = remoteDead.getValue();
630
631 Timestamped<V> local = items.get(key);
632 Timestamp localDead = removedItems.get(key);
633 if (local != null
634 && remoteDeadTimestamp.compareTo(local.timestamp()) > 0) {
635 // remove our version
636 if (removeInternal(key, remoteDeadTimestamp)) {
637 externalEvents.add(new EventuallyConsistentMapEvent<>(
638 EventuallyConsistentMapEvent.Type.REMOVE, key, null));
639 }
640 } else if (localDead != null &&
641 remoteDeadTimestamp.compareTo(localDead) > 0) {
642 // If we both had the item as removed, but their timestamp is
643 // newer, update ours to the newer value
644 removedItems.put(key, remoteDeadTimestamp);
645 }
646 }
647
648 return externalEvents;
649 }
650
651 private final class InternalAntiEntropyListener
652 implements ClusterMessageHandler {
653
654 @Override
655 public void handle(ClusterMessage message) {
656 log.trace("Received anti-entropy advertisement from peer: {}", message.sender());
657 AntiEntropyAdvertisement<K> advertisement = serializer.decode(message.payload());
658 backgroundExecutor.submit(() -> {
659 try {
660 handleAntiEntropyAdvertisement(advertisement);
661 } catch (Exception e) {
662 log.warn("Exception thrown handling advertisements", e);
663 }
664 });
665 }
666 }
667
Jonathan Hartdb3af892015-01-26 13:19:07 -0800668 private final class InternalPutEventListener implements
669 ClusterMessageHandler {
670 @Override
671 public void handle(ClusterMessage message) {
672 log.debug("Received put event from peer: {}", message.sender());
673 InternalPutEvent<K, V> event = serializer.decode(message.payload());
674
675 executor.submit(() -> {
676 try {
677 for (PutEntry<K, V> entry : event.entries()) {
678 K key = entry.key();
679 V value = entry.value();
680 Timestamp timestamp = entry.timestamp();
681
682 if (putInternal(key, value, timestamp)) {
Jonathan Hartaaa56572015-01-28 21:56:35 -0800683 EventuallyConsistentMapEvent<K, V> externalEvent =
Jonathan Hartdb3af892015-01-26 13:19:07 -0800684 new EventuallyConsistentMapEvent<>(
685 EventuallyConsistentMapEvent.Type.PUT, key,
686 value);
687 notifyListeners(externalEvent);
688 }
689 }
690 } catch (Exception e) {
691 log.warn("Exception thrown handling put", e);
692 }
693 });
694 }
695 }
696
697 private final class InternalRemoveEventListener implements
698 ClusterMessageHandler {
699 @Override
700 public void handle(ClusterMessage message) {
701 log.debug("Received remove event from peer: {}", message.sender());
702 InternalRemoveEvent<K> event = serializer.decode(message.payload());
703
704 executor.submit(() -> {
705 try {
706 for (RemoveEntry<K> entry : event.entries()) {
707 K key = entry.key();
708 Timestamp timestamp = entry.timestamp();
709
710 if (removeInternal(key, timestamp)) {
Jonathan Hartaaa56572015-01-28 21:56:35 -0800711 EventuallyConsistentMapEvent<K, V> externalEvent
712 = new EventuallyConsistentMapEvent<>(
Jonathan Hartdb3af892015-01-26 13:19:07 -0800713 EventuallyConsistentMapEvent.Type.REMOVE,
714 key, null);
715 notifyListeners(externalEvent);
716 }
717 }
718 } catch (Exception e) {
719 log.warn("Exception thrown handling remove", e);
720 }
721 });
722 }
723 }
724
Jonathan Hartdb3af892015-01-26 13:19:07 -0800725}