blob: 958734c7e98e2325a08e03603ee802feaa8c7f69 [file] [log] [blame]
Madan Jampani7c521002015-03-23 12:23:01 -07001/*
2 * Copyright 2015 Open Networking Laboratory
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Madan Jampanif4c88502016-01-21 12:35:36 -080017package org.onosproject.store.primitives.impl;
Madan Jampani7c521002015-03-23 12:23:01 -070018
Madan Jampanifa242182016-01-22 13:42:54 -080019import static com.google.common.base.Preconditions.checkNotNull;
20import static org.onosproject.store.primitives.impl.StateMachineUpdate.Target.MAP_UPDATE;
21import static org.onosproject.store.primitives.impl.StateMachineUpdate.Target.TX_COMMIT;
22import static org.slf4j.LoggerFactory.getLogger;
Madan Jampani7c521002015-03-23 12:23:01 -070023
Flavio Castro41b1f3a2015-07-31 13:51:32 -070024import java.util.Collection;
HIGUCHI Yuta14e865d2015-11-25 20:42:32 -080025import java.util.Collections;
Flavio Castro41b1f3a2015-07-31 13:51:32 -070026import java.util.Map;
27import java.util.Map.Entry;
28import java.util.Objects;
29import java.util.Set;
30import java.util.concurrent.CompletableFuture;
31import java.util.concurrent.CopyOnWriteArraySet;
32import java.util.concurrent.atomic.AtomicReference;
33import java.util.function.BiFunction;
34import java.util.function.Function;
35import java.util.function.Predicate;
36import java.util.stream.Collectors;
37
Madan Jampanifa242182016-01-22 13:42:54 -080038import org.onlab.util.HexString;
39import org.onlab.util.Match;
40import org.onlab.util.SharedExecutors;
41import org.onlab.util.Tools;
42import org.onosproject.core.ApplicationId;
43import org.onosproject.store.service.AsyncConsistentMap;
44import org.onosproject.store.service.ConsistentMapException;
45import org.onosproject.store.service.ConsistentMapException.ConcurrentModification;
46import org.onosproject.store.service.MapEvent;
47import org.onosproject.store.service.MapEventListener;
48import org.onosproject.store.service.Serializer;
49import org.onosproject.store.service.Versioned;
Aaron Kruglikov1110b2c2016-02-02 16:24:37 -080050import org.onosproject.utils.MeteringAgent;
Madan Jampanifa242182016-01-22 13:42:54 -080051import org.slf4j.Logger;
52
53import com.google.common.cache.CacheBuilder;
54import com.google.common.cache.CacheLoader;
55import com.google.common.cache.LoadingCache;
56import com.google.common.collect.Maps;
Madan Jampani7c521002015-03-23 12:23:01 -070057
58/**
59 * AsyncConsistentMap implementation that is backed by a Raft consensus
60 * based database.
61 *
62 * @param <K> type of key.
63 * @param <V> type of value.
64 */
Flavio Castro41b1f3a2015-07-31 13:51:32 -070065public class DefaultAsyncConsistentMap<K, V> implements AsyncConsistentMap<K, V> {
Madan Jampani7c521002015-03-23 12:23:01 -070066
67 private final String name;
Madan Jampanie8af1cc2015-06-23 14:23:31 -070068 private final ApplicationId applicationId;
Madan Jampanif1b8e172015-03-23 11:42:02 -070069 private final Database database;
Madan Jampani7c521002015-03-23 12:23:01 -070070 private final Serializer serializer;
Madan Jampani02b7fb82015-05-01 13:01:20 -070071 private final boolean readOnly;
Madan Jampanie8af1cc2015-06-23 14:23:31 -070072 private final boolean purgeOnUninstall;
Madan Jampani50589ac2015-06-08 11:38:46 -070073
Flavio Castro41b1f3a2015-07-31 13:51:32 -070074 private static final String PRIMITIVE_NAME = "consistentMap";
Flavio Castro5e1f1292015-07-23 17:14:09 -070075 private static final String SIZE = "size";
76 private static final String IS_EMPTY = "isEmpty";
77 private static final String CONTAINS_KEY = "containsKey";
78 private static final String CONTAINS_VALUE = "containsValue";
79 private static final String GET = "get";
80 private static final String COMPUTE_IF = "computeIf";
81 private static final String PUT = "put";
82 private static final String PUT_AND_GET = "putAndGet";
83 private static final String PUT_IF_ABSENT = "putIfAbsent";
84 private static final String REMOVE = "remove";
85 private static final String CLEAR = "clear";
86 private static final String KEY_SET = "keySet";
87 private static final String VALUES = "values";
88 private static final String ENTRY_SET = "entrySet";
89 private static final String REPLACE = "replace";
90 private static final String COMPUTE_IF_ABSENT = "computeIfAbsent";
91
Madan Jampani50589ac2015-06-08 11:38:46 -070092 private final Set<MapEventListener<K, V>> listeners = new CopyOnWriteArraySet<>();
93
94 private final Logger log = getLogger(getClass());
Flavio Castro41b1f3a2015-07-31 13:51:32 -070095 private final MeteringAgent monitor;
Madan Jampani7c521002015-03-23 12:23:01 -070096
97 private static final String ERROR_NULL_KEY = "Key cannot be null";
98 private static final String ERROR_NULL_VALUE = "Null values are not allowed";
99
HIGUCHI Yuta14e865d2015-11-25 20:42:32 -0800100 // String representation of serialized byte[] -> original key Object
101 private final LoadingCache<String, K> keyCache = CacheBuilder.newBuilder()
Madan Jampani7c521002015-03-23 12:23:01 -0700102 .softValues()
HIGUCHI Yuta14e865d2015-11-25 20:42:32 -0800103 .build(new CacheLoader<String, K>() {
Madan Jampani7c521002015-03-23 12:23:01 -0700104
105 @Override
HIGUCHI Yuta14e865d2015-11-25 20:42:32 -0800106 public K load(String key) {
107 return serializer.decode(HexString.fromHexString(key));
Madan Jampani7c521002015-03-23 12:23:01 -0700108 }
109 });
110
HIGUCHI Yuta14e865d2015-11-25 20:42:32 -0800111 protected String sK(K key) {
112 String s = HexString.toHexString(serializer.encode(key));
113 keyCache.put(s, key);
114 return s;
115 }
116
Madan Jampani7c521002015-03-23 12:23:01 -0700117 protected K dK(String key) {
HIGUCHI Yuta14e865d2015-11-25 20:42:32 -0800118 return keyCache.getUnchecked(key);
Madan Jampani7c521002015-03-23 12:23:01 -0700119 }
120
121 public DefaultAsyncConsistentMap(String name,
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700122 ApplicationId applicationId,
123 Database database,
124 Serializer serializer,
125 boolean readOnly,
126 boolean purgeOnUninstall,
127 boolean meteringEnabled) {
Madan Jampani7c521002015-03-23 12:23:01 -0700128 this.name = checkNotNull(name, "map name cannot be null");
Madan Jampanie8af1cc2015-06-23 14:23:31 -0700129 this.applicationId = applicationId;
Madan Jampanif1b8e172015-03-23 11:42:02 -0700130 this.database = checkNotNull(database, "database cannot be null");
Madan Jampani7c521002015-03-23 12:23:01 -0700131 this.serializer = checkNotNull(serializer, "serializer cannot be null");
Madan Jampani02b7fb82015-05-01 13:01:20 -0700132 this.readOnly = readOnly;
Madan Jampanie8af1cc2015-06-23 14:23:31 -0700133 this.purgeOnUninstall = purgeOnUninstall;
Madan Jampani648451f2015-07-21 22:09:05 -0700134 this.database.registerConsumer(update -> {
135 SharedExecutors.getSingleThreadExecutor().execute(() -> {
Madan Jampani9eb55d12015-08-14 07:47:56 -0700136 if (listeners.isEmpty()) {
137 return;
138 }
139 try {
140 if (update.target() == MAP_UPDATE) {
141 Result<UpdateResult<String, byte[]>> result = update.output();
142 if (result.success() && result.value().mapName().equals(name)) {
143 MapEvent<K, V> mapEvent = result.value()
144 .<K, V>map(this::dK,
145 v -> serializer.decode(Tools.copyOf(v)))
146 .toMapEvent();
147 notifyListeners(mapEvent);
148 }
149 } else if (update.target() == TX_COMMIT) {
150 CommitResponse response = update.output();
151 if (response.success()) {
152 response.updates().forEach(u -> {
153 if (u.mapName().equals(name)) {
154 MapEvent<K, V> mapEvent =
155 u.<K, V>map(this::dK,
156 v -> serializer.decode(Tools.copyOf(v)))
157 .toMapEvent();
158 notifyListeners(mapEvent);
159 }
160 });
161 }
Madan Jampani648451f2015-07-21 22:09:05 -0700162 }
Madan Jampani9eb55d12015-08-14 07:47:56 -0700163 } catch (Exception e) {
164 log.warn("Error notifying listeners", e);
Madan Jampani648451f2015-07-21 22:09:05 -0700165 }
166 });
167 });
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700168 this.monitor = new MeteringAgent(PRIMITIVE_NAME, name, meteringEnabled);
Madan Jampani50589ac2015-06-08 11:38:46 -0700169 }
170
171 /**
172 * Returns this map name.
173 * @return map name
174 */
Madan Jampania090a112016-01-18 16:38:17 -0800175 @Override
Madan Jampani50589ac2015-06-08 11:38:46 -0700176 public String name() {
177 return name;
178 }
179
180 /**
181 * Returns the serializer for map entries.
182 * @return map entry serializer
183 */
184 public Serializer serializer() {
185 return serializer;
Madan Jampani7c521002015-03-23 12:23:01 -0700186 }
187
Madan Jampanie8af1cc2015-06-23 14:23:31 -0700188 /**
189 * Returns the applicationId owning this map.
190 * @return application Id
191 */
Madan Jampania090a112016-01-18 16:38:17 -0800192 @Override
Madan Jampanie8af1cc2015-06-23 14:23:31 -0700193 public ApplicationId applicationId() {
194 return applicationId;
195 }
196
197 /**
198 * Returns whether the map entries should be purged when the application
199 * owning it is uninstalled.
200 * @return true is map needs to cleared on app uninstall; false otherwise
201 */
202 public boolean purgeOnUninstall() {
203 return purgeOnUninstall;
204 }
205
Madan Jampani7c521002015-03-23 12:23:01 -0700206 @Override
207 public CompletableFuture<Integer> size() {
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700208 final MeteringAgent.Context timer = monitor.startTimer(SIZE);
Flavio Castro5e1f1292015-07-23 17:14:09 -0700209 return database.mapSize(name)
Flavio Castro6e044612015-08-13 14:13:58 -0700210 .whenComplete((r, e) -> timer.stop(e));
Madan Jampani7c521002015-03-23 12:23:01 -0700211 }
212
213 @Override
214 public CompletableFuture<Boolean> isEmpty() {
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700215 final MeteringAgent.Context timer = monitor.startTimer(IS_EMPTY);
Flavio Castro5e1f1292015-07-23 17:14:09 -0700216 return database.mapIsEmpty(name)
Flavio Castro6e044612015-08-13 14:13:58 -0700217 .whenComplete((r, e) -> timer.stop(e));
Madan Jampani7c521002015-03-23 12:23:01 -0700218 }
219
220 @Override
221 public CompletableFuture<Boolean> containsKey(K key) {
222 checkNotNull(key, ERROR_NULL_KEY);
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700223 final MeteringAgent.Context timer = monitor.startTimer(CONTAINS_KEY);
HIGUCHI Yuta14e865d2015-11-25 20:42:32 -0800224 return database.mapContainsKey(name, sK(key))
Flavio Castro6e044612015-08-13 14:13:58 -0700225 .whenComplete((r, e) -> timer.stop(e));
Madan Jampani7c521002015-03-23 12:23:01 -0700226 }
227
228 @Override
229 public CompletableFuture<Boolean> containsValue(V value) {
230 checkNotNull(value, ERROR_NULL_VALUE);
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700231 final MeteringAgent.Context timer = monitor.startTimer(CONTAINS_VALUE);
Flavio Castro5e1f1292015-07-23 17:14:09 -0700232 return database.mapContainsValue(name, serializer.encode(value))
Flavio Castro6e044612015-08-13 14:13:58 -0700233 .whenComplete((r, e) -> timer.stop(e));
Madan Jampani7c521002015-03-23 12:23:01 -0700234 }
235
236 @Override
237 public CompletableFuture<Versioned<V>> get(K key) {
238 checkNotNull(key, ERROR_NULL_KEY);
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700239 final MeteringAgent.Context timer = monitor.startTimer(GET);
HIGUCHI Yuta14e865d2015-11-25 20:42:32 -0800240 return database.mapGet(name, sK(key))
Flavio Castro6e044612015-08-13 14:13:58 -0700241 .whenComplete((r, e) -> timer.stop(e))
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700242 .thenApply(v -> v != null ? v.map(serializer::decode) : null);
Madan Jampani7c521002015-03-23 12:23:01 -0700243 }
244
245 @Override
Madan Jampani346d4f52015-05-04 11:09:39 -0700246 public CompletableFuture<Versioned<V>> computeIfAbsent(K key,
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700247 Function<? super K, ? extends V> mappingFunction) {
Madan Jampani7804c992015-07-20 13:20:19 -0700248 checkNotNull(key, ERROR_NULL_KEY);
249 checkNotNull(mappingFunction, "Mapping function cannot be null");
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700250 final MeteringAgent.Context timer = monitor.startTimer(COMPUTE_IF_ABSENT);
Flavio Castro5e1f1292015-07-23 17:14:09 -0700251 return updateAndGet(key, Match.ifNull(), Match.any(), mappingFunction.apply(key))
Flavio Castro6e044612015-08-13 14:13:58 -0700252 .whenComplete((r, e) -> timer.stop(e))
Flavio Castro5e1f1292015-07-23 17:14:09 -0700253 .thenApply(v -> v.newValue());
Madan Jampani346d4f52015-05-04 11:09:39 -0700254 }
255
256 @Override
257 public CompletableFuture<Versioned<V>> computeIfPresent(K key,
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700258 BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
Madan Jampani346d4f52015-05-04 11:09:39 -0700259 return computeIf(key, Objects::nonNull, remappingFunction);
260 }
261
262 @Override
263 public CompletableFuture<Versioned<V>> compute(K key,
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700264 BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
Madan Jampani346d4f52015-05-04 11:09:39 -0700265 return computeIf(key, v -> true, remappingFunction);
266 }
267
268 @Override
269 public CompletableFuture<Versioned<V>> computeIf(K key,
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700270 Predicate<? super V> condition,
271 BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
Madan Jampani346d4f52015-05-04 11:09:39 -0700272 checkNotNull(key, ERROR_NULL_KEY);
273 checkNotNull(condition, "predicate function cannot be null");
274 checkNotNull(remappingFunction, "Remapping function cannot be null");
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700275 final MeteringAgent.Context timer = monitor.startTimer(COMPUTE_IF);
Madan Jampani346d4f52015-05-04 11:09:39 -0700276 return get(key).thenCompose(r1 -> {
277 V existingValue = r1 == null ? null : r1.value();
278 // if the condition evaluates to false, return existing value.
279 if (!condition.test(existingValue)) {
280 return CompletableFuture.completedFuture(r1);
281 }
282
283 AtomicReference<V> computedValue = new AtomicReference<>();
284 // if remappingFunction throws an exception, return the exception.
285 try {
286 computedValue.set(remappingFunction.apply(key, existingValue));
287 } catch (Exception e) {
288 return Tools.exceptionalFuture(e);
289 }
Madan Jampani7804c992015-07-20 13:20:19 -0700290 if (computedValue.get() == null && r1 == null) {
291 return CompletableFuture.completedFuture(null);
Madan Jampani346d4f52015-05-04 11:09:39 -0700292 }
Madan Jampani7804c992015-07-20 13:20:19 -0700293 Match<V> valueMatcher = r1 == null ? Match.ifNull() : Match.any();
294 Match<Long> versionMatcher = r1 == null ? Match.any() : Match.ifValue(r1.version());
295 return updateAndGet(key, valueMatcher, versionMatcher, computedValue.get())
Flavio Castro6e044612015-08-13 14:13:58 -0700296 .whenComplete((r, e) -> timer.stop(e))
Madan Jampani7804c992015-07-20 13:20:19 -0700297 .thenApply(v -> {
298 if (v.updated()) {
299 return v.newValue();
300 } else {
Madan Jampanic7f49f92015-12-10 11:35:06 -0800301 throw new ConcurrentModification("Concurrent update to " + name + " detected");
Madan Jampani7804c992015-07-20 13:20:19 -0700302 }
303 });
304 });
Madan Jampani346d4f52015-05-04 11:09:39 -0700305 }
306
307 @Override
Madan Jampani7c521002015-03-23 12:23:01 -0700308 public CompletableFuture<Versioned<V>> put(K key, V value) {
309 checkNotNull(key, ERROR_NULL_KEY);
310 checkNotNull(value, ERROR_NULL_VALUE);
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700311 final MeteringAgent.Context timer = monitor.startTimer(PUT);
Flavio Castro5e1f1292015-07-23 17:14:09 -0700312 return updateAndGet(key, Match.any(), Match.any(), value).thenApply(v -> v.oldValue())
Flavio Castro6e044612015-08-13 14:13:58 -0700313 .whenComplete((r, e) -> timer.stop(e));
Madan Jampani346d4f52015-05-04 11:09:39 -0700314 }
315
316 @Override
317 public CompletableFuture<Versioned<V>> putAndGet(K key, V value) {
318 checkNotNull(key, ERROR_NULL_KEY);
319 checkNotNull(value, ERROR_NULL_VALUE);
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700320 final MeteringAgent.Context timer = monitor.startTimer(PUT_AND_GET);
Flavio Castro5e1f1292015-07-23 17:14:09 -0700321 return updateAndGet(key, Match.any(), Match.any(), value).thenApply(v -> v.newValue())
Flavio Castro6e044612015-08-13 14:13:58 -0700322 .whenComplete((r, e) -> timer.stop(e));
Madan Jampani7c521002015-03-23 12:23:01 -0700323 }
324
325 @Override
326 public CompletableFuture<Versioned<V>> remove(K key) {
327 checkNotNull(key, ERROR_NULL_KEY);
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700328 final MeteringAgent.Context timer = monitor.startTimer(REMOVE);
Flavio Castro5e1f1292015-07-23 17:14:09 -0700329 return updateAndGet(key, Match.any(), Match.any(), null).thenApply(v -> v.oldValue())
Flavio Castro6e044612015-08-13 14:13:58 -0700330 .whenComplete((r, e) -> timer.stop(e));
Madan Jampani7c521002015-03-23 12:23:01 -0700331 }
332
333 @Override
334 public CompletableFuture<Void> clear() {
Madan Jampani02b7fb82015-05-01 13:01:20 -0700335 checkIfUnmodifiable();
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700336 final MeteringAgent.Context timer = monitor.startTimer(CLEAR);
Flavio Castro5e1f1292015-07-23 17:14:09 -0700337 return database.mapClear(name).thenApply(this::unwrapResult)
Flavio Castro6e044612015-08-13 14:13:58 -0700338 .whenComplete((r, e) -> timer.stop(e));
Madan Jampani7c521002015-03-23 12:23:01 -0700339 }
340
341 @Override
342 public CompletableFuture<Set<K>> keySet() {
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700343 final MeteringAgent.Context timer = monitor.startTimer(KEY_SET);
Madan Jampani7804c992015-07-20 13:20:19 -0700344 return database.mapKeySet(name)
HIGUCHI Yuta14e865d2015-11-25 20:42:32 -0800345 .thenApply(s -> newMappingKeySet(s))
Flavio Castro6e044612015-08-13 14:13:58 -0700346 .whenComplete((r, e) -> timer.stop(e));
Madan Jampani7c521002015-03-23 12:23:01 -0700347 }
348
349 @Override
350 public CompletableFuture<Collection<Versioned<V>>> values() {
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700351 final MeteringAgent.Context timer = monitor.startTimer(VALUES);
Flavio Castro5e1f1292015-07-23 17:14:09 -0700352 return database.mapValues(name)
Flavio Castro6e044612015-08-13 14:13:58 -0700353 .whenComplete((r, e) -> timer.stop(e))
Flavio Castro5e1f1292015-07-23 17:14:09 -0700354 .thenApply(c -> c
355 .stream()
356 .map(v -> v.<V>map(serializer::decode))
357 .collect(Collectors.toList()));
Madan Jampani7c521002015-03-23 12:23:01 -0700358 }
359
360 @Override
361 public CompletableFuture<Set<Entry<K, Versioned<V>>>> entrySet() {
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700362 final MeteringAgent.Context timer = monitor.startTimer(ENTRY_SET);
Flavio Castro5e1f1292015-07-23 17:14:09 -0700363 return database.mapEntrySet(name)
Flavio Castro6e044612015-08-13 14:13:58 -0700364 .whenComplete((r, e) -> timer.stop(e))
HIGUCHI Yuta14e865d2015-11-25 20:42:32 -0800365 .thenApply(s -> newMappingEntrySet(s));
Madan Jampani7c521002015-03-23 12:23:01 -0700366 }
367
368 @Override
369 public CompletableFuture<Versioned<V>> putIfAbsent(K key, V value) {
370 checkNotNull(key, ERROR_NULL_KEY);
371 checkNotNull(value, ERROR_NULL_VALUE);
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700372 final MeteringAgent.Context timer = monitor.startTimer(PUT_IF_ABSENT);
Flavio Castro5e1f1292015-07-23 17:14:09 -0700373 return updateAndGet(key, Match.ifNull(), Match.any(), value)
Flavio Castro6e044612015-08-13 14:13:58 -0700374 .whenComplete((r, e) -> timer.stop(e))
Flavio Castro5e1f1292015-07-23 17:14:09 -0700375 .thenApply(v -> v.oldValue());
Madan Jampani7c521002015-03-23 12:23:01 -0700376 }
377
378 @Override
379 public CompletableFuture<Boolean> remove(K key, V value) {
380 checkNotNull(key, ERROR_NULL_KEY);
381 checkNotNull(value, ERROR_NULL_VALUE);
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700382 final MeteringAgent.Context timer = monitor.startTimer(REMOVE);
Flavio Castro5e1f1292015-07-23 17:14:09 -0700383 return updateAndGet(key, Match.ifValue(value), Match.any(), null)
Flavio Castro6e044612015-08-13 14:13:58 -0700384 .whenComplete((r, e) -> timer.stop(e))
Flavio Castro5e1f1292015-07-23 17:14:09 -0700385 .thenApply(v -> v.updated());
Madan Jampani7c521002015-03-23 12:23:01 -0700386 }
387
388 @Override
389 public CompletableFuture<Boolean> remove(K key, long version) {
390 checkNotNull(key, ERROR_NULL_KEY);
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700391 final MeteringAgent.Context timer = monitor.startTimer(REMOVE);
Flavio Castro5e1f1292015-07-23 17:14:09 -0700392 return updateAndGet(key, Match.any(), Match.ifValue(version), null)
Flavio Castro6e044612015-08-13 14:13:58 -0700393 .whenComplete((r, e) -> timer.stop(e))
Flavio Castro5e1f1292015-07-23 17:14:09 -0700394 .thenApply(v -> v.updated());
Madan Jampani7c521002015-03-23 12:23:01 -0700395 }
396
397 @Override
Jihwan Kim9887ad92015-12-12 00:23:57 +0900398 public CompletableFuture<Versioned<V>> replace(K key, V value) {
399 checkNotNull(key, ERROR_NULL_KEY);
400 checkNotNull(value, ERROR_NULL_VALUE);
401 final MeteringAgent.Context timer = monitor.startTimer(REPLACE);
402 return updateAndGet(key, Match.ifNotNull(), Match.any(), value)
403 .whenComplete((r, e) -> timer.stop(e))
404 .thenApply(v -> v.oldValue());
405 }
406
407 @Override
Madan Jampani7c521002015-03-23 12:23:01 -0700408 public CompletableFuture<Boolean> replace(K key, V oldValue, V newValue) {
409 checkNotNull(key, ERROR_NULL_KEY);
Madan Jampani7804c992015-07-20 13:20:19 -0700410 checkNotNull(oldValue, ERROR_NULL_VALUE);
Madan Jampani7c521002015-03-23 12:23:01 -0700411 checkNotNull(newValue, ERROR_NULL_VALUE);
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700412 final MeteringAgent.Context timer = monitor.startTimer(REPLACE);
Flavio Castro5e1f1292015-07-23 17:14:09 -0700413 return updateAndGet(key, Match.ifValue(oldValue), Match.any(), newValue)
Flavio Castro6e044612015-08-13 14:13:58 -0700414 .whenComplete((r, e) -> timer.stop(e))
Flavio Castro5e1f1292015-07-23 17:14:09 -0700415 .thenApply(v -> v.updated());
Madan Jampani7c521002015-03-23 12:23:01 -0700416 }
417
418 @Override
419 public CompletableFuture<Boolean> replace(K key, long oldVersion, V newValue) {
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700420 final MeteringAgent.Context timer = monitor.startTimer(REPLACE);
Flavio Castro5e1f1292015-07-23 17:14:09 -0700421 return updateAndGet(key, Match.any(), Match.ifValue(oldVersion), newValue)
Flavio Castro6e044612015-08-13 14:13:58 -0700422 .whenComplete((r, e) -> timer.stop(e))
Flavio Castro5e1f1292015-07-23 17:14:09 -0700423 .thenApply(v -> v.updated());
Madan Jampani346d4f52015-05-04 11:09:39 -0700424 }
425
Madan Jampani14a38da2015-11-16 11:29:00 -0800426 /**
427 * Pre-update hook for performing required checks/actions before going forward with an update operation.
428 * @param key map key.
429 */
430 protected void beforeUpdate(K key) {
431 checkIfUnmodifiable();
432 }
433
HIGUCHI Yuta14e865d2015-11-25 20:42:32 -0800434 private Set<K> newMappingKeySet(Set<String> s) {
435 return new MappingSet<>(s, Collections::unmodifiableSet,
436 this::sK, this::dK);
437 }
438
439 private Set<Entry<K, Versioned<V>>> newMappingEntrySet(Set<Entry<String, Versioned<byte[]>>> s) {
440 return new MappingSet<>(s, Collections::unmodifiableSet,
441 this::reverseMapRawEntry, this::mapRawEntry);
442 }
443
Madan Jampani7804c992015-07-20 13:20:19 -0700444 private Map.Entry<K, Versioned<V>> mapRawEntry(Map.Entry<String, Versioned<byte[]>> e) {
445 return Maps.immutableEntry(dK(e.getKey()), e.getValue().<V>map(serializer::decode));
446 }
447
HIGUCHI Yuta14e865d2015-11-25 20:42:32 -0800448 private Map.Entry<String, Versioned<byte[]>> reverseMapRawEntry(Map.Entry<K, Versioned<V>> e) {
449 return Maps.immutableEntry(sK(e.getKey()), e.getValue().map(serializer::encode));
450 }
451
Madan Jampani7804c992015-07-20 13:20:19 -0700452 private CompletableFuture<UpdateResult<K, V>> updateAndGet(K key,
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700453 Match<V> oldValueMatch,
454 Match<Long> oldVersionMatch,
455 V value) {
Madan Jampani14a38da2015-11-16 11:29:00 -0800456 beforeUpdate(key);
Madan Jampani7804c992015-07-20 13:20:19 -0700457 return database.mapUpdate(name,
HIGUCHI Yuta14e865d2015-11-25 20:42:32 -0800458 sK(key),
Flavio Castro5e1f1292015-07-23 17:14:09 -0700459 oldValueMatch.map(serializer::encode),
460 oldVersionMatch,
461 value == null ? null : serializer.encode(value))
Madan Jampani7804c992015-07-20 13:20:19 -0700462 .thenApply(this::unwrapResult)
Madan Jampani85668632015-08-10 10:46:40 -0700463 .thenApply(r -> r.<K, V>map(this::dK, serializer::decode));
Madan Jampani7c521002015-03-23 12:23:01 -0700464 }
Madan Jampanibff6d8f2015-03-31 16:53:47 -0700465
466 private <T> T unwrapResult(Result<T> result) {
467 if (result.status() == Result.Status.LOCKED) {
468 throw new ConsistentMapException.ConcurrentModification();
469 } else if (result.success()) {
470 return result.value();
471 } else {
472 throw new IllegalStateException("Must not be here");
473 }
474 }
Madan Jampani02b7fb82015-05-01 13:01:20 -0700475
476 private void checkIfUnmodifiable() {
477 if (readOnly) {
478 throw new UnsupportedOperationException();
479 }
480 }
Madan Jampani50589ac2015-06-08 11:38:46 -0700481
482 @Override
Madan Jampanidfde6ba2016-01-13 21:36:09 -0800483 public CompletableFuture<Void> addListener(MapEventListener<K, V> listener) {
Madan Jampani50589ac2015-06-08 11:38:46 -0700484 listeners.add(listener);
Madan Jampanidfde6ba2016-01-13 21:36:09 -0800485 return CompletableFuture.completedFuture(null);
Madan Jampani50589ac2015-06-08 11:38:46 -0700486 }
487
488 @Override
Madan Jampanidfde6ba2016-01-13 21:36:09 -0800489 public CompletableFuture<Void> removeListener(MapEventListener<K, V> listener) {
Madan Jampani50589ac2015-06-08 11:38:46 -0700490 listeners.remove(listener);
Madan Jampanidfde6ba2016-01-13 21:36:09 -0800491 return CompletableFuture.completedFuture(null);
Madan Jampani50589ac2015-06-08 11:38:46 -0700492 }
493
494 protected void notifyListeners(MapEvent<K, V> event) {
Madan Jampani85668632015-08-10 10:46:40 -0700495 if (event == null) {
496 return;
497 }
498 listeners.forEach(listener -> {
499 try {
500 listener.event(event);
501 } catch (Exception e) {
502 log.warn("Failure notifying listener about {}", event, e);
Madan Jampani50589ac2015-06-08 11:38:46 -0700503 }
Madan Jampani85668632015-08-10 10:46:40 -0700504 });
Madan Jampani50589ac2015-06-08 11:38:46 -0700505 }
Madan Jampanibab51a42015-08-10 13:53:35 -0700506}