blob: 8c52156f00bb5e59d42127ed1d042b95b1ba5252 [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 */
Jonathan Hart77bdd262015-02-03 09:07:48 -080016package org.onosproject.store.ecmap;
Jonathan Hartdb3af892015-01-26 13:19:07 -080017
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;
Jonathan Hart77bdd262015-02-03 09:07:48 -080029import org.onosproject.store.impl.ClockService;
30import org.onosproject.store.impl.Timestamped;
31import org.onosproject.store.impl.WallClockTimestamp;
Jonathan Hartdb3af892015-01-26 13:19:07 -080032import org.onosproject.store.serializers.KryoSerializer;
33import org.slf4j.Logger;
34import org.slf4j.LoggerFactory;
35
36import java.io.IOException;
37import java.util.ArrayList;
38import java.util.Collection;
Jonathan Hartaaa56572015-01-28 21:56:35 -080039import java.util.HashMap;
40import java.util.LinkedList;
Jonathan Hartdb3af892015-01-26 13:19:07 -080041import java.util.List;
42import java.util.Map;
43import java.util.Set;
44import java.util.concurrent.ConcurrentHashMap;
45import java.util.concurrent.CopyOnWriteArraySet;
46import java.util.concurrent.ExecutorService;
47import java.util.concurrent.Executors;
48import java.util.concurrent.ScheduledExecutorService;
Jonathan Hartaaa56572015-01-28 21:56:35 -080049import java.util.concurrent.TimeUnit;
Jonathan Hartdb3af892015-01-26 13:19:07 -080050import java.util.stream.Collectors;
51
52import static com.google.common.base.Preconditions.checkNotNull;
53import static com.google.common.base.Preconditions.checkState;
54import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
Brian O'Connor4b2ba5f2015-02-18 20:54:00 -080055import static org.onlab.util.Tools.groupedThreads;
Jonathan Hartdb3af892015-01-26 13:19:07 -080056import static org.onlab.util.Tools.minPriority;
Jonathan Hartdb3af892015-01-26 13:19:07 -080057
58/**
59 * Distributed Map implementation which uses optimistic replication and gossip
60 * based techniques to provide an eventually consistent data store.
61 */
62public class EventuallyConsistentMapImpl<K, V>
63 implements EventuallyConsistentMap<K, V> {
64
65 private static final Logger log = LoggerFactory.getLogger(EventuallyConsistentMapImpl.class);
66
67 private final Map<K, Timestamped<V>> items;
68 private final Map<K, Timestamp> removedItems;
69
70 private final String mapName;
71 private final ClusterService clusterService;
72 private final ClusterCommunicationService clusterCommunicator;
73 private final KryoSerializer serializer;
74
Jonathan Hart5ec32ba2015-02-05 13:33:58 -080075 private final ClockService<K, V> clockService;
Jonathan Hartdb3af892015-01-26 13:19:07 -080076
77 private final MessageSubject updateMessageSubject;
78 private final MessageSubject removeMessageSubject;
Jonathan Hartaaa56572015-01-28 21:56:35 -080079 private final MessageSubject antiEntropyAdvertisementSubject;
Jonathan Hartdb3af892015-01-26 13:19:07 -080080
Jonathan Hartaaa56572015-01-28 21:56:35 -080081 private final Set<EventuallyConsistentMapListener<K, V>> listeners
Jonathan Hartdb3af892015-01-26 13:19:07 -080082 = new CopyOnWriteArraySet<>();
83
84 private final ExecutorService executor;
85
86 private final ScheduledExecutorService backgroundExecutor;
87
Madan Jampani28726282015-02-19 11:40:23 -080088 private final ExecutorService broadcastMessageExecutor;
89
Jonathan Hartdb3af892015-01-26 13:19:07 -080090 private volatile boolean destroyed = false;
Jonathan Hart539a6462015-01-27 17:05:43 -080091 private static final String ERROR_DESTROYED = " map is already destroyed";
Jonathan Hartdb3af892015-01-26 13:19:07 -080092
Jonathan Hart4f397e82015-02-04 09:10:41 -080093 private static final String ERROR_NULL_KEY = "Key cannot be null";
94 private static final String ERROR_NULL_VALUE = "Null values are not allowed";
95
Jonathan Hartdb3af892015-01-26 13:19:07 -080096 // TODO: Make these anti-entropy params configurable
97 private long initialDelaySec = 5;
98 private long periodSec = 5;
99
100 /**
101 * Creates a new eventually consistent map shared amongst multiple instances.
102 *
103 * Each map is identified by a string map name. EventuallyConsistentMapImpl
104 * objects in different JVMs that use the same map name will form a
105 * distributed map across JVMs (provided the cluster service is aware of
106 * both nodes).
107 *
108 * The client is expected to provide an
109 * {@link org.onlab.util.KryoNamespace.Builder} with which all classes that
110 * will be stored in this map have been registered (including referenced
111 * classes). This serializer will be used to serialize both K and V for
112 * inter-node notifications.
113 *
114 * The client must provide an {@link org.onosproject.store.impl.ClockService}
115 * which can generate timestamps for a given key. The clock service is free
116 * to generate timestamps however it wishes, however these timestamps will
117 * be used to serialize updates to the map so they must be strict enough
118 * to ensure updates are properly ordered for the use case (i.e. in some
119 * cases wallclock time will suffice, whereas in other cases logical time
120 * will be necessary).
121 *
122 * @param mapName a String identifier for the map.
123 * @param clusterService the cluster service
124 * @param clusterCommunicator the cluster communications service
125 * @param serializerBuilder a Kryo namespace builder that can serialize
126 * both K and V
127 * @param clockService a clock service able to generate timestamps
128 * for K
129 */
130 public EventuallyConsistentMapImpl(String mapName,
131 ClusterService clusterService,
132 ClusterCommunicationService clusterCommunicator,
133 KryoNamespace.Builder serializerBuilder,
Jonathan Hart5ec32ba2015-02-05 13:33:58 -0800134 ClockService<K, V> clockService) {
Jonathan Hartdb3af892015-01-26 13:19:07 -0800135
136 this.mapName = checkNotNull(mapName);
137 this.clusterService = checkNotNull(clusterService);
138 this.clusterCommunicator = checkNotNull(clusterCommunicator);
139
140 serializer = createSerializer(checkNotNull(serializerBuilder));
141
142 this.clockService = checkNotNull(clockService);
143
144 items = new ConcurrentHashMap<>();
145 removedItems = new ConcurrentHashMap<>();
146
Brian O'Connor4b2ba5f2015-02-18 20:54:00 -0800147 executor = Executors //FIXME
148 .newFixedThreadPool(4, groupedThreads("onos/ecm", mapName + "-fg-%d"));
Jonathan Hartdb3af892015-01-26 13:19:07 -0800149
Madan Jampani28726282015-02-19 11:40:23 -0800150 broadcastMessageExecutor = Executors.newSingleThreadExecutor(groupedThreads("onos/ecm", mapName + "-notify"));
151
Jonathan Hartdb3af892015-01-26 13:19:07 -0800152 backgroundExecutor =
153 newSingleThreadScheduledExecutor(minPriority(
Brian O'Connor4b2ba5f2015-02-18 20:54:00 -0800154 groupedThreads("onos/ecm", mapName + "-bg-%d")));
Jonathan Hartdb3af892015-01-26 13:19:07 -0800155
Jonathan Hartaaa56572015-01-28 21:56:35 -0800156 // start anti-entropy thread
157 backgroundExecutor.scheduleAtFixedRate(new SendAdvertisementTask(),
158 initialDelaySec, periodSec,
159 TimeUnit.SECONDS);
160
Jonathan Hartdb3af892015-01-26 13:19:07 -0800161 updateMessageSubject = new MessageSubject("ecm-" + mapName + "-update");
162 clusterCommunicator.addSubscriber(updateMessageSubject,
163 new InternalPutEventListener());
164 removeMessageSubject = new MessageSubject("ecm-" + mapName + "-remove");
165 clusterCommunicator.addSubscriber(removeMessageSubject,
166 new InternalRemoveEventListener());
Jonathan Hartaaa56572015-01-28 21:56:35 -0800167 antiEntropyAdvertisementSubject = new MessageSubject("ecm-" + mapName + "-anti-entropy");
168 clusterCommunicator.addSubscriber(antiEntropyAdvertisementSubject,
169 new InternalAntiEntropyListener());
Jonathan Hartdb3af892015-01-26 13:19:07 -0800170 }
171
172 private KryoSerializer createSerializer(KryoNamespace.Builder builder) {
173 return new KryoSerializer() {
174 @Override
175 protected void setupKryoPool() {
176 // Add the map's internal helper classes to the user-supplied serializer
177 serializerPool = builder
178 .register(WallClockTimestamp.class)
179 .register(PutEntry.class)
Jonathan Hart539a6462015-01-27 17:05:43 -0800180 .register(RemoveEntry.class)
Jonathan Hartdb3af892015-01-26 13:19:07 -0800181 .register(ArrayList.class)
182 .register(InternalPutEvent.class)
183 .register(InternalRemoveEvent.class)
Jonathan Hartaaa56572015-01-28 21:56:35 -0800184 .register(AntiEntropyAdvertisement.class)
185 .register(HashMap.class)
Jonathan Hartdb3af892015-01-26 13:19:07 -0800186 .build();
Jonathan Hartdb3af892015-01-26 13:19:07 -0800187 }
188 };
189 }
190
191 @Override
192 public int size() {
Jonathan Hart539a6462015-01-27 17:05:43 -0800193 checkState(!destroyed, mapName + ERROR_DESTROYED);
Jonathan Hartdb3af892015-01-26 13:19:07 -0800194 return items.size();
195 }
196
197 @Override
198 public boolean isEmpty() {
Jonathan Hart539a6462015-01-27 17:05:43 -0800199 checkState(!destroyed, mapName + ERROR_DESTROYED);
Jonathan Hartdb3af892015-01-26 13:19:07 -0800200 return items.isEmpty();
201 }
202
203 @Override
204 public boolean containsKey(K key) {
Jonathan Hart539a6462015-01-27 17:05:43 -0800205 checkState(!destroyed, mapName + ERROR_DESTROYED);
Jonathan Hart4f397e82015-02-04 09:10:41 -0800206 checkNotNull(key, ERROR_NULL_KEY);
Jonathan Hartdb3af892015-01-26 13:19:07 -0800207 return items.containsKey(key);
208 }
209
210 @Override
211 public boolean containsValue(V value) {
Jonathan Hart539a6462015-01-27 17:05:43 -0800212 checkState(!destroyed, mapName + ERROR_DESTROYED);
Jonathan Hart4f397e82015-02-04 09:10:41 -0800213 checkNotNull(value, ERROR_NULL_VALUE);
Jonathan Hartdb3af892015-01-26 13:19:07 -0800214
215 return items.values().stream()
216 .anyMatch(timestamped -> timestamped.value().equals(value));
217 }
218
219 @Override
220 public V get(K key) {
Jonathan Hart539a6462015-01-27 17:05:43 -0800221 checkState(!destroyed, mapName + ERROR_DESTROYED);
Jonathan Hart4f397e82015-02-04 09:10:41 -0800222 checkNotNull(key, ERROR_NULL_KEY);
Jonathan Hartdb3af892015-01-26 13:19:07 -0800223
224 Timestamped<V> value = items.get(key);
225 if (value != null) {
226 return value.value();
227 }
228 return null;
229 }
230
231 @Override
232 public void put(K key, V value) {
Jonathan Hart539a6462015-01-27 17:05:43 -0800233 checkState(!destroyed, mapName + ERROR_DESTROYED);
Jonathan Hart4f397e82015-02-04 09:10:41 -0800234 checkNotNull(key, ERROR_NULL_KEY);
235 checkNotNull(value, ERROR_NULL_VALUE);
Jonathan Hartdb3af892015-01-26 13:19:07 -0800236
Jonathan Hart5ec32ba2015-02-05 13:33:58 -0800237 Timestamp timestamp = clockService.getTimestamp(key, value);
238
Jonathan Hartdb3af892015-01-26 13:19:07 -0800239 if (putInternal(key, value, timestamp)) {
240 notifyPeers(new InternalPutEvent<>(key, value, timestamp));
241 EventuallyConsistentMapEvent<K, V> externalEvent
242 = new EventuallyConsistentMapEvent<>(
243 EventuallyConsistentMapEvent.Type.PUT, key, value);
244 notifyListeners(externalEvent);
245 }
246 }
247
248 private boolean putInternal(K key, V value, Timestamp timestamp) {
249 synchronized (this) {
250 Timestamp removed = removedItems.get(key);
251 if (removed != null && removed.compareTo(timestamp) > 0) {
Jonathan Hart07e58be2015-02-12 09:57:16 -0800252 log.debug("ecmap - removed was newer {}", value);
Jonathan Hartdb3af892015-01-26 13:19:07 -0800253 return false;
254 }
255
256 Timestamped<V> existing = items.get(key);
257 if (existing != null && existing.isNewer(timestamp)) {
Jonathan Hart07e58be2015-02-12 09:57:16 -0800258 log.debug("ecmap - existing was newer {}", value);
Jonathan Hartdb3af892015-01-26 13:19:07 -0800259 return false;
260 } else {
261 items.put(key, new Timestamped<>(value, timestamp));
262 removedItems.remove(key);
263 return true;
264 }
265 }
266 }
267
268 @Override
269 public void remove(K key) {
Jonathan Hart539a6462015-01-27 17:05:43 -0800270 checkState(!destroyed, mapName + ERROR_DESTROYED);
Jonathan Hart4f397e82015-02-04 09:10:41 -0800271 checkNotNull(key, ERROR_NULL_KEY);
Jonathan Hartdb3af892015-01-26 13:19:07 -0800272
Jonathan Hart5ec32ba2015-02-05 13:33:58 -0800273 // TODO prevent calls here if value is important for timestamp
274 Timestamp timestamp = clockService.getTimestamp(key, null);
275
Jonathan Hartdb3af892015-01-26 13:19:07 -0800276 if (removeInternal(key, timestamp)) {
277 notifyPeers(new InternalRemoveEvent<>(key, timestamp));
278 EventuallyConsistentMapEvent<K, V> externalEvent
279 = new EventuallyConsistentMapEvent<>(
280 EventuallyConsistentMapEvent.Type.REMOVE, key, null);
281 notifyListeners(externalEvent);
282 }
283 }
284
285 private boolean removeInternal(K key, Timestamp timestamp) {
286 synchronized (this) {
287 if (items.get(key) != null && items.get(key).isNewer(timestamp)) {
288 return false;
289 }
290
291 items.remove(key);
292 removedItems.put(key, timestamp);
293 return true;
294 }
295 }
296
297 @Override
Jonathan Hart5ec32ba2015-02-05 13:33:58 -0800298 public void remove(K key, V value) {
299 checkState(!destroyed, mapName + ERROR_DESTROYED);
300 checkNotNull(key, ERROR_NULL_KEY);
301 checkNotNull(value, ERROR_NULL_VALUE);
302
303 Timestamp timestamp = clockService.getTimestamp(key, value);
304
305 if (removeInternal(key, timestamp)) {
306 notifyPeers(new InternalRemoveEvent<>(key, timestamp));
307 EventuallyConsistentMapEvent<K, V> externalEvent
308 = new EventuallyConsistentMapEvent<>(
309 EventuallyConsistentMapEvent.Type.REMOVE, key, value);
310 notifyListeners(externalEvent);
311 }
312 }
313
314 @Override
Jonathan Hartdb3af892015-01-26 13:19:07 -0800315 public void putAll(Map<? extends K, ? extends V> m) {
Jonathan Hart539a6462015-01-27 17:05:43 -0800316 checkState(!destroyed, mapName + ERROR_DESTROYED);
Jonathan Hartdb3af892015-01-26 13:19:07 -0800317
318 List<PutEntry<K, V>> updates = new ArrayList<>(m.size());
319
320 for (Map.Entry<? extends K, ? extends V> entry : m.entrySet()) {
321 K key = entry.getKey();
322 V value = entry.getValue();
Jonathan Hart4f397e82015-02-04 09:10:41 -0800323
324 checkNotNull(key, ERROR_NULL_KEY);
325 checkNotNull(value, ERROR_NULL_VALUE);
326
Jonathan Hart5ec32ba2015-02-05 13:33:58 -0800327 Timestamp timestamp = clockService.getTimestamp(key, value);
Jonathan Hartdb3af892015-01-26 13:19:07 -0800328
329 if (putInternal(key, value, timestamp)) {
330 updates.add(new PutEntry<>(key, value, timestamp));
331 }
332 }
333
Jonathan Hart584d2f32015-01-27 19:46:14 -0800334 if (!updates.isEmpty()) {
335 notifyPeers(new InternalPutEvent<>(updates));
Jonathan Hartdb3af892015-01-26 13:19:07 -0800336
Jonathan Hart584d2f32015-01-27 19:46:14 -0800337 for (PutEntry<K, V> entry : updates) {
Jonathan Hart5ec32ba2015-02-05 13:33:58 -0800338 EventuallyConsistentMapEvent<K, V> externalEvent =
339 new EventuallyConsistentMapEvent<>(
Jonathan Hart584d2f32015-01-27 19:46:14 -0800340 EventuallyConsistentMapEvent.Type.PUT, entry.key(),
341 entry.value());
342 notifyListeners(externalEvent);
343 }
Jonathan Hartdb3af892015-01-26 13:19:07 -0800344 }
345 }
346
347 @Override
348 public void clear() {
Jonathan Hart539a6462015-01-27 17:05:43 -0800349 checkState(!destroyed, mapName + ERROR_DESTROYED);
Jonathan Hartdb3af892015-01-26 13:19:07 -0800350
351 List<RemoveEntry<K>> removed = new ArrayList<>(items.size());
352
353 for (K key : items.keySet()) {
Jonathan Hart5ec32ba2015-02-05 13:33:58 -0800354 // TODO also this is not applicable if value is important for timestamp?
355 Timestamp timestamp = clockService.getTimestamp(key, null);
Jonathan Hartdb3af892015-01-26 13:19:07 -0800356
357 if (removeInternal(key, timestamp)) {
358 removed.add(new RemoveEntry<>(key, timestamp));
359 }
360 }
361
Jonathan Hart584d2f32015-01-27 19:46:14 -0800362 if (!removed.isEmpty()) {
363 notifyPeers(new InternalRemoveEvent<>(removed));
Jonathan Hartdb3af892015-01-26 13:19:07 -0800364
Jonathan Hart584d2f32015-01-27 19:46:14 -0800365 for (RemoveEntry<K> entry : removed) {
366 EventuallyConsistentMapEvent<K, V> externalEvent
367 = new EventuallyConsistentMapEvent<>(
368 EventuallyConsistentMapEvent.Type.REMOVE, entry.key(),
369 null);
370 notifyListeners(externalEvent);
371 }
Jonathan Hartdb3af892015-01-26 13:19:07 -0800372 }
373 }
374
375 @Override
376 public Set<K> keySet() {
Jonathan Hart539a6462015-01-27 17:05:43 -0800377 checkState(!destroyed, mapName + ERROR_DESTROYED);
Jonathan Hartdb3af892015-01-26 13:19:07 -0800378
379 return items.keySet();
380 }
381
382 @Override
383 public Collection<V> values() {
Jonathan Hart539a6462015-01-27 17:05:43 -0800384 checkState(!destroyed, mapName + ERROR_DESTROYED);
Jonathan Hartdb3af892015-01-26 13:19:07 -0800385
386 return items.values().stream()
387 .map(Timestamped::value)
388 .collect(Collectors.toList());
389 }
390
391 @Override
392 public Set<Map.Entry<K, V>> entrySet() {
Jonathan Hart539a6462015-01-27 17:05:43 -0800393 checkState(!destroyed, mapName + ERROR_DESTROYED);
Jonathan Hartdb3af892015-01-26 13:19:07 -0800394
395 return items.entrySet().stream()
Jonathan Hartf9108232015-02-02 16:37:35 -0800396 .map(e -> Pair.of(e.getKey(), e.getValue().value()))
Jonathan Hartdb3af892015-01-26 13:19:07 -0800397 .collect(Collectors.toSet());
398 }
399
400 @Override
Jonathan Hart539a6462015-01-27 17:05:43 -0800401 public void addListener(EventuallyConsistentMapListener<K, V> listener) {
402 checkState(!destroyed, mapName + ERROR_DESTROYED);
Jonathan Hartdb3af892015-01-26 13:19:07 -0800403
404 listeners.add(checkNotNull(listener));
405 }
406
407 @Override
Jonathan Hart539a6462015-01-27 17:05:43 -0800408 public void removeListener(EventuallyConsistentMapListener<K, V> listener) {
409 checkState(!destroyed, mapName + ERROR_DESTROYED);
Jonathan Hartdb3af892015-01-26 13:19:07 -0800410
411 listeners.remove(checkNotNull(listener));
412 }
413
414 @Override
415 public void destroy() {
416 destroyed = true;
417
418 executor.shutdown();
419 backgroundExecutor.shutdown();
420
Jonathan Hart584d2f32015-01-27 19:46:14 -0800421 listeners.clear();
422
Jonathan Hartdb3af892015-01-26 13:19:07 -0800423 clusterCommunicator.removeSubscriber(updateMessageSubject);
424 clusterCommunicator.removeSubscriber(removeMessageSubject);
Jonathan Hart584d2f32015-01-27 19:46:14 -0800425 clusterCommunicator.removeSubscriber(antiEntropyAdvertisementSubject);
Jonathan Hartdb3af892015-01-26 13:19:07 -0800426 }
427
Jonathan Hartaaa56572015-01-28 21:56:35 -0800428 private void notifyListeners(EventuallyConsistentMapEvent<K, V> event) {
429 for (EventuallyConsistentMapListener<K, V> listener : listeners) {
Jonathan Hartdb3af892015-01-26 13:19:07 -0800430 listener.event(event);
431 }
432 }
433
434 private void notifyPeers(InternalPutEvent event) {
Jonathan Hart7d656f42015-01-27 14:07:23 -0800435 broadcastMessage(updateMessageSubject, event);
Jonathan Hartdb3af892015-01-26 13:19:07 -0800436 }
437
438 private void notifyPeers(InternalRemoveEvent event) {
Jonathan Hart7d656f42015-01-27 14:07:23 -0800439 broadcastMessage(removeMessageSubject, event);
Jonathan Hartdb3af892015-01-26 13:19:07 -0800440 }
441
Jonathan Hart7d656f42015-01-27 14:07:23 -0800442 private void broadcastMessage(MessageSubject subject, Object event) {
Jonathan Hartdb3af892015-01-26 13:19:07 -0800443 ClusterMessage message = new ClusterMessage(
444 clusterService.getLocalNode().id(),
445 subject,
446 serializer.encode(event));
Madan Jampani28726282015-02-19 11:40:23 -0800447 broadcastMessageExecutor.execute(() -> clusterCommunicator.broadcast(message));
Jonathan Hartdb3af892015-01-26 13:19:07 -0800448 }
449
450 private void unicastMessage(NodeId peer,
451 MessageSubject subject,
452 Object event) throws IOException {
453 ClusterMessage message = new ClusterMessage(
454 clusterService.getLocalNode().id(),
455 subject,
456 serializer.encode(event));
457 clusterCommunicator.unicast(message, peer);
458 }
459
Jonathan Hartaaa56572015-01-28 21:56:35 -0800460 private final class SendAdvertisementTask implements Runnable {
461 @Override
462 public void run() {
463 if (Thread.currentThread().isInterrupted()) {
464 log.info("Interrupted, quitting");
465 return;
466 }
467
468 try {
469 final NodeId self = clusterService.getLocalNode().id();
470 Set<ControllerNode> nodes = clusterService.getNodes();
471
472 List<NodeId> nodeIds = nodes.stream()
473 .map(node -> node.id())
474 .collect(Collectors.toList());
475
476 if (nodeIds.size() == 1 && nodeIds.get(0).equals(self)) {
477 log.trace("No other peers in the cluster.");
478 return;
479 }
480
481 NodeId peer;
482 do {
483 int idx = RandomUtils.nextInt(0, nodeIds.size());
484 peer = nodeIds.get(idx);
485 } while (peer.equals(self));
486
487 if (Thread.currentThread().isInterrupted()) {
488 log.info("Interrupted, quitting");
489 return;
490 }
491
492 AntiEntropyAdvertisement<K> ad = createAdvertisement();
493
494 try {
495 unicastMessage(peer, antiEntropyAdvertisementSubject, ad);
496 } catch (IOException e) {
497 log.debug("Failed to send anti-entropy advertisement to {}", peer);
498 }
499 } catch (Exception e) {
500 // Catch all exceptions to avoid scheduled task being suppressed.
501 log.error("Exception thrown while sending advertisement", e);
502 }
503 }
504 }
505
506 private AntiEntropyAdvertisement<K> createAdvertisement() {
507 final NodeId self = clusterService.getLocalNode().id();
508
509 Map<K, Timestamp> timestamps = new HashMap<>(items.size());
510
511 items.forEach((key, value) -> timestamps.put(key, value.timestamp()));
512
513 Map<K, Timestamp> tombstones = new HashMap<>(removedItems);
514
515 return new AntiEntropyAdvertisement<>(self, timestamps, tombstones);
516 }
517
518 private void handleAntiEntropyAdvertisement(AntiEntropyAdvertisement<K> ad) {
519 List<EventuallyConsistentMapEvent<K, V>> externalEvents;
520
521 synchronized (this) {
522 final NodeId sender = ad.sender();
523
524 externalEvents = antiEntropyCheckLocalItems(ad);
525
526 antiEntropyCheckLocalRemoved(ad);
527
528 externalEvents.addAll(antiEntropyCheckRemoteRemoved(ad));
529
530 // if remote ad has something unknown, actively sync
531 for (K key : ad.timestamps().keySet()) {
532 if (!items.containsKey(key)) {
533 AntiEntropyAdvertisement<K> myAd = createAdvertisement();
534 try {
535 unicastMessage(sender, antiEntropyAdvertisementSubject,
536 myAd);
537 break;
538 } catch (IOException e) {
539 log.debug(
540 "Failed to send reactive anti-entropy advertisement to {}",
541 sender);
542 }
543 }
544 }
545 } // synchronized (this)
546
547 externalEvents.forEach(this::notifyListeners);
548 }
549
550 /**
551 * Checks if any of the remote's live items or tombstones are out of date
552 * according to our local live item list, or if our live items are out of
553 * date according to the remote's tombstone list.
554 * If the local copy is more recent, it will be pushed to the remote. If the
555 * remote has a more recent remove, we apply that to the local state.
556 *
557 * @param ad remote anti-entropy advertisement
558 * @return list of external events relating to local operations performed
559 */
560 // Guarded by synchronized (this)
561 private List<EventuallyConsistentMapEvent<K, V>> antiEntropyCheckLocalItems(
562 AntiEntropyAdvertisement<K> ad) {
563 final List<EventuallyConsistentMapEvent<K, V>> externalEvents
564 = new LinkedList<>();
565 final NodeId sender = ad.sender();
566
567 final List<PutEntry<K, V>> updatesToSend = new ArrayList<>();
568
569 for (Map.Entry<K, Timestamped<V>> item : items.entrySet()) {
570 K key = item.getKey();
571 Timestamped<V> localValue = item.getValue();
572
573 Timestamp remoteTimestamp = ad.timestamps().get(key);
574 if (remoteTimestamp == null) {
575 remoteTimestamp = ad.tombstones().get(key);
576 }
577 if (remoteTimestamp == null || localValue
578 .isNewer(remoteTimestamp)) {
579 // local value is more recent, push to sender
580 updatesToSend
581 .add(new PutEntry<>(key, localValue.value(),
582 localValue.timestamp()));
583 }
584
585 Timestamp remoteDeadTimestamp = ad.tombstones().get(key);
586 if (remoteDeadTimestamp != null &&
587 remoteDeadTimestamp.compareTo(localValue.timestamp()) > 0) {
588 // sender has a more recent remove
589 if (removeInternal(key, remoteDeadTimestamp)) {
590 externalEvents.add(new EventuallyConsistentMapEvent<>(
591 EventuallyConsistentMapEvent.Type.REMOVE, key, null));
592 }
593 }
594 }
595
596 // Send all updates to the peer at once
597 if (!updatesToSend.isEmpty()) {
598 try {
Jonathan Hart5ec32ba2015-02-05 13:33:58 -0800599 unicastMessage(sender, updateMessageSubject,
600 new InternalPutEvent<>(updatesToSend));
Jonathan Hartaaa56572015-01-28 21:56:35 -0800601 } catch (IOException e) {
602 log.warn("Failed to send advertisement response", e);
603 }
604 }
605
606 return externalEvents;
607 }
608
609 /**
610 * Checks if any items in the remote live list are out of date according
611 * to our tombstone list. If we find we have a more up to date tombstone,
612 * we'll send it to the remote.
613 *
614 * @param ad remote anti-entropy advertisement
615 */
616 // Guarded by synchronized (this)
617 private void antiEntropyCheckLocalRemoved(AntiEntropyAdvertisement<K> ad) {
618 final NodeId sender = ad.sender();
619
620 final List<RemoveEntry<K>> removesToSend = new ArrayList<>();
621
622 for (Map.Entry<K, Timestamp> dead : removedItems.entrySet()) {
623 K key = dead.getKey();
624 Timestamp localDeadTimestamp = dead.getValue();
625
626 Timestamp remoteLiveTimestamp = ad.timestamps().get(key);
627 if (remoteLiveTimestamp != null
628 && localDeadTimestamp.compareTo(remoteLiveTimestamp) > 0) {
629 // sender has zombie, push remove
630 removesToSend
631 .add(new RemoveEntry<>(key, localDeadTimestamp));
632 }
633 }
634
635 // Send all removes to the peer at once
636 if (!removesToSend.isEmpty()) {
637 try {
Jonathan Hart5ec32ba2015-02-05 13:33:58 -0800638 unicastMessage(sender, removeMessageSubject,
639 new InternalRemoveEvent<>(removesToSend));
Jonathan Hartaaa56572015-01-28 21:56:35 -0800640 } catch (IOException e) {
641 log.warn("Failed to send advertisement response", e);
642 }
643 }
644 }
645
646 /**
647 * Checks if any of the local live items are out of date according to the
648 * remote's tombstone advertisements. If we find a local item is out of date,
649 * we'll apply the remove operation to the local state.
650 *
651 * @param ad remote anti-entropy advertisement
652 * @return list of external events relating to local operations performed
653 */
654 // Guarded by synchronized (this)
655 private List<EventuallyConsistentMapEvent<K, V>>
656 antiEntropyCheckRemoteRemoved(AntiEntropyAdvertisement<K> ad) {
657 final List<EventuallyConsistentMapEvent<K, V>> externalEvents
658 = new LinkedList<>();
659
660 for (Map.Entry<K, Timestamp> remoteDead : ad.tombstones().entrySet()) {
661 K key = remoteDead.getKey();
662 Timestamp remoteDeadTimestamp = remoteDead.getValue();
663
664 Timestamped<V> local = items.get(key);
665 Timestamp localDead = removedItems.get(key);
666 if (local != null
667 && remoteDeadTimestamp.compareTo(local.timestamp()) > 0) {
668 // remove our version
669 if (removeInternal(key, remoteDeadTimestamp)) {
670 externalEvents.add(new EventuallyConsistentMapEvent<>(
671 EventuallyConsistentMapEvent.Type.REMOVE, key, null));
672 }
673 } else if (localDead != null &&
674 remoteDeadTimestamp.compareTo(localDead) > 0) {
675 // If we both had the item as removed, but their timestamp is
676 // newer, update ours to the newer value
677 removedItems.put(key, remoteDeadTimestamp);
678 }
679 }
680
681 return externalEvents;
682 }
683
684 private final class InternalAntiEntropyListener
685 implements ClusterMessageHandler {
686
687 @Override
688 public void handle(ClusterMessage message) {
Jonathan Hart4fd4ebb2015-02-04 17:38:48 -0800689 log.trace("Received anti-entropy advertisement from peer: {}",
690 message.sender());
Jonathan Hartaaa56572015-01-28 21:56:35 -0800691 AntiEntropyAdvertisement<K> advertisement = serializer.decode(message.payload());
692 backgroundExecutor.submit(() -> {
693 try {
694 handleAntiEntropyAdvertisement(advertisement);
695 } catch (Exception e) {
696 log.warn("Exception thrown handling advertisements", e);
697 }
698 });
699 }
700 }
701
Jonathan Hartdb3af892015-01-26 13:19:07 -0800702 private final class InternalPutEventListener implements
703 ClusterMessageHandler {
704 @Override
705 public void handle(ClusterMessage message) {
706 log.debug("Received put event from peer: {}", message.sender());
707 InternalPutEvent<K, V> event = serializer.decode(message.payload());
708
709 executor.submit(() -> {
710 try {
711 for (PutEntry<K, V> entry : event.entries()) {
712 K key = entry.key();
713 V value = entry.value();
714 Timestamp timestamp = entry.timestamp();
715
716 if (putInternal(key, value, timestamp)) {
Jonathan Hartaaa56572015-01-28 21:56:35 -0800717 EventuallyConsistentMapEvent<K, V> externalEvent =
Jonathan Hartdb3af892015-01-26 13:19:07 -0800718 new EventuallyConsistentMapEvent<>(
719 EventuallyConsistentMapEvent.Type.PUT, key,
720 value);
721 notifyListeners(externalEvent);
722 }
723 }
724 } catch (Exception e) {
725 log.warn("Exception thrown handling put", e);
726 }
727 });
728 }
729 }
730
731 private final class InternalRemoveEventListener implements
732 ClusterMessageHandler {
733 @Override
734 public void handle(ClusterMessage message) {
735 log.debug("Received remove event from peer: {}", message.sender());
736 InternalRemoveEvent<K> event = serializer.decode(message.payload());
737
738 executor.submit(() -> {
739 try {
740 for (RemoveEntry<K> entry : event.entries()) {
741 K key = entry.key();
742 Timestamp timestamp = entry.timestamp();
743
744 if (removeInternal(key, timestamp)) {
Jonathan Hartaaa56572015-01-28 21:56:35 -0800745 EventuallyConsistentMapEvent<K, V> externalEvent
746 = new EventuallyConsistentMapEvent<>(
Jonathan Hartdb3af892015-01-26 13:19:07 -0800747 EventuallyConsistentMapEvent.Type.REMOVE,
748 key, null);
749 notifyListeners(externalEvent);
750 }
751 }
752 } catch (Exception e) {
753 log.warn("Exception thrown handling remove", e);
754 }
755 });
756 }
757 }
758
Jonathan Hartdb3af892015-01-26 13:19:07 -0800759}