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