Jonathan Hart | db3af89 | 2015-01-26 13:19:07 -0800 | [diff] [blame] | 1 | /* |
Thomas Vachuska | b6d3167 | 2018-07-27 17:03:46 -0700 | [diff] [blame] | 2 | * Copyright 2018-present Open Networking Foundation |
Jonathan Hart | db3af89 | 2015-01-26 13:19:07 -0800 | [diff] [blame] | 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 | */ |
Thomas Vachuska | b6d3167 | 2018-07-27 17:03:46 -0700 | [diff] [blame] | 16 | package org.onosproject.store.atomix.primitives.impl; |
Jonathan Hart | db3af89 | 2015-01-26 13:19:07 -0800 | [diff] [blame] | 17 | |
Jordan Halterman | 00e92da | 2018-05-22 23:05:52 -0700 | [diff] [blame] | 18 | import java.util.ArrayList; |
| 19 | import java.util.Collection; |
| 20 | import java.util.Collections; |
| 21 | import java.util.HashSet; |
| 22 | import java.util.List; |
| 23 | import java.util.Map; |
| 24 | import java.util.Objects; |
| 25 | import java.util.Optional; |
| 26 | import java.util.Set; |
| 27 | import java.util.Timer; |
| 28 | import java.util.concurrent.CompletableFuture; |
| 29 | import java.util.concurrent.ExecutionException; |
| 30 | import java.util.concurrent.ExecutorService; |
| 31 | import java.util.concurrent.Executors; |
| 32 | import java.util.concurrent.ScheduledExecutorService; |
| 33 | import java.util.concurrent.TimeUnit; |
| 34 | import java.util.concurrent.TimeoutException; |
| 35 | import java.util.concurrent.atomic.AtomicBoolean; |
| 36 | import java.util.concurrent.atomic.AtomicInteger; |
| 37 | import java.util.concurrent.atomic.AtomicReference; |
| 38 | import java.util.function.BiFunction; |
| 39 | import java.util.function.Function; |
| 40 | import java.util.function.Supplier; |
| 41 | import java.util.stream.Collectors; |
| 42 | |
slowr | 878625f | 2017-10-24 14:53:49 -0700 | [diff] [blame] | 43 | import com.google.common.collect.Collections2; |
| 44 | import com.google.common.collect.ImmutableList; |
| 45 | import com.google.common.collect.ImmutableMap; |
| 46 | import com.google.common.collect.Lists; |
| 47 | import com.google.common.collect.Maps; |
| 48 | import com.google.common.collect.Sets; |
| 49 | import org.apache.commons.lang3.exception.ExceptionUtils; |
| 50 | import org.apache.commons.lang3.tuple.Pair; |
| 51 | import org.onlab.util.AbstractAccumulator; |
| 52 | import org.onlab.util.KryoNamespace; |
| 53 | import org.onlab.util.SlidingWindowCounter; |
| 54 | import org.onosproject.cluster.NodeId; |
| 55 | import org.onosproject.persistence.PersistenceService; |
| 56 | import org.onosproject.store.LogicalTimestamp; |
| 57 | import org.onosproject.store.Timestamp; |
| 58 | import org.onosproject.store.cluster.messaging.ClusterCommunicationService; |
| 59 | import org.onosproject.store.cluster.messaging.MessageSubject; |
| 60 | import org.onosproject.store.serializers.KryoNamespaces; |
| 61 | import org.onosproject.store.service.DistributedPrimitive; |
| 62 | import org.onosproject.store.service.EventuallyConsistentMap; |
| 63 | import org.onosproject.store.service.EventuallyConsistentMapEvent; |
| 64 | import org.onosproject.store.service.EventuallyConsistentMapListener; |
| 65 | import org.onosproject.store.service.Serializer; |
| 66 | import org.onosproject.store.service.WallClockTimestamp; |
| 67 | import org.slf4j.Logger; |
| 68 | import org.slf4j.LoggerFactory; |
| 69 | |
Jonathan Hart | 9dc5f09 | 2016-06-17 15:15:17 -0700 | [diff] [blame] | 70 | import static com.google.common.base.Preconditions.checkNotNull; |
| 71 | import static com.google.common.base.Preconditions.checkState; |
| 72 | import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor; |
| 73 | import static org.onlab.util.BoundedThreadPool.newFixedThreadPool; |
| 74 | import static org.onlab.util.Tools.groupedThreads; |
| 75 | import static org.onosproject.store.service.EventuallyConsistentMapEvent.Type.PUT; |
| 76 | import static org.onosproject.store.service.EventuallyConsistentMapEvent.Type.REMOVE; |
Jonathan Hart | db3af89 | 2015-01-26 13:19:07 -0800 | [diff] [blame] | 77 | |
| 78 | /** |
| 79 | * Distributed Map implementation which uses optimistic replication and gossip |
| 80 | * based techniques to provide an eventually consistent data store. |
| 81 | */ |
| 82 | public class EventuallyConsistentMapImpl<K, V> |
| 83 | implements EventuallyConsistentMap<K, V> { |
| 84 | |
| 85 | private static final Logger log = LoggerFactory.getLogger(EventuallyConsistentMapImpl.class); |
slowr | 878625f | 2017-10-24 14:53:49 -0700 | [diff] [blame] | 86 | private static final String ERROR_DESTROYED = " map is already destroyed"; |
| 87 | private static final String ERROR_NULL_KEY = "Key cannot be null"; |
| 88 | private static final String ERROR_NULL_VALUE = "Null values are not allowed"; |
| 89 | private static final int WINDOW_SIZE = 5; |
| 90 | private static final int HIGH_LOAD_THRESHOLD = 2; |
| 91 | private static final int LOAD_WINDOW = 2; |
Jonathan Hart | db3af89 | 2015-01-26 13:19:07 -0800 | [diff] [blame] | 92 | |
Madan Jampani | 3d76c94 | 2015-06-29 23:37:10 -0700 | [diff] [blame] | 93 | private final Map<K, MapValue<V>> items; |
Jordan Halterman | 28183ee | 2017-10-17 17:29:10 -0700 | [diff] [blame] | 94 | private final ClusterCommunicationService clusterCommunicator; |
Jordan Halterman | 2c83a10 | 2017-08-20 17:11:41 -0700 | [diff] [blame] | 95 | private final Serializer serializer; |
Aaron Kruglikov | 66cf0b9 | 2015-10-26 15:46:54 -0700 | [diff] [blame] | 96 | private final PersistenceService persistenceService; |
Madan Jampani | bcf1a48 | 2015-06-24 19:05:56 -0700 | [diff] [blame] | 97 | private final BiFunction<K, V, Timestamp> timestampProvider; |
Jordan Halterman | 12d5ec4 | 2017-05-17 00:53:44 -0700 | [diff] [blame] | 98 | private final MessageSubject bootstrapMessageSubject; |
| 99 | private final MessageSubject initializeMessageSubject; |
Jonathan Hart | db3af89 | 2015-01-26 13:19:07 -0800 | [diff] [blame] | 100 | private final MessageSubject updateMessageSubject; |
Jonathan Hart | aaa5657 | 2015-01-28 21:56:35 -0800 | [diff] [blame] | 101 | private final MessageSubject antiEntropyAdvertisementSubject; |
Jon Hall | d198b88 | 2016-05-18 16:44:40 -0700 | [diff] [blame] | 102 | private final MessageSubject updateRequestSubject; |
Jonathan Hart | aaa5657 | 2015-01-28 21:56:35 -0800 | [diff] [blame] | 103 | private final Set<EventuallyConsistentMapListener<K, V>> listeners |
Madan Jampani | 3d76c94 | 2015-06-29 23:37:10 -0700 | [diff] [blame] | 104 | = Sets.newCopyOnWriteArraySet(); |
Jonathan Hart | db3af89 | 2015-01-26 13:19:07 -0800 | [diff] [blame] | 105 | private final ExecutorService executor; |
Jonathan Hart | db3af89 | 2015-01-26 13:19:07 -0800 | [diff] [blame] | 106 | private final ScheduledExecutorService backgroundExecutor; |
Brian O'Connor | eeaea2c | 2015-03-05 16:24:34 -0800 | [diff] [blame] | 107 | private final BiFunction<K, V, Collection<NodeId>> peerUpdateFunction; |
Jonathan Hart | 6ec029a | 2015-03-24 17:12:35 -0700 | [diff] [blame] | 108 | private final ExecutorService communicationExecutor; |
| 109 | private final Map<NodeId, EventAccumulator> senderPending; |
Madan Jampani | 29f52a3 | 2016-04-18 15:20:52 -0700 | [diff] [blame] | 110 | private final Map<NodeId, Long> antiEntropyTimes = Maps.newConcurrentMap(); |
Madan Jampani | 4f1f4cd | 2015-07-08 23:05:35 -0700 | [diff] [blame] | 111 | private final String mapName; |
Thomas Vachuska | a132e3a | 2015-02-21 01:53:14 -0800 | [diff] [blame] | 112 | private final String destroyedMessage; |
Jonathan Hart | 6ec029a | 2015-03-24 17:12:35 -0700 | [diff] [blame] | 113 | private final long initialDelaySec = 5; |
| 114 | private final boolean lightweightAntiEntropy; |
| 115 | private final boolean tombstonesDisabled; |
Jonathan Hart | ca335e9 | 2015-03-05 10:34:32 -0800 | [diff] [blame] | 116 | private final boolean persistent; |
slowr | 878625f | 2017-10-24 14:53:49 -0700 | [diff] [blame] | 117 | private final Supplier<List<NodeId>> peersSupplier; |
| 118 | private final Supplier<List<NodeId>> bootstrapPeersSupplier; |
| 119 | private final NodeId localNodeId; |
| 120 | private long previousTombstonePurgeTime; |
| 121 | private volatile boolean destroyed = false; |
| 122 | private SlidingWindowCounter counter = new SlidingWindowCounter(WINDOW_SIZE); |
Aaron Kruglikov | 66cf0b9 | 2015-10-26 15:46:54 -0700 | [diff] [blame] | 123 | |
Jonathan Hart | db3af89 | 2015-01-26 13:19:07 -0800 | [diff] [blame] | 124 | /** |
| 125 | * Creates a new eventually consistent map shared amongst multiple instances. |
Thomas Vachuska | a132e3a | 2015-02-21 01:53:14 -0800 | [diff] [blame] | 126 | * <p> |
Jonathan Hart | 6ec029a | 2015-03-24 17:12:35 -0700 | [diff] [blame] | 127 | * See {@link org.onosproject.store.service.EventuallyConsistentMapBuilder} |
| 128 | * for more description of the parameters expected by the map. |
Thomas Vachuska | a132e3a | 2015-02-21 01:53:14 -0800 | [diff] [blame] | 129 | * </p> |
Jonathan Hart | db3af89 | 2015-01-26 13:19:07 -0800 | [diff] [blame] | 130 | * |
slowr | 878625f | 2017-10-24 14:53:49 -0700 | [diff] [blame] | 131 | * @param localNodeId local node id |
| 132 | * @param mapName a String identifier for the map. |
| 133 | * @param clusterCommunicator the cluster communications service |
| 134 | * @param ns a Kryo namespace that can serialize both K and V |
| 135 | * @param timestampProvider provider of timestamps for K and V |
| 136 | * @param peerUpdateFunction function that provides a set of nodes to immediately |
| 137 | * update to when there writes to the map |
| 138 | * @param eventExecutor executor to use for processing incoming events from peers |
| 139 | * @param communicationExecutor executor to use for sending events to peers |
| 140 | * @param backgroundExecutor executor to use for background anti-entropy tasks |
| 141 | * @param tombstonesDisabled true if this map should not maintain tombstones |
| 142 | * @param antiEntropyPeriod period that the anti-entropy task should run |
| 143 | * @param antiEntropyTimeUnit time unit for anti-entropy period |
| 144 | * @param convergeFaster make anti-entropy try to converge faster |
| 145 | * @param persistent persist data to disk |
| 146 | * @param persistenceService persistence service |
| 147 | * @param peersSupplier supplier for peers |
| 148 | * @param bootstrapPeersSupplier supplier for bootstrap peers |
Jonathan Hart | db3af89 | 2015-01-26 13:19:07 -0800 | [diff] [blame] | 149 | */ |
slowr | 878625f | 2017-10-24 14:53:49 -0700 | [diff] [blame] | 150 | //CHECKSTYLE:OFF |
| 151 | EventuallyConsistentMapImpl( |
| 152 | NodeId localNodeId, |
| 153 | String mapName, |
| 154 | ClusterCommunicationService clusterCommunicator, |
| 155 | KryoNamespace ns, |
| 156 | BiFunction<K, V, Timestamp> timestampProvider, |
| 157 | BiFunction<K, V, Collection<NodeId>> peerUpdateFunction, |
| 158 | ExecutorService eventExecutor, |
| 159 | ExecutorService communicationExecutor, |
| 160 | ScheduledExecutorService backgroundExecutor, |
| 161 | boolean tombstonesDisabled, |
| 162 | long antiEntropyPeriod, |
| 163 | TimeUnit antiEntropyTimeUnit, |
| 164 | boolean convergeFaster, |
| 165 | boolean persistent, |
| 166 | PersistenceService persistenceService, |
| 167 | Supplier<List<NodeId>> peersSupplier, |
| 168 | Supplier<List<NodeId>> bootstrapPeersSupplier |
| 169 | ) { |
| 170 | //CHECKSTYLE:ON |
| 171 | this.localNodeId = localNodeId; |
Madan Jampani | 4f1f4cd | 2015-07-08 23:05:35 -0700 | [diff] [blame] | 172 | this.mapName = mapName; |
HIGUCHI Yuta | 163efb5 | 2016-05-18 19:24:19 -0700 | [diff] [blame] | 173 | this.serializer = createSerializer(ns); |
Aaron Kruglikov | 66cf0b9 | 2015-10-26 15:46:54 -0700 | [diff] [blame] | 174 | this.persistenceService = persistenceService; |
| 175 | this.persistent = |
| 176 | persistent; |
| 177 | if (persistent) { |
| 178 | items = this.persistenceService.<K, MapValue<V>>persistentMapBuilder() |
Aaron Kruglikov | 3721041 | 2016-12-06 12:55:57 -0800 | [diff] [blame] | 179 | .withName(mapName) |
HIGUCHI Yuta | 163efb5 | 2016-05-18 19:24:19 -0700 | [diff] [blame] | 180 | .withSerializer(this.serializer) |
Aaron Kruglikov | 66cf0b9 | 2015-10-26 15:46:54 -0700 | [diff] [blame] | 181 | .build(); |
| 182 | } else { |
| 183 | items = Maps.newConcurrentMap(); |
| 184 | } |
Brian O'Connor | eeaea2c | 2015-03-05 16:24:34 -0800 | [diff] [blame] | 185 | senderPending = Maps.newConcurrentMap(); |
Jonathan Hart | 6ec029a | 2015-03-24 17:12:35 -0700 | [diff] [blame] | 186 | destroyedMessage = mapName + ERROR_DESTROYED; |
Madan Jampani | 2872628 | 2015-02-19 11:40:23 -0800 | [diff] [blame] | 187 | |
Jonathan Hart | 6ec029a | 2015-03-24 17:12:35 -0700 | [diff] [blame] | 188 | this.clusterCommunicator = clusterCommunicator; |
| 189 | |
Madan Jampani | bcf1a48 | 2015-06-24 19:05:56 -0700 | [diff] [blame] | 190 | this.timestampProvider = timestampProvider; |
Jonathan Hart | 6ec029a | 2015-03-24 17:12:35 -0700 | [diff] [blame] | 191 | |
slowr | 878625f | 2017-10-24 14:53:49 -0700 | [diff] [blame] | 192 | this.peersSupplier = peersSupplier; |
| 193 | this.bootstrapPeersSupplier = bootstrapPeersSupplier; |
| 194 | |
Jonathan Hart | 6ec029a | 2015-03-24 17:12:35 -0700 | [diff] [blame] | 195 | if (peerUpdateFunction != null) { |
slowr | 878625f | 2017-10-24 14:53:49 -0700 | [diff] [blame] | 196 | this.peerUpdateFunction = peerUpdateFunction.andThen(peers -> peersSupplier.get() |
| 197 | .stream() |
| 198 | .filter(peers::contains) |
| 199 | .collect(Collectors.toList())); |
Jonathan Hart | 6ec029a | 2015-03-24 17:12:35 -0700 | [diff] [blame] | 200 | } else { |
slowr | 878625f | 2017-10-24 14:53:49 -0700 | [diff] [blame] | 201 | this.peerUpdateFunction = (key, value) -> peersSupplier.get(); |
Jonathan Hart | 6ec029a | 2015-03-24 17:12:35 -0700 | [diff] [blame] | 202 | } |
| 203 | |
| 204 | if (eventExecutor != null) { |
| 205 | this.executor = eventExecutor; |
| 206 | } else { |
| 207 | // should be a normal executor; it's used for receiving messages |
| 208 | this.executor = |
slowr | 878625f | 2017-10-24 14:53:49 -0700 | [diff] [blame] | 209 | Executors.newFixedThreadPool(8, |
| 210 | groupedThreads("onos/ecm", mapName + "-fg-%d", log)); |
Jonathan Hart | 6ec029a | 2015-03-24 17:12:35 -0700 | [diff] [blame] | 211 | } |
| 212 | |
| 213 | if (communicationExecutor != null) { |
| 214 | this.communicationExecutor = communicationExecutor; |
| 215 | } else { |
| 216 | // sending executor; should be capped |
| 217 | //TODO this probably doesn't need to be bounded anymore |
| 218 | this.communicationExecutor = |
slowr | 878625f | 2017-10-24 14:53:49 -0700 | [diff] [blame] | 219 | newFixedThreadPool(8, |
| 220 | groupedThreads("onos/ecm", mapName + "-publish-%d", log)); |
Jonathan Hart | 6ec029a | 2015-03-24 17:12:35 -0700 | [diff] [blame] | 221 | } |
| 222 | |
Jonathan Hart | ca335e9 | 2015-03-05 10:34:32 -0800 | [diff] [blame] | 223 | |
Jonathan Hart | 6ec029a | 2015-03-24 17:12:35 -0700 | [diff] [blame] | 224 | if (backgroundExecutor != null) { |
| 225 | this.backgroundExecutor = backgroundExecutor; |
| 226 | } else { |
| 227 | this.backgroundExecutor = |
slowr | 878625f | 2017-10-24 14:53:49 -0700 | [diff] [blame] | 228 | newSingleThreadScheduledExecutor( |
| 229 | groupedThreads("onos/ecm", mapName + "-bg-%d", log)); |
Jonathan Hart | 6ec029a | 2015-03-24 17:12:35 -0700 | [diff] [blame] | 230 | } |
Jonathan Hart | db3af89 | 2015-01-26 13:19:07 -0800 | [diff] [blame] | 231 | |
Jonathan Hart | aaa5657 | 2015-01-28 21:56:35 -0800 | [diff] [blame] | 232 | // start anti-entropy thread |
slowr | 878625f | 2017-10-24 14:53:49 -0700 | [diff] [blame] | 233 | this.backgroundExecutor.scheduleAtFixedRate( |
| 234 | this::sendAdvertisement, |
| 235 | initialDelaySec, antiEntropyPeriod, |
| 236 | antiEntropyTimeUnit |
| 237 | ); |
Jonathan Hart | aaa5657 | 2015-01-28 21:56:35 -0800 | [diff] [blame] | 238 | |
Jordan Halterman | 12d5ec4 | 2017-05-17 00:53:44 -0700 | [diff] [blame] | 239 | bootstrapMessageSubject = new MessageSubject("ecm-" + mapName + "-bootstrap"); |
slowr | 878625f | 2017-10-24 14:53:49 -0700 | [diff] [blame] | 240 | clusterCommunicator.addSubscriber( |
| 241 | bootstrapMessageSubject, |
| 242 | serializer::decode, |
| 243 | (Function<NodeId, CompletableFuture<Void>>) this::handleBootstrap, |
| 244 | serializer::encode |
| 245 | ); |
Jordan Halterman | 12d5ec4 | 2017-05-17 00:53:44 -0700 | [diff] [blame] | 246 | |
| 247 | initializeMessageSubject = new MessageSubject("ecm-" + mapName + "-initialize"); |
slowr | 878625f | 2017-10-24 14:53:49 -0700 | [diff] [blame] | 248 | clusterCommunicator.addSubscriber( |
| 249 | initializeMessageSubject, |
Jordan Halterman | 12d5ec4 | 2017-05-17 00:53:44 -0700 | [diff] [blame] | 250 | serializer::decode, |
| 251 | (Function<Collection<UpdateEntry<K, V>>, Void>) u -> { |
| 252 | processUpdates(u); |
| 253 | return null; |
| 254 | }, |
| 255 | serializer::encode, |
slowr | 878625f | 2017-10-24 14:53:49 -0700 | [diff] [blame] | 256 | this.executor |
| 257 | ); |
Jordan Halterman | 12d5ec4 | 2017-05-17 00:53:44 -0700 | [diff] [blame] | 258 | |
Jonathan Hart | db3af89 | 2015-01-26 13:19:07 -0800 | [diff] [blame] | 259 | updateMessageSubject = new MessageSubject("ecm-" + mapName + "-update"); |
slowr | 878625f | 2017-10-24 14:53:49 -0700 | [diff] [blame] | 260 | clusterCommunicator.addSubscriber( |
| 261 | updateMessageSubject, |
| 262 | serializer::decode, |
| 263 | this::processUpdates, |
| 264 | this.executor |
| 265 | ); |
Brian O'Connor | eeaea2c | 2015-03-05 16:24:34 -0800 | [diff] [blame] | 266 | |
Jonathan Hart | aaa5657 | 2015-01-28 21:56:35 -0800 | [diff] [blame] | 267 | antiEntropyAdvertisementSubject = new MessageSubject("ecm-" + mapName + "-anti-entropy"); |
slowr | 878625f | 2017-10-24 14:53:49 -0700 | [diff] [blame] | 268 | clusterCommunicator.addSubscriber( |
| 269 | antiEntropyAdvertisementSubject, |
| 270 | serializer::decode, |
| 271 | this::handleAntiEntropyAdvertisement, |
| 272 | serializer::encode, |
| 273 | this.backgroundExecutor |
| 274 | ); |
Jonathan Hart | db3af89 | 2015-01-26 13:19:07 -0800 | [diff] [blame] | 275 | |
Jon Hall | d198b88 | 2016-05-18 16:44:40 -0700 | [diff] [blame] | 276 | updateRequestSubject = new MessageSubject("ecm-" + mapName + "-update-request"); |
slowr | 878625f | 2017-10-24 14:53:49 -0700 | [diff] [blame] | 277 | clusterCommunicator.addSubscriber( |
| 278 | updateRequestSubject, |
| 279 | serializer::decode, |
| 280 | this::handleUpdateRequests, |
| 281 | this.backgroundExecutor |
| 282 | ); |
Jon Hall | d198b88 | 2016-05-18 16:44:40 -0700 | [diff] [blame] | 283 | |
Madan Jampani | a8f919e | 2016-04-18 16:47:35 -0700 | [diff] [blame] | 284 | if (!tombstonesDisabled) { |
| 285 | previousTombstonePurgeTime = 0; |
slowr | 878625f | 2017-10-24 14:53:49 -0700 | [diff] [blame] | 286 | this.backgroundExecutor.scheduleWithFixedDelay( |
| 287 | this::purgeTombstones, |
| 288 | initialDelaySec, |
| 289 | antiEntropyPeriod, |
| 290 | TimeUnit.SECONDS |
| 291 | ); |
Madan Jampani | a8f919e | 2016-04-18 16:47:35 -0700 | [diff] [blame] | 292 | } |
Madan Jampani | 29f52a3 | 2016-04-18 15:20:52 -0700 | [diff] [blame] | 293 | |
Jonathan Hart | 6ec029a | 2015-03-24 17:12:35 -0700 | [diff] [blame] | 294 | this.tombstonesDisabled = tombstonesDisabled; |
| 295 | this.lightweightAntiEntropy = !convergeFaster; |
Jon Hall | dabee68 | 2016-05-17 11:29:51 -0700 | [diff] [blame] | 296 | |
| 297 | // Initiate first round of Gossip |
| 298 | this.bootstrap(); |
Madan Jampani | e135628 | 2015-03-10 19:05:36 -0700 | [diff] [blame] | 299 | } |
| 300 | |
Jordan Halterman | 2c83a10 | 2017-08-20 17:11:41 -0700 | [diff] [blame] | 301 | private Serializer createSerializer(KryoNamespace ns) { |
| 302 | return Serializer.using(KryoNamespace.newBuilder() |
slowr | 878625f | 2017-10-24 14:53:49 -0700 | [diff] [blame] | 303 | .register(ns) |
| 304 | // not so robust way to avoid collision with other |
| 305 | // user supplied registrations |
| 306 | .nextId(KryoNamespaces.BEGIN_USER_CUSTOM_ID + 100) |
| 307 | .register(KryoNamespaces.BASIC) |
| 308 | .register(LogicalTimestamp.class) |
| 309 | .register(WallClockTimestamp.class) |
| 310 | .register(AntiEntropyAdvertisement.class) |
| 311 | .register(AntiEntropyResponse.class) |
| 312 | .register(UpdateEntry.class) |
| 313 | .register(MapValue.class) |
| 314 | .register(MapValue.Digest.class) |
| 315 | .register(UpdateRequest.class) |
| 316 | .build(name() + "-ecmap")); |
Jonathan Hart | db3af89 | 2015-01-26 13:19:07 -0800 | [diff] [blame] | 317 | } |
| 318 | |
| 319 | @Override |
Madan Jampani | a090a11 | 2016-01-18 16:38:17 -0800 | [diff] [blame] | 320 | public String name() { |
| 321 | return mapName; |
| 322 | } |
| 323 | |
| 324 | @Override |
Jonathan Hart | db3af89 | 2015-01-26 13:19:07 -0800 | [diff] [blame] | 325 | public int size() { |
Thomas Vachuska | a132e3a | 2015-02-21 01:53:14 -0800 | [diff] [blame] | 326 | checkState(!destroyed, destroyedMessage); |
Madan Jampani | 3d76c94 | 2015-06-29 23:37:10 -0700 | [diff] [blame] | 327 | // TODO: Maintain a separate counter for tracking live elements in map. |
| 328 | return Maps.filterValues(items, MapValue::isAlive).size(); |
Jonathan Hart | db3af89 | 2015-01-26 13:19:07 -0800 | [diff] [blame] | 329 | } |
| 330 | |
| 331 | @Override |
| 332 | public boolean isEmpty() { |
Thomas Vachuska | a132e3a | 2015-02-21 01:53:14 -0800 | [diff] [blame] | 333 | checkState(!destroyed, destroyedMessage); |
Madan Jampani | 3d76c94 | 2015-06-29 23:37:10 -0700 | [diff] [blame] | 334 | return size() == 0; |
Jonathan Hart | db3af89 | 2015-01-26 13:19:07 -0800 | [diff] [blame] | 335 | } |
| 336 | |
| 337 | @Override |
| 338 | public boolean containsKey(K key) { |
Thomas Vachuska | a132e3a | 2015-02-21 01:53:14 -0800 | [diff] [blame] | 339 | checkState(!destroyed, destroyedMessage); |
Jonathan Hart | 4f397e8 | 2015-02-04 09:10:41 -0800 | [diff] [blame] | 340 | checkNotNull(key, ERROR_NULL_KEY); |
Madan Jampani | 3d76c94 | 2015-06-29 23:37:10 -0700 | [diff] [blame] | 341 | return get(key) != null; |
Jonathan Hart | db3af89 | 2015-01-26 13:19:07 -0800 | [diff] [blame] | 342 | } |
| 343 | |
| 344 | @Override |
| 345 | public boolean containsValue(V value) { |
Thomas Vachuska | a132e3a | 2015-02-21 01:53:14 -0800 | [diff] [blame] | 346 | checkState(!destroyed, destroyedMessage); |
Jonathan Hart | 4f397e8 | 2015-02-04 09:10:41 -0800 | [diff] [blame] | 347 | checkNotNull(value, ERROR_NULL_VALUE); |
Madan Jampani | 3d76c94 | 2015-06-29 23:37:10 -0700 | [diff] [blame] | 348 | return items.values() |
slowr | 878625f | 2017-10-24 14:53:49 -0700 | [diff] [blame] | 349 | .stream() |
| 350 | .filter(MapValue::isAlive) |
| 351 | .anyMatch(v -> value.equals(v.get())); |
Jonathan Hart | db3af89 | 2015-01-26 13:19:07 -0800 | [diff] [blame] | 352 | } |
| 353 | |
| 354 | @Override |
| 355 | public V get(K key) { |
Thomas Vachuska | a132e3a | 2015-02-21 01:53:14 -0800 | [diff] [blame] | 356 | checkState(!destroyed, destroyedMessage); |
Jonathan Hart | 4f397e8 | 2015-02-04 09:10:41 -0800 | [diff] [blame] | 357 | checkNotNull(key, ERROR_NULL_KEY); |
Jonathan Hart | db3af89 | 2015-01-26 13:19:07 -0800 | [diff] [blame] | 358 | |
Madan Jampani | 3d76c94 | 2015-06-29 23:37:10 -0700 | [diff] [blame] | 359 | MapValue<V> value = items.get(key); |
| 360 | return (value == null || value.isTombstone()) ? null : value.get(); |
Jonathan Hart | db3af89 | 2015-01-26 13:19:07 -0800 | [diff] [blame] | 361 | } |
| 362 | |
| 363 | @Override |
| 364 | public void put(K key, V value) { |
Thomas Vachuska | a132e3a | 2015-02-21 01:53:14 -0800 | [diff] [blame] | 365 | checkState(!destroyed, destroyedMessage); |
Jonathan Hart | 4f397e8 | 2015-02-04 09:10:41 -0800 | [diff] [blame] | 366 | checkNotNull(key, ERROR_NULL_KEY); |
| 367 | checkNotNull(value, ERROR_NULL_VALUE); |
Jonathan Hart | db3af89 | 2015-01-26 13:19:07 -0800 | [diff] [blame] | 368 | |
Madan Jampani | 3d76c94 | 2015-06-29 23:37:10 -0700 | [diff] [blame] | 369 | MapValue<V> newValue = new MapValue<>(value, timestampProvider.apply(key, value)); |
Madan Jampani | 4f1f4cd | 2015-07-08 23:05:35 -0700 | [diff] [blame] | 370 | if (putInternal(key, newValue)) { |
HIGUCHI Yuta | e729065 | 2016-05-18 11:29:01 -0700 | [diff] [blame] | 371 | notifyPeers(new UpdateEntry<>(key, newValue), peerUpdateFunction.apply(key, value)); |
Madan Jampani | cab114c | 2015-07-23 00:14:19 -0700 | [diff] [blame] | 372 | notifyListeners(new EventuallyConsistentMapEvent<>(mapName, PUT, key, value)); |
Jonathan Hart | db3af89 | 2015-01-26 13:19:07 -0800 | [diff] [blame] | 373 | } |
| 374 | } |
| 375 | |
Jonathan Hart | db3af89 | 2015-01-26 13:19:07 -0800 | [diff] [blame] | 376 | @Override |
Madan Jampani | 43e9c9c | 2015-06-26 14:16:46 -0700 | [diff] [blame] | 377 | public V remove(K key) { |
Thomas Vachuska | a132e3a | 2015-02-21 01:53:14 -0800 | [diff] [blame] | 378 | checkState(!destroyed, destroyedMessage); |
Jonathan Hart | 4f397e8 | 2015-02-04 09:10:41 -0800 | [diff] [blame] | 379 | checkNotNull(key, ERROR_NULL_KEY); |
Madan Jampani | 4f1f4cd | 2015-07-08 23:05:35 -0700 | [diff] [blame] | 380 | return removeAndNotify(key, null); |
| 381 | } |
| 382 | |
| 383 | @Override |
| 384 | public void remove(K key, V value) { |
| 385 | checkState(!destroyed, destroyedMessage); |
| 386 | checkNotNull(key, ERROR_NULL_KEY); |
| 387 | checkNotNull(value, ERROR_NULL_VALUE); |
| 388 | removeAndNotify(key, value); |
| 389 | } |
| 390 | |
| 391 | private V removeAndNotify(K key, V value) { |
Madan Jampani | 483d0a2 | 2015-08-19 17:33:00 -0700 | [diff] [blame] | 392 | Timestamp timestamp = timestampProvider.apply(key, value); |
| 393 | Optional<MapValue<V>> tombstone = tombstonesDisabled || timestamp == null |
| 394 | ? Optional.empty() : Optional.of(MapValue.tombstone(timestamp)); |
Madan Jampani | 4f1f4cd | 2015-07-08 23:05:35 -0700 | [diff] [blame] | 395 | MapValue<V> previousValue = removeInternal(key, Optional.ofNullable(value), tombstone); |
Madan Jampani | a0ac487 | 2015-07-02 11:23:49 -0700 | [diff] [blame] | 396 | if (previousValue != null) { |
Madan Jampani | 483d0a2 | 2015-08-19 17:33:00 -0700 | [diff] [blame] | 397 | notifyPeers(new UpdateEntry<>(key, tombstone.orElse(null)), |
slowr | 878625f | 2017-10-24 14:53:49 -0700 | [diff] [blame] | 398 | peerUpdateFunction.apply(key, previousValue.get())); |
Madan Jampani | a0ac487 | 2015-07-02 11:23:49 -0700 | [diff] [blame] | 399 | if (previousValue.isAlive()) { |
Madan Jampani | cab114c | 2015-07-23 00:14:19 -0700 | [diff] [blame] | 400 | notifyListeners(new EventuallyConsistentMapEvent<>(mapName, REMOVE, key, previousValue.get())); |
Madan Jampani | a0ac487 | 2015-07-02 11:23:49 -0700 | [diff] [blame] | 401 | } |
| 402 | } |
Madan Jampani | d13f3b8 | 2015-07-01 17:37:50 -0700 | [diff] [blame] | 403 | return previousValue != null ? previousValue.get() : null; |
Jonathan Hart | db3af89 | 2015-01-26 13:19:07 -0800 | [diff] [blame] | 404 | } |
| 405 | |
Madan Jampani | 483d0a2 | 2015-08-19 17:33:00 -0700 | [diff] [blame] | 406 | private MapValue<V> removeInternal(K key, Optional<V> value, Optional<MapValue<V>> tombstone) { |
Madan Jampani | 3d76c94 | 2015-06-29 23:37:10 -0700 | [diff] [blame] | 407 | checkState(!destroyed, destroyedMessage); |
| 408 | checkNotNull(key, ERROR_NULL_KEY); |
| 409 | checkNotNull(value, ERROR_NULL_VALUE); |
Madan Jampani | 483d0a2 | 2015-08-19 17:33:00 -0700 | [diff] [blame] | 410 | tombstone.ifPresent(v -> checkState(v.isTombstone())); |
Madan Jampani | 4f1f4cd | 2015-07-08 23:05:35 -0700 | [diff] [blame] | 411 | |
| 412 | counter.incrementCount(); |
Madan Jampani | 3d76c94 | 2015-06-29 23:37:10 -0700 | [diff] [blame] | 413 | AtomicBoolean updated = new AtomicBoolean(false); |
Madan Jampani | d13f3b8 | 2015-07-01 17:37:50 -0700 | [diff] [blame] | 414 | AtomicReference<MapValue<V>> previousValue = new AtomicReference<>(); |
Madan Jampani | 3d76c94 | 2015-06-29 23:37:10 -0700 | [diff] [blame] | 415 | items.compute(key, (k, existing) -> { |
Madan Jampani | d13f3b8 | 2015-07-01 17:37:50 -0700 | [diff] [blame] | 416 | boolean valueMatches = true; |
| 417 | if (value.isPresent() && existing != null && existing.isAlive()) { |
| 418 | valueMatches = Objects.equals(value.get(), existing.get()); |
Madan Jampani | 3d76c94 | 2015-06-29 23:37:10 -0700 | [diff] [blame] | 419 | } |
Brian O'Connor | 6325dad | 2015-07-07 15:36:29 -0700 | [diff] [blame] | 420 | if (existing == null) { |
Jonathan Hart | 4a29c59 | 2015-09-23 17:55:07 -0700 | [diff] [blame] | 421 | log.trace("ECMap Remove: Existing value for key {} is already null", k); |
Brian O'Connor | 6325dad | 2015-07-07 15:36:29 -0700 | [diff] [blame] | 422 | } |
Madan Jampani | 483d0a2 | 2015-08-19 17:33:00 -0700 | [diff] [blame] | 423 | if (valueMatches) { |
| 424 | if (existing == null) { |
| 425 | updated.set(tombstone.isPresent()); |
| 426 | } else { |
| 427 | updated.set(!tombstone.isPresent() || tombstone.get().isNewerThan(existing)); |
| 428 | } |
Madan Jampani | d13f3b8 | 2015-07-01 17:37:50 -0700 | [diff] [blame] | 429 | } |
Madan Jampani | 4f1f4cd | 2015-07-08 23:05:35 -0700 | [diff] [blame] | 430 | if (updated.get()) { |
Madan Jampani | 483d0a2 | 2015-08-19 17:33:00 -0700 | [diff] [blame] | 431 | previousValue.set(existing); |
| 432 | return tombstone.orElse(null); |
Madan Jampani | 4f1f4cd | 2015-07-08 23:05:35 -0700 | [diff] [blame] | 433 | } else { |
| 434 | return existing; |
| 435 | } |
Madan Jampani | 3d76c94 | 2015-06-29 23:37:10 -0700 | [diff] [blame] | 436 | }); |
Madan Jampani | d13f3b8 | 2015-07-01 17:37:50 -0700 | [diff] [blame] | 437 | return previousValue.get(); |
Jonathan Hart | 5ec32ba | 2015-02-05 13:33:58 -0800 | [diff] [blame] | 438 | } |
| 439 | |
| 440 | @Override |
Madan Jampani | 4727a11 | 2015-07-16 12:12:58 -0700 | [diff] [blame] | 441 | public V compute(K key, BiFunction<K, V, V> recomputeFunction) { |
| 442 | checkState(!destroyed, destroyedMessage); |
| 443 | checkNotNull(key, ERROR_NULL_KEY); |
| 444 | checkNotNull(recomputeFunction, "Recompute function cannot be null"); |
| 445 | |
| 446 | AtomicBoolean updated = new AtomicBoolean(false); |
| 447 | AtomicReference<MapValue<V>> previousValue = new AtomicReference<>(); |
Madan Jampani | dc01297 | 2016-04-25 11:13:26 -0700 | [diff] [blame] | 448 | MapValue<V> computedValue = items.compute(serializer.copy(key), (k, mv) -> { |
Madan Jampani | 4727a11 | 2015-07-16 12:12:58 -0700 | [diff] [blame] | 449 | previousValue.set(mv); |
| 450 | V newRawValue = recomputeFunction.apply(key, mv == null ? null : mv.get()); |
Brian O'Connor | 05acd64 | 2016-08-03 00:42:35 -0700 | [diff] [blame] | 451 | if (mv != null && Objects.equals(newRawValue, mv.get())) { |
| 452 | // value was not updated |
| 453 | return mv; |
| 454 | } |
Madan Jampani | 4727a11 | 2015-07-16 12:12:58 -0700 | [diff] [blame] | 455 | MapValue<V> newValue = new MapValue<>(newRawValue, timestampProvider.apply(key, newRawValue)); |
| 456 | if (mv == null || newValue.isNewerThan(mv)) { |
| 457 | updated.set(true); |
Madan Jampani | dc01297 | 2016-04-25 11:13:26 -0700 | [diff] [blame] | 458 | // We return a copy to ensure updates to peers can be serialized. |
| 459 | // This prevents replica divergence due to serialization failures. |
| 460 | return serializer.copy(newValue); |
Madan Jampani | 4727a11 | 2015-07-16 12:12:58 -0700 | [diff] [blame] | 461 | } else { |
| 462 | return mv; |
| 463 | } |
| 464 | }); |
| 465 | if (updated.get()) { |
| 466 | notifyPeers(new UpdateEntry<>(key, computedValue), peerUpdateFunction.apply(key, computedValue.get())); |
| 467 | EventuallyConsistentMapEvent.Type updateType = computedValue.isTombstone() ? REMOVE : PUT; |
| 468 | V value = computedValue.isTombstone() |
| 469 | ? previousValue.get() == null ? null : previousValue.get().get() |
| 470 | : computedValue.get(); |
| 471 | if (value != null) { |
Madan Jampani | cab114c | 2015-07-23 00:14:19 -0700 | [diff] [blame] | 472 | notifyListeners(new EventuallyConsistentMapEvent<>(mapName, updateType, key, value)); |
Madan Jampani | 4727a11 | 2015-07-16 12:12:58 -0700 | [diff] [blame] | 473 | } |
| 474 | } |
| 475 | return computedValue.get(); |
| 476 | } |
| 477 | |
| 478 | @Override |
Jonathan Hart | db3af89 | 2015-01-26 13:19:07 -0800 | [diff] [blame] | 479 | public void putAll(Map<? extends K, ? extends V> m) { |
Thomas Vachuska | a132e3a | 2015-02-21 01:53:14 -0800 | [diff] [blame] | 480 | checkState(!destroyed, destroyedMessage); |
Brian O'Connor | eeaea2c | 2015-03-05 16:24:34 -0800 | [diff] [blame] | 481 | m.forEach(this::put); |
Jonathan Hart | db3af89 | 2015-01-26 13:19:07 -0800 | [diff] [blame] | 482 | } |
| 483 | |
| 484 | @Override |
| 485 | public void clear() { |
Thomas Vachuska | a132e3a | 2015-02-21 01:53:14 -0800 | [diff] [blame] | 486 | checkState(!destroyed, destroyedMessage); |
Madan Jampani | 3d76c94 | 2015-06-29 23:37:10 -0700 | [diff] [blame] | 487 | Maps.filterValues(items, MapValue::isAlive) |
slowr | 878625f | 2017-10-24 14:53:49 -0700 | [diff] [blame] | 488 | .forEach((k, v) -> remove(k)); |
Jonathan Hart | db3af89 | 2015-01-26 13:19:07 -0800 | [diff] [blame] | 489 | } |
| 490 | |
| 491 | @Override |
| 492 | public Set<K> keySet() { |
Thomas Vachuska | a132e3a | 2015-02-21 01:53:14 -0800 | [diff] [blame] | 493 | checkState(!destroyed, destroyedMessage); |
Madan Jampani | 3d76c94 | 2015-06-29 23:37:10 -0700 | [diff] [blame] | 494 | return Maps.filterValues(items, MapValue::isAlive) |
slowr | 878625f | 2017-10-24 14:53:49 -0700 | [diff] [blame] | 495 | .keySet(); |
Jonathan Hart | db3af89 | 2015-01-26 13:19:07 -0800 | [diff] [blame] | 496 | } |
| 497 | |
| 498 | @Override |
| 499 | public Collection<V> values() { |
Thomas Vachuska | a132e3a | 2015-02-21 01:53:14 -0800 | [diff] [blame] | 500 | checkState(!destroyed, destroyedMessage); |
Madan Jampani | 4f1f4cd | 2015-07-08 23:05:35 -0700 | [diff] [blame] | 501 | return Collections2.transform(Maps.filterValues(items, MapValue::isAlive).values(), MapValue::get); |
Jonathan Hart | db3af89 | 2015-01-26 13:19:07 -0800 | [diff] [blame] | 502 | } |
| 503 | |
| 504 | @Override |
| 505 | public Set<Map.Entry<K, V>> entrySet() { |
Thomas Vachuska | a132e3a | 2015-02-21 01:53:14 -0800 | [diff] [blame] | 506 | checkState(!destroyed, destroyedMessage); |
Madan Jampani | 3d76c94 | 2015-06-29 23:37:10 -0700 | [diff] [blame] | 507 | return Maps.filterValues(items, MapValue::isAlive) |
slowr | 878625f | 2017-10-24 14:53:49 -0700 | [diff] [blame] | 508 | .entrySet() |
| 509 | .stream() |
| 510 | .map(e -> Pair.of(e.getKey(), e.getValue().get())) |
| 511 | .collect(Collectors.toSet()); |
Madan Jampani | 3d76c94 | 2015-06-29 23:37:10 -0700 | [diff] [blame] | 512 | } |
Jonathan Hart | db3af89 | 2015-01-26 13:19:07 -0800 | [diff] [blame] | 513 | |
Madan Jampani | 3d76c94 | 2015-06-29 23:37:10 -0700 | [diff] [blame] | 514 | /** |
| 515 | * Returns true if newValue was accepted i.e. map is updated. |
Aaron Kruglikov | 66cf0b9 | 2015-10-26 15:46:54 -0700 | [diff] [blame] | 516 | * |
slowr | 878625f | 2017-10-24 14:53:49 -0700 | [diff] [blame] | 517 | * @param key key |
Madan Jampani | 3d76c94 | 2015-06-29 23:37:10 -0700 | [diff] [blame] | 518 | * @param newValue proposed new value |
| 519 | * @return true if update happened; false if map already contains a more recent value for the key |
| 520 | */ |
Madan Jampani | 4f1f4cd | 2015-07-08 23:05:35 -0700 | [diff] [blame] | 521 | private boolean putInternal(K key, MapValue<V> newValue) { |
| 522 | checkState(!destroyed, destroyedMessage); |
| 523 | checkNotNull(key, ERROR_NULL_KEY); |
| 524 | checkNotNull(newValue, ERROR_NULL_VALUE); |
| 525 | checkState(newValue.isAlive()); |
| 526 | counter.incrementCount(); |
Madan Jampani | 3d76c94 | 2015-06-29 23:37:10 -0700 | [diff] [blame] | 527 | AtomicBoolean updated = new AtomicBoolean(false); |
| 528 | items.compute(key, (k, existing) -> { |
| 529 | if (existing == null || newValue.isNewerThan(existing)) { |
| 530 | updated.set(true); |
Madan Jampani | 3d76c94 | 2015-06-29 23:37:10 -0700 | [diff] [blame] | 531 | return newValue; |
| 532 | } |
| 533 | return existing; |
| 534 | }); |
Madan Jampani | 3d76c94 | 2015-06-29 23:37:10 -0700 | [diff] [blame] | 535 | return updated.get(); |
Jonathan Hart | db3af89 | 2015-01-26 13:19:07 -0800 | [diff] [blame] | 536 | } |
| 537 | |
| 538 | @Override |
Jonathan Hart | 539a646 | 2015-01-27 17:05:43 -0800 | [diff] [blame] | 539 | public void addListener(EventuallyConsistentMapListener<K, V> listener) { |
Thomas Vachuska | a132e3a | 2015-02-21 01:53:14 -0800 | [diff] [blame] | 540 | checkState(!destroyed, destroyedMessage); |
Jonathan Hart | db3af89 | 2015-01-26 13:19:07 -0800 | [diff] [blame] | 541 | |
| 542 | listeners.add(checkNotNull(listener)); |
Jordan Halterman | 12d5ec4 | 2017-05-17 00:53:44 -0700 | [diff] [blame] | 543 | items.forEach((k, v) -> { |
| 544 | if (v.isAlive()) { |
| 545 | listener.event(new EventuallyConsistentMapEvent<K, V>(mapName, PUT, k, v.get())); |
| 546 | } |
| 547 | }); |
Jonathan Hart | db3af89 | 2015-01-26 13:19:07 -0800 | [diff] [blame] | 548 | } |
| 549 | |
| 550 | @Override |
Jonathan Hart | 539a646 | 2015-01-27 17:05:43 -0800 | [diff] [blame] | 551 | public void removeListener(EventuallyConsistentMapListener<K, V> listener) { |
Thomas Vachuska | a132e3a | 2015-02-21 01:53:14 -0800 | [diff] [blame] | 552 | checkState(!destroyed, destroyedMessage); |
Jonathan Hart | db3af89 | 2015-01-26 13:19:07 -0800 | [diff] [blame] | 553 | |
| 554 | listeners.remove(checkNotNull(listener)); |
| 555 | } |
| 556 | |
| 557 | @Override |
Madan Jampani | fa24218 | 2016-01-22 13:42:54 -0800 | [diff] [blame] | 558 | public CompletableFuture<Void> destroy() { |
Jonathan Hart | db3af89 | 2015-01-26 13:19:07 -0800 | [diff] [blame] | 559 | destroyed = true; |
| 560 | |
| 561 | executor.shutdown(); |
| 562 | backgroundExecutor.shutdown(); |
Brian O'Connor | eeaea2c | 2015-03-05 16:24:34 -0800 | [diff] [blame] | 563 | communicationExecutor.shutdown(); |
Jonathan Hart | db3af89 | 2015-01-26 13:19:07 -0800 | [diff] [blame] | 564 | |
Jonathan Hart | 584d2f3 | 2015-01-27 19:46:14 -0800 | [diff] [blame] | 565 | listeners.clear(); |
| 566 | |
Jordan Halterman | 12d5ec4 | 2017-05-17 00:53:44 -0700 | [diff] [blame] | 567 | clusterCommunicator.removeSubscriber(bootstrapMessageSubject); |
| 568 | clusterCommunicator.removeSubscriber(initializeMessageSubject); |
Jonathan Hart | db3af89 | 2015-01-26 13:19:07 -0800 | [diff] [blame] | 569 | clusterCommunicator.removeSubscriber(updateMessageSubject); |
Jon Hall | d198b88 | 2016-05-18 16:44:40 -0700 | [diff] [blame] | 570 | clusterCommunicator.removeSubscriber(updateRequestSubject); |
Jonathan Hart | 584d2f3 | 2015-01-27 19:46:14 -0800 | [diff] [blame] | 571 | clusterCommunicator.removeSubscriber(antiEntropyAdvertisementSubject); |
Madan Jampani | fa24218 | 2016-01-22 13:42:54 -0800 | [diff] [blame] | 572 | return CompletableFuture.completedFuture(null); |
Jonathan Hart | db3af89 | 2015-01-26 13:19:07 -0800 | [diff] [blame] | 573 | } |
| 574 | |
Jonathan Hart | aaa5657 | 2015-01-28 21:56:35 -0800 | [diff] [blame] | 575 | private void notifyListeners(EventuallyConsistentMapEvent<K, V> event) { |
Madan Jampani | 3d76c94 | 2015-06-29 23:37:10 -0700 | [diff] [blame] | 576 | listeners.forEach(listener -> listener.event(event)); |
Jonathan Hart | db3af89 | 2015-01-26 13:19:07 -0800 | [diff] [blame] | 577 | } |
| 578 | |
Madan Jampani | 3d76c94 | 2015-06-29 23:37:10 -0700 | [diff] [blame] | 579 | private void notifyPeers(UpdateEntry<K, V> event, Collection<NodeId> peers) { |
Brian O'Connor | eeaea2c | 2015-03-05 16:24:34 -0800 | [diff] [blame] | 580 | queueUpdate(event, peers); |
Jonathan Hart | db3af89 | 2015-01-26 13:19:07 -0800 | [diff] [blame] | 581 | } |
| 582 | |
Madan Jampani | 3d76c94 | 2015-06-29 23:37:10 -0700 | [diff] [blame] | 583 | private void queueUpdate(UpdateEntry<K, V> event, Collection<NodeId> peers) { |
Brian O'Connor | eeaea2c | 2015-03-05 16:24:34 -0800 | [diff] [blame] | 584 | if (peers == null) { |
| 585 | // we have no friends :( |
| 586 | return; |
| 587 | } |
| 588 | peers.forEach(node -> |
slowr | 878625f | 2017-10-24 14:53:49 -0700 | [diff] [blame] | 589 | senderPending.computeIfAbsent(node, unusedKey -> new EventAccumulator(node)).add(event) |
Brian O'Connor | eeaea2c | 2015-03-05 16:24:34 -0800 | [diff] [blame] | 590 | ); |
| 591 | } |
| 592 | |
Jonathan Hart | 233a18a | 2015-03-02 17:24:58 -0800 | [diff] [blame] | 593 | private boolean underHighLoad() { |
| 594 | return counter.get(LOAD_WINDOW) > HIGH_LOAD_THRESHOLD; |
| 595 | } |
| 596 | |
Madan Jampani | 3d76c94 | 2015-06-29 23:37:10 -0700 | [diff] [blame] | 597 | private void sendAdvertisement() { |
| 598 | try { |
Thomas Vachuska | 152f9fd | 2015-04-02 16:28:13 -0700 | [diff] [blame] | 599 | if (underHighLoad() || destroyed) { |
Jonathan Hart | 233a18a | 2015-03-02 17:24:58 -0800 | [diff] [blame] | 600 | return; |
| 601 | } |
Madan Jampani | 3d76c94 | 2015-06-29 23:37:10 -0700 | [diff] [blame] | 602 | pickRandomActivePeer().ifPresent(this::sendAdvertisementToPeer); |
| 603 | } catch (Exception e) { |
| 604 | // Catch all exceptions to avoid scheduled task being suppressed. |
| 605 | log.error("Exception thrown while sending advertisement", e); |
Jonathan Hart | aaa5657 | 2015-01-28 21:56:35 -0800 | [diff] [blame] | 606 | } |
| 607 | } |
| 608 | |
Madan Jampani | 3d76c94 | 2015-06-29 23:37:10 -0700 | [diff] [blame] | 609 | private Optional<NodeId> pickRandomActivePeer() { |
slowr | 878625f | 2017-10-24 14:53:49 -0700 | [diff] [blame] | 610 | List<NodeId> activePeers = peersSupplier.get(); |
Madan Jampani | 3d76c94 | 2015-06-29 23:37:10 -0700 | [diff] [blame] | 611 | Collections.shuffle(activePeers); |
slowr | 878625f | 2017-10-24 14:53:49 -0700 | [diff] [blame] | 612 | return activePeers.stream().findFirst(); |
Madan Jampani | 3d76c94 | 2015-06-29 23:37:10 -0700 | [diff] [blame] | 613 | } |
| 614 | |
| 615 | private void sendAdvertisementToPeer(NodeId peer) { |
Madan Jampani | ee35d55 | 2016-04-26 16:07:40 -0700 | [diff] [blame] | 616 | long adCreationTime = System.currentTimeMillis(); |
Madan Jampani | 29f52a3 | 2016-04-18 15:20:52 -0700 | [diff] [blame] | 617 | AntiEntropyAdvertisement<K> ad = createAdvertisement(); |
| 618 | clusterCommunicator.sendAndReceive(ad, |
Madan Jampani | 3d76c94 | 2015-06-29 23:37:10 -0700 | [diff] [blame] | 619 | antiEntropyAdvertisementSubject, |
| 620 | serializer::encode, |
Madan Jampani | 29f52a3 | 2016-04-18 15:20:52 -0700 | [diff] [blame] | 621 | serializer::decode, |
Madan Jampani | 3d76c94 | 2015-06-29 23:37:10 -0700 | [diff] [blame] | 622 | peer) |
| 623 | .whenComplete((result, error) -> { |
| 624 | if (error != null) { |
Jonathan Hart | e255cc4 | 2016-09-12 14:50:24 -0700 | [diff] [blame] | 625 | log.debug("Failed to send anti-entropy advertisement to {}: {}", |
| 626 | peer, error.getMessage()); |
Madan Jampani | 29f52a3 | 2016-04-18 15:20:52 -0700 | [diff] [blame] | 627 | } else if (result == AntiEntropyResponse.PROCESSED) { |
Madan Jampani | ee35d55 | 2016-04-26 16:07:40 -0700 | [diff] [blame] | 628 | antiEntropyTimes.put(peer, adCreationTime); |
Madan Jampani | 3d76c94 | 2015-06-29 23:37:10 -0700 | [diff] [blame] | 629 | } |
| 630 | }); |
| 631 | } |
| 632 | |
Jon Hall | d198b88 | 2016-05-18 16:44:40 -0700 | [diff] [blame] | 633 | private void sendUpdateRequestToPeer(NodeId peer, Set<K> keys) { |
| 634 | UpdateRequest<K> request = new UpdateRequest<>(localNodeId, keys); |
| 635 | clusterCommunicator.unicast(request, |
| 636 | updateRequestSubject, |
| 637 | serializer::encode, |
| 638 | peer) |
| 639 | .whenComplete((result, error) -> { |
| 640 | if (error != null) { |
Jonathan Hart | e255cc4 | 2016-09-12 14:50:24 -0700 | [diff] [blame] | 641 | log.debug("Failed to send update request to {}: {}", |
| 642 | peer, error.getMessage()); |
Jon Hall | d198b88 | 2016-05-18 16:44:40 -0700 | [diff] [blame] | 643 | } |
| 644 | }); |
| 645 | } |
| 646 | |
Jonathan Hart | aaa5657 | 2015-01-28 21:56:35 -0800 | [diff] [blame] | 647 | private AntiEntropyAdvertisement<K> createAdvertisement() { |
HIGUCHI Yuta | e729065 | 2016-05-18 11:29:01 -0700 | [diff] [blame] | 648 | return new AntiEntropyAdvertisement<>(localNodeId, |
Madan Jampani | 4f1f4cd | 2015-07-08 23:05:35 -0700 | [diff] [blame] | 649 | ImmutableMap.copyOf(Maps.transformValues(items, MapValue::digest))); |
Jonathan Hart | aaa5657 | 2015-01-28 21:56:35 -0800 | [diff] [blame] | 650 | } |
| 651 | |
Madan Jampani | 29f52a3 | 2016-04-18 15:20:52 -0700 | [diff] [blame] | 652 | private AntiEntropyResponse handleAntiEntropyAdvertisement(AntiEntropyAdvertisement<K> ad) { |
Madan Jampani | 3d76c94 | 2015-06-29 23:37:10 -0700 | [diff] [blame] | 653 | if (destroyed || underHighLoad()) { |
Madan Jampani | 29f52a3 | 2016-04-18 15:20:52 -0700 | [diff] [blame] | 654 | return AntiEntropyResponse.IGNORED; |
Madan Jampani | 3d76c94 | 2015-06-29 23:37:10 -0700 | [diff] [blame] | 655 | } |
| 656 | try { |
Jonathan Hart | 9a426f8 | 2015-09-03 15:43:13 +0200 | [diff] [blame] | 657 | if (log.isTraceEnabled()) { |
| 658 | log.trace("Received anti-entropy advertisement from {} for {} with {} entries in it", |
Jon Hall | d198b88 | 2016-05-18 16:44:40 -0700 | [diff] [blame] | 659 | ad.sender(), mapName, ad.digest().size()); |
Jonathan Hart | 9a426f8 | 2015-09-03 15:43:13 +0200 | [diff] [blame] | 660 | } |
Madan Jampani | 3d76c94 | 2015-06-29 23:37:10 -0700 | [diff] [blame] | 661 | antiEntropyCheckLocalItems(ad).forEach(this::notifyListeners); |
Madan Jampani | 3d76c94 | 2015-06-29 23:37:10 -0700 | [diff] [blame] | 662 | } catch (Exception e) { |
| 663 | log.warn("Error handling anti-entropy advertisement", e); |
Madan Jampani | 29f52a3 | 2016-04-18 15:20:52 -0700 | [diff] [blame] | 664 | return AntiEntropyResponse.FAILED; |
HIGUCHI Yuta | 00c3f57 | 2015-02-25 07:33:50 -0800 | [diff] [blame] | 665 | } |
Madan Jampani | 29f52a3 | 2016-04-18 15:20:52 -0700 | [diff] [blame] | 666 | return AntiEntropyResponse.PROCESSED; |
Jonathan Hart | aaa5657 | 2015-01-28 21:56:35 -0800 | [diff] [blame] | 667 | } |
| 668 | |
| 669 | /** |
Madan Jampani | 3d76c94 | 2015-06-29 23:37:10 -0700 | [diff] [blame] | 670 | * Processes anti-entropy ad from peer by taking following actions: |
| 671 | * 1. If peer has an old entry, updates peer. |
| 672 | * 2. If peer indicates an entry is removed and has a more recent |
| 673 | * timestamp than the local entry, update local state. |
Jonathan Hart | aaa5657 | 2015-01-28 21:56:35 -0800 | [diff] [blame] | 674 | */ |
Jonathan Hart | aaa5657 | 2015-01-28 21:56:35 -0800 | [diff] [blame] | 675 | private List<EventuallyConsistentMapEvent<K, V>> antiEntropyCheckLocalItems( |
| 676 | AntiEntropyAdvertisement<K> ad) { |
Madan Jampani | 3d76c94 | 2015-06-29 23:37:10 -0700 | [diff] [blame] | 677 | final List<EventuallyConsistentMapEvent<K, V>> externalEvents = Lists.newLinkedList(); |
Jonathan Hart | aaa5657 | 2015-01-28 21:56:35 -0800 | [diff] [blame] | 678 | final NodeId sender = ad.sender(); |
Jon Hall | d198b88 | 2016-05-18 16:44:40 -0700 | [diff] [blame] | 679 | final List<NodeId> peers = ImmutableList.of(sender); |
| 680 | Set<K> staleOrMissing = new HashSet<>(); |
| 681 | Set<K> locallyUnknown = new HashSet<>(ad.digest().keySet()); |
| 682 | |
Madan Jampani | 3d76c94 | 2015-06-29 23:37:10 -0700 | [diff] [blame] | 683 | items.forEach((key, localValue) -> { |
Jon Hall | d198b88 | 2016-05-18 16:44:40 -0700 | [diff] [blame] | 684 | locallyUnknown.remove(key); |
Madan Jampani | 3d76c94 | 2015-06-29 23:37:10 -0700 | [diff] [blame] | 685 | MapValue.Digest remoteValueDigest = ad.digest().get(key); |
| 686 | if (remoteValueDigest == null || localValue.isNewerThan(remoteValueDigest.timestamp())) { |
Jonathan Hart | aaa5657 | 2015-01-28 21:56:35 -0800 | [diff] [blame] | 687 | // local value is more recent, push to sender |
Jon Hall | d198b88 | 2016-05-18 16:44:40 -0700 | [diff] [blame] | 688 | queueUpdate(new UpdateEntry<>(key, localValue), peers); |
slowr | 878625f | 2017-10-24 14:53:49 -0700 | [diff] [blame] | 689 | } else if (remoteValueDigest.isNewerThan(localValue.digest()) && remoteValueDigest.isTombstone()) { |
Jon Hall | d198b88 | 2016-05-18 16:44:40 -0700 | [diff] [blame] | 690 | // remote value is more recent and a tombstone: update local value |
Madan Jampani | 483d0a2 | 2015-08-19 17:33:00 -0700 | [diff] [blame] | 691 | MapValue<V> tombstone = MapValue.tombstone(remoteValueDigest.timestamp()); |
Madan Jampani | d13f3b8 | 2015-07-01 17:37:50 -0700 | [diff] [blame] | 692 | MapValue<V> previousValue = removeInternal(key, |
slowr | 878625f | 2017-10-24 14:53:49 -0700 | [diff] [blame] | 693 | Optional.empty(), |
| 694 | Optional.of(tombstone)); |
Madan Jampani | d13f3b8 | 2015-07-01 17:37:50 -0700 | [diff] [blame] | 695 | if (previousValue != null && previousValue.isAlive()) { |
Madan Jampani | cab114c | 2015-07-23 00:14:19 -0700 | [diff] [blame] | 696 | externalEvents.add(new EventuallyConsistentMapEvent<>(mapName, REMOVE, key, previousValue.get())); |
Jonathan Hart | aaa5657 | 2015-01-28 21:56:35 -0800 | [diff] [blame] | 697 | } |
Jon Hall | d198b88 | 2016-05-18 16:44:40 -0700 | [diff] [blame] | 698 | } else if (remoteValueDigest.isNewerThan(localValue.digest())) { |
| 699 | // Not a tombstone and remote is newer |
| 700 | staleOrMissing.add(key); |
Jonathan Hart | aaa5657 | 2015-01-28 21:56:35 -0800 | [diff] [blame] | 701 | } |
Madan Jampani | 3d76c94 | 2015-06-29 23:37:10 -0700 | [diff] [blame] | 702 | }); |
Jon Hall | d198b88 | 2016-05-18 16:44:40 -0700 | [diff] [blame] | 703 | // Keys missing in local map |
| 704 | staleOrMissing.addAll(locallyUnknown); |
| 705 | // Request updates that we missed out on |
| 706 | sendUpdateRequestToPeer(sender, staleOrMissing); |
Jonathan Hart | aaa5657 | 2015-01-28 21:56:35 -0800 | [diff] [blame] | 707 | return externalEvents; |
| 708 | } |
| 709 | |
Jon Hall | d198b88 | 2016-05-18 16:44:40 -0700 | [diff] [blame] | 710 | private void handleUpdateRequests(UpdateRequest<K> request) { |
| 711 | final Set<K> keys = request.keys(); |
| 712 | final NodeId sender = request.sender(); |
| 713 | final List<NodeId> peers = ImmutableList.of(sender); |
Jon Hall | d198b88 | 2016-05-18 16:44:40 -0700 | [diff] [blame] | 714 | keys.forEach(key -> |
slowr | 878625f | 2017-10-24 14:53:49 -0700 | [diff] [blame] | 715 | queueUpdate(new UpdateEntry<>(key, items.get(key)), peers) |
Jon Hall | d198b88 | 2016-05-18 16:44:40 -0700 | [diff] [blame] | 716 | ); |
| 717 | } |
| 718 | |
Madan Jampani | 29f52a3 | 2016-04-18 15:20:52 -0700 | [diff] [blame] | 719 | private void purgeTombstones() { |
| 720 | /* |
Jon Hall | d198b88 | 2016-05-18 16:44:40 -0700 | [diff] [blame] | 721 | * In order to mitigate the resource exhaustion that can ensue due to an ever-growing set |
Madan Jampani | 29f52a3 | 2016-04-18 15:20:52 -0700 | [diff] [blame] | 722 | * of tombstones we employ the following heuristic to purge old tombstones periodically. |
| 723 | * First, we keep track of the time (local system time) when we were able to have a successful |
| 724 | * AE exchange with each peer. The smallest (or oldest) such time across *all* peers is regarded |
| 725 | * as the time before which all tombstones are considered safe to purge. |
| 726 | */ |
slowr | 878625f | 2017-10-24 14:53:49 -0700 | [diff] [blame] | 727 | long currentSafeTombstonePurgeTime = peersSupplier.get() |
| 728 | .stream() |
| 729 | .map(id -> antiEntropyTimes.getOrDefault(id, 0L)) |
| 730 | .reduce(Math::min) |
| 731 | .orElse(0L); |
Madan Jampani | 29f52a3 | 2016-04-18 15:20:52 -0700 | [diff] [blame] | 732 | if (currentSafeTombstonePurgeTime == previousTombstonePurgeTime) { |
| 733 | return; |
| 734 | } |
| 735 | List<Map.Entry<K, MapValue<V>>> tombStonesToDelete = items.entrySet() |
slowr | 878625f | 2017-10-24 14:53:49 -0700 | [diff] [blame] | 736 | .stream() |
| 737 | .filter(e -> e.getValue().isTombstone()) |
| 738 | .filter(e -> e.getValue().creationTime() <= currentSafeTombstonePurgeTime) |
| 739 | .collect(Collectors.toList()); |
Madan Jampani | 29f52a3 | 2016-04-18 15:20:52 -0700 | [diff] [blame] | 740 | previousTombstonePurgeTime = currentSafeTombstonePurgeTime; |
| 741 | tombStonesToDelete.forEach(entry -> items.remove(entry.getKey(), entry.getValue())); |
| 742 | } |
| 743 | |
Madan Jampani | 3d76c94 | 2015-06-29 23:37:10 -0700 | [diff] [blame] | 744 | private void processUpdates(Collection<UpdateEntry<K, V>> updates) { |
| 745 | if (destroyed) { |
| 746 | return; |
Jonathan Hart | aaa5657 | 2015-01-28 21:56:35 -0800 | [diff] [blame] | 747 | } |
Madan Jampani | 3d76c94 | 2015-06-29 23:37:10 -0700 | [diff] [blame] | 748 | updates.forEach(update -> { |
| 749 | final K key = update.key(); |
Madan Jampani | 29f52a3 | 2016-04-18 15:20:52 -0700 | [diff] [blame] | 750 | final MapValue<V> value = update.value() == null ? null : update.value().copy(); |
Madan Jampani | 483d0a2 | 2015-08-19 17:33:00 -0700 | [diff] [blame] | 751 | if (value == null || value.isTombstone()) { |
| 752 | MapValue<V> previousValue = removeInternal(key, Optional.empty(), Optional.ofNullable(value)); |
Madan Jampani | 4f1f4cd | 2015-07-08 23:05:35 -0700 | [diff] [blame] | 753 | if (previousValue != null && previousValue.isAlive()) { |
Madan Jampani | cab114c | 2015-07-23 00:14:19 -0700 | [diff] [blame] | 754 | notifyListeners(new EventuallyConsistentMapEvent<>(mapName, REMOVE, key, previousValue.get())); |
Madan Jampani | d13f3b8 | 2015-07-01 17:37:50 -0700 | [diff] [blame] | 755 | } |
Madan Jampani | 4f1f4cd | 2015-07-08 23:05:35 -0700 | [diff] [blame] | 756 | } else if (putInternal(key, value)) { |
Madan Jampani | cab114c | 2015-07-23 00:14:19 -0700 | [diff] [blame] | 757 | notifyListeners(new EventuallyConsistentMapEvent<>(mapName, PUT, key, value.get())); |
Jonathan Hart | aaa5657 | 2015-01-28 21:56:35 -0800 | [diff] [blame] | 758 | } |
Madan Jampani | 3d76c94 | 2015-06-29 23:37:10 -0700 | [diff] [blame] | 759 | }); |
Jonathan Hart | db3af89 | 2015-01-26 13:19:07 -0800 | [diff] [blame] | 760 | } |
| 761 | |
Jordan Halterman | 12d5ec4 | 2017-05-17 00:53:44 -0700 | [diff] [blame] | 762 | /** |
| 763 | * Bootstraps the map to attempt to get in sync with existing instances of the same map on other nodes in the |
| 764 | * cluster. This is necessary to ensure that a read immediately after the map is created doesn't return a null |
| 765 | * value. |
| 766 | */ |
Jon Hall | dabee68 | 2016-05-17 11:29:51 -0700 | [diff] [blame] | 767 | private void bootstrap() { |
slowr | 878625f | 2017-10-24 14:53:49 -0700 | [diff] [blame] | 768 | List<NodeId> activePeers = bootstrapPeersSupplier.get(); |
Jon Hall | dabee68 | 2016-05-17 11:29:51 -0700 | [diff] [blame] | 769 | if (activePeers.isEmpty()) { |
| 770 | return; |
| 771 | } |
Jordan Halterman | 12d5ec4 | 2017-05-17 00:53:44 -0700 | [diff] [blame] | 772 | try { |
| 773 | requestBootstrapFromPeers(activePeers) |
Jordan Halterman | 6440b09 | 2017-05-24 17:48:08 -0700 | [diff] [blame] | 774 | .get(DistributedPrimitive.DEFAULT_OPERATION_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); |
slowr | 878625f | 2017-10-24 14:53:49 -0700 | [diff] [blame] | 775 | } catch (ExecutionException | InterruptedException | TimeoutException e) { |
| 776 | log.debug("Failed to bootstrap ec map {}: {}", mapName, ExceptionUtils.getStackTrace(e)); |
Jordan Halterman | 12d5ec4 | 2017-05-17 00:53:44 -0700 | [diff] [blame] | 777 | } |
| 778 | } |
| 779 | |
| 780 | /** |
| 781 | * Requests all updates from each peer in the provided list of peers. |
| 782 | * <p> |
| 783 | * The returned future will be completed once at least one peer bootstraps this map or bootstrap requests to all |
| 784 | * peers fail. |
| 785 | * |
| 786 | * @param peers the list of peers from which to request updates |
| 787 | * @return a future to be completed once updates have been received from at least one peer |
| 788 | */ |
| 789 | private CompletableFuture<Void> requestBootstrapFromPeers(List<NodeId> peers) { |
| 790 | if (peers.isEmpty()) { |
| 791 | return CompletableFuture.completedFuture(null); |
Jon Hall | dabee68 | 2016-05-17 11:29:51 -0700 | [diff] [blame] | 792 | } |
Jordan Halterman | 12d5ec4 | 2017-05-17 00:53:44 -0700 | [diff] [blame] | 793 | CompletableFuture<Void> future = new CompletableFuture<>(); |
Jordan Halterman | 12d5ec4 | 2017-05-17 00:53:44 -0700 | [diff] [blame] | 794 | final int totalPeers = peers.size(); |
Jordan Halterman | 12d5ec4 | 2017-05-17 00:53:44 -0700 | [diff] [blame] | 795 | AtomicBoolean successful = new AtomicBoolean(); |
| 796 | AtomicInteger totalCount = new AtomicInteger(); |
| 797 | AtomicReference<Throwable> lastError = new AtomicReference<>(); |
| 798 | |
| 799 | // Iterate through all of the peers and send a bootstrap request. On the first peer that returns |
| 800 | // a successful bootstrap response, complete the future. Otherwise, if no peers respond with any |
| 801 | // successful bootstrap response, the future will be completed with the last exception. |
| 802 | for (NodeId peer : peers) { |
| 803 | requestBootstrapFromPeer(peer).whenComplete((result, error) -> { |
| 804 | if (error == null) { |
| 805 | if (successful.compareAndSet(false, true)) { |
| 806 | future.complete(null); |
| 807 | } else if (totalCount.incrementAndGet() == totalPeers) { |
| 808 | Throwable e = lastError.get(); |
| 809 | if (e != null) { |
| 810 | future.completeExceptionally(e); |
| 811 | } |
| 812 | } |
| 813 | } else { |
| 814 | if (!successful.get() && totalCount.incrementAndGet() == totalPeers) { |
| 815 | future.completeExceptionally(error); |
| 816 | } else { |
| 817 | lastError.set(error); |
| 818 | } |
| 819 | } |
| 820 | }); |
Jon Hall | dabee68 | 2016-05-17 11:29:51 -0700 | [diff] [blame] | 821 | } |
Jordan Halterman | 12d5ec4 | 2017-05-17 00:53:44 -0700 | [diff] [blame] | 822 | return future; |
| 823 | } |
| 824 | |
| 825 | /** |
| 826 | * Requests a bootstrap from the given peer. |
| 827 | * |
| 828 | * @param peer the peer from which to request updates |
| 829 | * @return a future to be completed once the peer has sent bootstrap updates |
| 830 | */ |
| 831 | private CompletableFuture<Void> requestBootstrapFromPeer(NodeId peer) { |
slowr | 878625f | 2017-10-24 14:53:49 -0700 | [diff] [blame] | 832 | log.trace("Sending bootstrap request to {} for {}", peer, mapName); |
Jordan Halterman | 12d5ec4 | 2017-05-17 00:53:44 -0700 | [diff] [blame] | 833 | return clusterCommunicator.<NodeId, Void>sendAndReceive( |
| 834 | localNodeId, |
| 835 | bootstrapMessageSubject, |
| 836 | serializer::encode, |
| 837 | serializer::decode, |
| 838 | peer) |
| 839 | .whenComplete((updates, error) -> { |
| 840 | if (error != null) { |
| 841 | log.debug("Bootstrap request to {} failed: {}", peer, error.getMessage()); |
| 842 | } |
| 843 | }); |
| 844 | } |
| 845 | |
| 846 | /** |
| 847 | * Handles a bootstrap request from a peer. |
| 848 | * <p> |
| 849 | * When handling a bootstrap request from a peer, the node sends batches of entries back to the peer and |
| 850 | * completes the bootstrap request once all batches have been received and processed. |
| 851 | * |
| 852 | * @param peer the peer that sent the bootstrap request |
| 853 | * @return a future to be completed once updates have been sent to the peer |
| 854 | */ |
| 855 | private CompletableFuture<Void> handleBootstrap(NodeId peer) { |
slowr | 878625f | 2017-10-24 14:53:49 -0700 | [diff] [blame] | 856 | log.trace("Received bootstrap request from {} for {}", peer, bootstrapMessageSubject); |
Jordan Halterman | 12d5ec4 | 2017-05-17 00:53:44 -0700 | [diff] [blame] | 857 | |
| 858 | Function<List<UpdateEntry<K, V>>, CompletableFuture<Void>> sendUpdates = updates -> { |
| 859 | log.trace("Initializing {} with {} entries", peer, updates.size()); |
| 860 | return clusterCommunicator.<List<UpdateEntry<K, V>>, Void>sendAndReceive( |
| 861 | ImmutableList.copyOf(updates), |
| 862 | initializeMessageSubject, |
| 863 | serializer::encode, |
| 864 | serializer::decode, |
| 865 | peer) |
| 866 | .whenComplete((result, error) -> { |
| 867 | if (error != null) { |
| 868 | log.debug("Failed to initialize {}", peer, error); |
| 869 | } |
| 870 | }); |
| 871 | }; |
| 872 | |
| 873 | List<CompletableFuture<Void>> futures = Lists.newArrayList(); |
| 874 | List<UpdateEntry<K, V>> updates = Lists.newArrayList(); |
| 875 | for (Map.Entry<K, MapValue<V>> entry : items.entrySet()) { |
| 876 | K key = entry.getKey(); |
| 877 | MapValue<V> value = entry.getValue(); |
| 878 | if (value.isAlive()) { |
slowr | 878625f | 2017-10-24 14:53:49 -0700 | [diff] [blame] | 879 | updates.add(new UpdateEntry<>(key, value)); |
Jordan Halterman | 12d5ec4 | 2017-05-17 00:53:44 -0700 | [diff] [blame] | 880 | if (updates.size() == DEFAULT_MAX_EVENTS) { |
| 881 | futures.add(sendUpdates.apply(updates)); |
| 882 | updates = new ArrayList<>(); |
| 883 | } |
| 884 | } |
| 885 | } |
| 886 | |
| 887 | if (!updates.isEmpty()) { |
| 888 | futures.add(sendUpdates.apply(updates)); |
| 889 | } |
| 890 | return CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()])); |
Jon Hall | dabee68 | 2016-05-17 11:29:51 -0700 | [diff] [blame] | 891 | } |
| 892 | |
Brian O'Connor | eeaea2c | 2015-03-05 16:24:34 -0800 | [diff] [blame] | 893 | // TODO pull this into the class if this gets pulled out... |
| 894 | private static final int DEFAULT_MAX_EVENTS = 1000; |
| 895 | private static final int DEFAULT_MAX_IDLE_MS = 10; |
| 896 | private static final int DEFAULT_MAX_BATCH_MS = 50; |
| 897 | private static final Timer TIMER = new Timer("onos-ecm-sender-events"); |
Jonathan Hart | db3af89 | 2015-01-26 13:19:07 -0800 | [diff] [blame] | 898 | |
Madan Jampani | 3d76c94 | 2015-06-29 23:37:10 -0700 | [diff] [blame] | 899 | private final class EventAccumulator extends AbstractAccumulator<UpdateEntry<K, V>> { |
Brian O'Connor | eeaea2c | 2015-03-05 16:24:34 -0800 | [diff] [blame] | 900 | |
| 901 | private final NodeId peer; |
| 902 | |
| 903 | private EventAccumulator(NodeId peer) { |
| 904 | super(TIMER, DEFAULT_MAX_EVENTS, DEFAULT_MAX_BATCH_MS, DEFAULT_MAX_IDLE_MS); |
| 905 | this.peer = peer; |
| 906 | } |
| 907 | |
| 908 | @Override |
Madan Jampani | 3d76c94 | 2015-06-29 23:37:10 -0700 | [diff] [blame] | 909 | public void processItems(List<UpdateEntry<K, V>> items) { |
| 910 | Map<K, UpdateEntry<K, V>> map = Maps.newHashMap(); |
| 911 | items.forEach(item -> map.compute(item.key(), (key, existing) -> |
Madan Jampani | 92c64eb | 2015-07-23 15:37:07 -0700 | [diff] [blame] | 912 | item.isNewerThan(existing) ? item : existing)); |
HIGUCHI Yuta | d9e0105 | 2016-04-14 09:31:42 -0700 | [diff] [blame] | 913 | communicationExecutor.execute(() -> { |
Jordan Halterman | e0fae91 | 2017-05-18 12:52:51 -0700 | [diff] [blame] | 914 | try { |
| 915 | clusterCommunicator.unicast(ImmutableList.copyOf(map.values()), |
| 916 | updateMessageSubject, |
| 917 | serializer::encode, |
| 918 | peer) |
| 919 | .whenComplete((result, error) -> { |
| 920 | if (error != null) { |
| 921 | log.debug("Failed to send to {}", peer, error); |
| 922 | } |
| 923 | }); |
| 924 | } catch (Exception e) { |
| 925 | log.warn("Failed to send to {}", peer, e); |
| 926 | } |
Brian O'Connor | eeaea2c | 2015-03-05 16:24:34 -0800 | [diff] [blame] | 927 | }); |
Jonathan Hart | db3af89 | 2015-01-26 13:19:07 -0800 | [diff] [blame] | 928 | } |
| 929 | } |
Jonathan Hart | 4a29c59 | 2015-09-23 17:55:07 -0700 | [diff] [blame] | 930 | } |