blob: 46a097c7cf3b0a9597fd78fe481d58c60497269f [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
17package org.onosproject.store.consistent.impl;
18
Flavio Castro41b1f3a2015-07-31 13:51:32 -070019import com.google.common.cache.CacheBuilder;
20import com.google.common.cache.CacheLoader;
21import com.google.common.cache.LoadingCache;
22import com.google.common.collect.Maps;
HIGUCHI Yuta14e865d2015-11-25 20:42:32 -080023
Madan Jampani7c521002015-03-23 12:23:01 -070024import org.onlab.util.HexString;
Madan Jampanif2f086c2016-01-13 16:15:39 -080025import org.onlab.util.Match;
Madan Jampani648451f2015-07-21 22:09:05 -070026import org.onlab.util.SharedExecutors;
Madan Jampani346d4f52015-05-04 11:09:39 -070027import org.onlab.util.Tools;
Madan Jampanie8af1cc2015-06-23 14:23:31 -070028import org.onosproject.core.ApplicationId;
Madan Jampani7c521002015-03-23 12:23:01 -070029import org.onosproject.store.service.AsyncConsistentMap;
Madan Jampanibff6d8f2015-03-31 16:53:47 -070030import org.onosproject.store.service.ConsistentMapException;
Madan Jampanic7f49f92015-12-10 11:35:06 -080031import org.onosproject.store.service.ConsistentMapException.ConcurrentModification;
Madan Jampani50589ac2015-06-08 11:38:46 -070032import org.onosproject.store.service.MapEvent;
33import org.onosproject.store.service.MapEventListener;
Madan Jampani7c521002015-03-23 12:23:01 -070034import org.onosproject.store.service.Serializer;
35import org.onosproject.store.service.Versioned;
Madan Jampani50589ac2015-06-08 11:38:46 -070036import org.slf4j.Logger;
Madan Jampani7c521002015-03-23 12:23:01 -070037
Flavio Castro41b1f3a2015-07-31 13:51:32 -070038import java.util.Collection;
HIGUCHI Yuta14e865d2015-11-25 20:42:32 -080039import java.util.Collections;
Flavio Castro41b1f3a2015-07-31 13:51:32 -070040import java.util.Map;
41import java.util.Map.Entry;
42import java.util.Objects;
43import java.util.Set;
44import java.util.concurrent.CompletableFuture;
45import java.util.concurrent.CopyOnWriteArraySet;
46import java.util.concurrent.atomic.AtomicReference;
47import java.util.function.BiFunction;
48import java.util.function.Function;
49import java.util.function.Predicate;
50import java.util.stream.Collectors;
51
52import static com.google.common.base.Preconditions.checkNotNull;
Madan Jampania6d787b2015-08-11 11:02:02 -070053import static org.onosproject.store.consistent.impl.StateMachineUpdate.Target.MAP_UPDATE;
Madan Jampanibab51a42015-08-10 13:53:35 -070054import static org.onosproject.store.consistent.impl.StateMachineUpdate.Target.TX_COMMIT;
Flavio Castro41b1f3a2015-07-31 13:51:32 -070055import static org.slf4j.LoggerFactory.getLogger;
Madan Jampani7c521002015-03-23 12:23:01 -070056
57/**
58 * AsyncConsistentMap implementation that is backed by a Raft consensus
59 * based database.
60 *
61 * @param <K> type of key.
62 * @param <V> type of value.
63 */
Flavio Castro41b1f3a2015-07-31 13:51:32 -070064public class DefaultAsyncConsistentMap<K, V> implements AsyncConsistentMap<K, V> {
Madan Jampani7c521002015-03-23 12:23:01 -070065
66 private final String name;
Madan Jampanie8af1cc2015-06-23 14:23:31 -070067 private final ApplicationId applicationId;
Madan Jampanif1b8e172015-03-23 11:42:02 -070068 private final Database database;
Madan Jampani7c521002015-03-23 12:23:01 -070069 private final Serializer serializer;
Madan Jampani02b7fb82015-05-01 13:01:20 -070070 private final boolean readOnly;
Madan Jampanie8af1cc2015-06-23 14:23:31 -070071 private final boolean purgeOnUninstall;
Madan Jampani50589ac2015-06-08 11:38:46 -070072
Flavio Castro41b1f3a2015-07-31 13:51:32 -070073 private static final String PRIMITIVE_NAME = "consistentMap";
Flavio Castro5e1f1292015-07-23 17:14:09 -070074 private static final String SIZE = "size";
75 private static final String IS_EMPTY = "isEmpty";
76 private static final String CONTAINS_KEY = "containsKey";
77 private static final String CONTAINS_VALUE = "containsValue";
78 private static final String GET = "get";
79 private static final String COMPUTE_IF = "computeIf";
80 private static final String PUT = "put";
81 private static final String PUT_AND_GET = "putAndGet";
82 private static final String PUT_IF_ABSENT = "putIfAbsent";
83 private static final String REMOVE = "remove";
84 private static final String CLEAR = "clear";
85 private static final String KEY_SET = "keySet";
86 private static final String VALUES = "values";
87 private static final String ENTRY_SET = "entrySet";
88 private static final String REPLACE = "replace";
89 private static final String COMPUTE_IF_ABSENT = "computeIfAbsent";
90
Madan Jampani50589ac2015-06-08 11:38:46 -070091 private final Set<MapEventListener<K, V>> listeners = new CopyOnWriteArraySet<>();
92
93 private final Logger log = getLogger(getClass());
Flavio Castro41b1f3a2015-07-31 13:51:32 -070094 private final MeteringAgent monitor;
Madan Jampani7c521002015-03-23 12:23:01 -070095
96 private static final String ERROR_NULL_KEY = "Key cannot be null";
97 private static final String ERROR_NULL_VALUE = "Null values are not allowed";
98
HIGUCHI Yuta14e865d2015-11-25 20:42:32 -080099 // String representation of serialized byte[] -> original key Object
100 private final LoadingCache<String, K> keyCache = CacheBuilder.newBuilder()
Madan Jampani7c521002015-03-23 12:23:01 -0700101 .softValues()
HIGUCHI Yuta14e865d2015-11-25 20:42:32 -0800102 .build(new CacheLoader<String, K>() {
Madan Jampani7c521002015-03-23 12:23:01 -0700103
104 @Override
HIGUCHI Yuta14e865d2015-11-25 20:42:32 -0800105 public K load(String key) {
106 return serializer.decode(HexString.fromHexString(key));
Madan Jampani7c521002015-03-23 12:23:01 -0700107 }
108 });
109
HIGUCHI Yuta14e865d2015-11-25 20:42:32 -0800110 protected String sK(K key) {
111 String s = HexString.toHexString(serializer.encode(key));
112 keyCache.put(s, key);
113 return s;
114 }
115
Madan Jampani7c521002015-03-23 12:23:01 -0700116 protected K dK(String key) {
HIGUCHI Yuta14e865d2015-11-25 20:42:32 -0800117 return keyCache.getUnchecked(key);
Madan Jampani7c521002015-03-23 12:23:01 -0700118 }
119
120 public DefaultAsyncConsistentMap(String name,
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700121 ApplicationId applicationId,
122 Database database,
123 Serializer serializer,
124 boolean readOnly,
125 boolean purgeOnUninstall,
126 boolean meteringEnabled) {
Madan Jampani7c521002015-03-23 12:23:01 -0700127 this.name = checkNotNull(name, "map name cannot be null");
Madan Jampanie8af1cc2015-06-23 14:23:31 -0700128 this.applicationId = applicationId;
Madan Jampanif1b8e172015-03-23 11:42:02 -0700129 this.database = checkNotNull(database, "database cannot be null");
Madan Jampani7c521002015-03-23 12:23:01 -0700130 this.serializer = checkNotNull(serializer, "serializer cannot be null");
Madan Jampani02b7fb82015-05-01 13:01:20 -0700131 this.readOnly = readOnly;
Madan Jampanie8af1cc2015-06-23 14:23:31 -0700132 this.purgeOnUninstall = purgeOnUninstall;
Madan Jampani648451f2015-07-21 22:09:05 -0700133 this.database.registerConsumer(update -> {
134 SharedExecutors.getSingleThreadExecutor().execute(() -> {
Madan Jampani9eb55d12015-08-14 07:47:56 -0700135 if (listeners.isEmpty()) {
136 return;
137 }
138 try {
139 if (update.target() == MAP_UPDATE) {
140 Result<UpdateResult<String, byte[]>> result = update.output();
141 if (result.success() && result.value().mapName().equals(name)) {
142 MapEvent<K, V> mapEvent = result.value()
143 .<K, V>map(this::dK,
144 v -> serializer.decode(Tools.copyOf(v)))
145 .toMapEvent();
146 notifyListeners(mapEvent);
147 }
148 } else if (update.target() == TX_COMMIT) {
149 CommitResponse response = update.output();
150 if (response.success()) {
151 response.updates().forEach(u -> {
152 if (u.mapName().equals(name)) {
153 MapEvent<K, V> mapEvent =
154 u.<K, V>map(this::dK,
155 v -> serializer.decode(Tools.copyOf(v)))
156 .toMapEvent();
157 notifyListeners(mapEvent);
158 }
159 });
160 }
Madan Jampani648451f2015-07-21 22:09:05 -0700161 }
Madan Jampani9eb55d12015-08-14 07:47:56 -0700162 } catch (Exception e) {
163 log.warn("Error notifying listeners", e);
Madan Jampani648451f2015-07-21 22:09:05 -0700164 }
165 });
166 });
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700167 this.monitor = new MeteringAgent(PRIMITIVE_NAME, name, meteringEnabled);
Madan Jampani50589ac2015-06-08 11:38:46 -0700168 }
169
170 /**
171 * Returns this map name.
172 * @return map name
173 */
174 public String name() {
175 return name;
176 }
177
178 /**
179 * Returns the serializer for map entries.
180 * @return map entry serializer
181 */
182 public Serializer serializer() {
183 return serializer;
Madan Jampani7c521002015-03-23 12:23:01 -0700184 }
185
Madan Jampanie8af1cc2015-06-23 14:23:31 -0700186 /**
187 * Returns the applicationId owning this map.
188 * @return application Id
189 */
190 public ApplicationId applicationId() {
191 return applicationId;
192 }
193
194 /**
195 * Returns whether the map entries should be purged when the application
196 * owning it is uninstalled.
197 * @return true is map needs to cleared on app uninstall; false otherwise
198 */
199 public boolean purgeOnUninstall() {
200 return purgeOnUninstall;
201 }
202
Madan Jampani7c521002015-03-23 12:23:01 -0700203 @Override
204 public CompletableFuture<Integer> size() {
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700205 final MeteringAgent.Context timer = monitor.startTimer(SIZE);
Flavio Castro5e1f1292015-07-23 17:14:09 -0700206 return database.mapSize(name)
Flavio Castro6e044612015-08-13 14:13:58 -0700207 .whenComplete((r, e) -> timer.stop(e));
Madan Jampani7c521002015-03-23 12:23:01 -0700208 }
209
210 @Override
211 public CompletableFuture<Boolean> isEmpty() {
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700212 final MeteringAgent.Context timer = monitor.startTimer(IS_EMPTY);
Flavio Castro5e1f1292015-07-23 17:14:09 -0700213 return database.mapIsEmpty(name)
Flavio Castro6e044612015-08-13 14:13:58 -0700214 .whenComplete((r, e) -> timer.stop(e));
Madan Jampani7c521002015-03-23 12:23:01 -0700215 }
216
217 @Override
218 public CompletableFuture<Boolean> containsKey(K key) {
219 checkNotNull(key, ERROR_NULL_KEY);
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700220 final MeteringAgent.Context timer = monitor.startTimer(CONTAINS_KEY);
HIGUCHI Yuta14e865d2015-11-25 20:42:32 -0800221 return database.mapContainsKey(name, sK(key))
Flavio Castro6e044612015-08-13 14:13:58 -0700222 .whenComplete((r, e) -> timer.stop(e));
Madan Jampani7c521002015-03-23 12:23:01 -0700223 }
224
225 @Override
226 public CompletableFuture<Boolean> containsValue(V value) {
227 checkNotNull(value, ERROR_NULL_VALUE);
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700228 final MeteringAgent.Context timer = monitor.startTimer(CONTAINS_VALUE);
Flavio Castro5e1f1292015-07-23 17:14:09 -0700229 return database.mapContainsValue(name, serializer.encode(value))
Flavio Castro6e044612015-08-13 14:13:58 -0700230 .whenComplete((r, e) -> timer.stop(e));
Madan Jampani7c521002015-03-23 12:23:01 -0700231 }
232
233 @Override
234 public CompletableFuture<Versioned<V>> get(K key) {
235 checkNotNull(key, ERROR_NULL_KEY);
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700236 final MeteringAgent.Context timer = monitor.startTimer(GET);
HIGUCHI Yuta14e865d2015-11-25 20:42:32 -0800237 return database.mapGet(name, sK(key))
Flavio Castro6e044612015-08-13 14:13:58 -0700238 .whenComplete((r, e) -> timer.stop(e))
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700239 .thenApply(v -> v != null ? v.map(serializer::decode) : null);
Madan Jampani7c521002015-03-23 12:23:01 -0700240 }
241
242 @Override
Madan Jampani346d4f52015-05-04 11:09:39 -0700243 public CompletableFuture<Versioned<V>> computeIfAbsent(K key,
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700244 Function<? super K, ? extends V> mappingFunction) {
Madan Jampani7804c992015-07-20 13:20:19 -0700245 checkNotNull(key, ERROR_NULL_KEY);
246 checkNotNull(mappingFunction, "Mapping function cannot be null");
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700247 final MeteringAgent.Context timer = monitor.startTimer(COMPUTE_IF_ABSENT);
Flavio Castro5e1f1292015-07-23 17:14:09 -0700248 return updateAndGet(key, Match.ifNull(), Match.any(), mappingFunction.apply(key))
Flavio Castro6e044612015-08-13 14:13:58 -0700249 .whenComplete((r, e) -> timer.stop(e))
Flavio Castro5e1f1292015-07-23 17:14:09 -0700250 .thenApply(v -> v.newValue());
Madan Jampani346d4f52015-05-04 11:09:39 -0700251 }
252
253 @Override
254 public CompletableFuture<Versioned<V>> computeIfPresent(K key,
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700255 BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
Madan Jampani346d4f52015-05-04 11:09:39 -0700256 return computeIf(key, Objects::nonNull, remappingFunction);
257 }
258
259 @Override
260 public CompletableFuture<Versioned<V>> compute(K key,
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700261 BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
Madan Jampani346d4f52015-05-04 11:09:39 -0700262 return computeIf(key, v -> true, remappingFunction);
263 }
264
265 @Override
266 public CompletableFuture<Versioned<V>> computeIf(K key,
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700267 Predicate<? super V> condition,
268 BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
Madan Jampani346d4f52015-05-04 11:09:39 -0700269 checkNotNull(key, ERROR_NULL_KEY);
270 checkNotNull(condition, "predicate function cannot be null");
271 checkNotNull(remappingFunction, "Remapping function cannot be null");
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700272 final MeteringAgent.Context timer = monitor.startTimer(COMPUTE_IF);
Madan Jampani346d4f52015-05-04 11:09:39 -0700273 return get(key).thenCompose(r1 -> {
274 V existingValue = r1 == null ? null : r1.value();
275 // if the condition evaluates to false, return existing value.
276 if (!condition.test(existingValue)) {
277 return CompletableFuture.completedFuture(r1);
278 }
279
280 AtomicReference<V> computedValue = new AtomicReference<>();
281 // if remappingFunction throws an exception, return the exception.
282 try {
283 computedValue.set(remappingFunction.apply(key, existingValue));
284 } catch (Exception e) {
285 return Tools.exceptionalFuture(e);
286 }
Madan Jampani7804c992015-07-20 13:20:19 -0700287 if (computedValue.get() == null && r1 == null) {
288 return CompletableFuture.completedFuture(null);
Madan Jampani346d4f52015-05-04 11:09:39 -0700289 }
Madan Jampani7804c992015-07-20 13:20:19 -0700290 Match<V> valueMatcher = r1 == null ? Match.ifNull() : Match.any();
291 Match<Long> versionMatcher = r1 == null ? Match.any() : Match.ifValue(r1.version());
292 return updateAndGet(key, valueMatcher, versionMatcher, computedValue.get())
Flavio Castro6e044612015-08-13 14:13:58 -0700293 .whenComplete((r, e) -> timer.stop(e))
Madan Jampani7804c992015-07-20 13:20:19 -0700294 .thenApply(v -> {
295 if (v.updated()) {
296 return v.newValue();
297 } else {
Madan Jampanic7f49f92015-12-10 11:35:06 -0800298 throw new ConcurrentModification("Concurrent update to " + name + " detected");
Madan Jampani7804c992015-07-20 13:20:19 -0700299 }
300 });
301 });
Madan Jampani346d4f52015-05-04 11:09:39 -0700302 }
303
304 @Override
Madan Jampani7c521002015-03-23 12:23:01 -0700305 public CompletableFuture<Versioned<V>> put(K key, V value) {
306 checkNotNull(key, ERROR_NULL_KEY);
307 checkNotNull(value, ERROR_NULL_VALUE);
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700308 final MeteringAgent.Context timer = monitor.startTimer(PUT);
Flavio Castro5e1f1292015-07-23 17:14:09 -0700309 return updateAndGet(key, Match.any(), Match.any(), value).thenApply(v -> v.oldValue())
Flavio Castro6e044612015-08-13 14:13:58 -0700310 .whenComplete((r, e) -> timer.stop(e));
Madan Jampani346d4f52015-05-04 11:09:39 -0700311 }
312
313 @Override
314 public CompletableFuture<Versioned<V>> putAndGet(K key, V value) {
315 checkNotNull(key, ERROR_NULL_KEY);
316 checkNotNull(value, ERROR_NULL_VALUE);
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700317 final MeteringAgent.Context timer = monitor.startTimer(PUT_AND_GET);
Flavio Castro5e1f1292015-07-23 17:14:09 -0700318 return updateAndGet(key, Match.any(), Match.any(), value).thenApply(v -> v.newValue())
Flavio Castro6e044612015-08-13 14:13:58 -0700319 .whenComplete((r, e) -> timer.stop(e));
Madan Jampani7c521002015-03-23 12:23:01 -0700320 }
321
322 @Override
323 public CompletableFuture<Versioned<V>> remove(K key) {
324 checkNotNull(key, ERROR_NULL_KEY);
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700325 final MeteringAgent.Context timer = monitor.startTimer(REMOVE);
Flavio Castro5e1f1292015-07-23 17:14:09 -0700326 return updateAndGet(key, Match.any(), Match.any(), null).thenApply(v -> v.oldValue())
Flavio Castro6e044612015-08-13 14:13:58 -0700327 .whenComplete((r, e) -> timer.stop(e));
Madan Jampani7c521002015-03-23 12:23:01 -0700328 }
329
330 @Override
331 public CompletableFuture<Void> clear() {
Madan Jampani02b7fb82015-05-01 13:01:20 -0700332 checkIfUnmodifiable();
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700333 final MeteringAgent.Context timer = monitor.startTimer(CLEAR);
Flavio Castro5e1f1292015-07-23 17:14:09 -0700334 return database.mapClear(name).thenApply(this::unwrapResult)
Flavio Castro6e044612015-08-13 14:13:58 -0700335 .whenComplete((r, e) -> timer.stop(e));
Madan Jampani7c521002015-03-23 12:23:01 -0700336 }
337
338 @Override
339 public CompletableFuture<Set<K>> keySet() {
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700340 final MeteringAgent.Context timer = monitor.startTimer(KEY_SET);
Madan Jampani7804c992015-07-20 13:20:19 -0700341 return database.mapKeySet(name)
HIGUCHI Yuta14e865d2015-11-25 20:42:32 -0800342 .thenApply(s -> newMappingKeySet(s))
Flavio Castro6e044612015-08-13 14:13:58 -0700343 .whenComplete((r, e) -> timer.stop(e));
Madan Jampani7c521002015-03-23 12:23:01 -0700344 }
345
346 @Override
347 public CompletableFuture<Collection<Versioned<V>>> values() {
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700348 final MeteringAgent.Context timer = monitor.startTimer(VALUES);
Flavio Castro5e1f1292015-07-23 17:14:09 -0700349 return database.mapValues(name)
Flavio Castro6e044612015-08-13 14:13:58 -0700350 .whenComplete((r, e) -> timer.stop(e))
Flavio Castro5e1f1292015-07-23 17:14:09 -0700351 .thenApply(c -> c
352 .stream()
353 .map(v -> v.<V>map(serializer::decode))
354 .collect(Collectors.toList()));
Madan Jampani7c521002015-03-23 12:23:01 -0700355 }
356
357 @Override
358 public CompletableFuture<Set<Entry<K, Versioned<V>>>> entrySet() {
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700359 final MeteringAgent.Context timer = monitor.startTimer(ENTRY_SET);
Flavio Castro5e1f1292015-07-23 17:14:09 -0700360 return database.mapEntrySet(name)
Flavio Castro6e044612015-08-13 14:13:58 -0700361 .whenComplete((r, e) -> timer.stop(e))
HIGUCHI Yuta14e865d2015-11-25 20:42:32 -0800362 .thenApply(s -> newMappingEntrySet(s));
Madan Jampani7c521002015-03-23 12:23:01 -0700363 }
364
365 @Override
366 public CompletableFuture<Versioned<V>> putIfAbsent(K key, V value) {
367 checkNotNull(key, ERROR_NULL_KEY);
368 checkNotNull(value, ERROR_NULL_VALUE);
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700369 final MeteringAgent.Context timer = monitor.startTimer(PUT_IF_ABSENT);
Flavio Castro5e1f1292015-07-23 17:14:09 -0700370 return updateAndGet(key, Match.ifNull(), Match.any(), value)
Flavio Castro6e044612015-08-13 14:13:58 -0700371 .whenComplete((r, e) -> timer.stop(e))
Flavio Castro5e1f1292015-07-23 17:14:09 -0700372 .thenApply(v -> v.oldValue());
Madan Jampani7c521002015-03-23 12:23:01 -0700373 }
374
375 @Override
376 public CompletableFuture<Boolean> remove(K key, V value) {
377 checkNotNull(key, ERROR_NULL_KEY);
378 checkNotNull(value, ERROR_NULL_VALUE);
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700379 final MeteringAgent.Context timer = monitor.startTimer(REMOVE);
Flavio Castro5e1f1292015-07-23 17:14:09 -0700380 return updateAndGet(key, Match.ifValue(value), Match.any(), null)
Flavio Castro6e044612015-08-13 14:13:58 -0700381 .whenComplete((r, e) -> timer.stop(e))
Flavio Castro5e1f1292015-07-23 17:14:09 -0700382 .thenApply(v -> v.updated());
Madan Jampani7c521002015-03-23 12:23:01 -0700383 }
384
385 @Override
386 public CompletableFuture<Boolean> remove(K key, long version) {
387 checkNotNull(key, ERROR_NULL_KEY);
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700388 final MeteringAgent.Context timer = monitor.startTimer(REMOVE);
Flavio Castro5e1f1292015-07-23 17:14:09 -0700389 return updateAndGet(key, Match.any(), Match.ifValue(version), null)
Flavio Castro6e044612015-08-13 14:13:58 -0700390 .whenComplete((r, e) -> timer.stop(e))
Flavio Castro5e1f1292015-07-23 17:14:09 -0700391 .thenApply(v -> v.updated());
Madan Jampani7c521002015-03-23 12:23:01 -0700392 }
393
394 @Override
Jihwan Kim9887ad92015-12-12 00:23:57 +0900395 public CompletableFuture<Versioned<V>> replace(K key, V value) {
396 checkNotNull(key, ERROR_NULL_KEY);
397 checkNotNull(value, ERROR_NULL_VALUE);
398 final MeteringAgent.Context timer = monitor.startTimer(REPLACE);
399 return updateAndGet(key, Match.ifNotNull(), Match.any(), value)
400 .whenComplete((r, e) -> timer.stop(e))
401 .thenApply(v -> v.oldValue());
402 }
403
404 @Override
Madan Jampani7c521002015-03-23 12:23:01 -0700405 public CompletableFuture<Boolean> replace(K key, V oldValue, V newValue) {
406 checkNotNull(key, ERROR_NULL_KEY);
Madan Jampani7804c992015-07-20 13:20:19 -0700407 checkNotNull(oldValue, ERROR_NULL_VALUE);
Madan Jampani7c521002015-03-23 12:23:01 -0700408 checkNotNull(newValue, ERROR_NULL_VALUE);
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700409 final MeteringAgent.Context timer = monitor.startTimer(REPLACE);
Flavio Castro5e1f1292015-07-23 17:14:09 -0700410 return updateAndGet(key, Match.ifValue(oldValue), Match.any(), newValue)
Flavio Castro6e044612015-08-13 14:13:58 -0700411 .whenComplete((r, e) -> timer.stop(e))
Flavio Castro5e1f1292015-07-23 17:14:09 -0700412 .thenApply(v -> v.updated());
Madan Jampani7c521002015-03-23 12:23:01 -0700413 }
414
415 @Override
416 public CompletableFuture<Boolean> replace(K key, long oldVersion, V newValue) {
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700417 final MeteringAgent.Context timer = monitor.startTimer(REPLACE);
Flavio Castro5e1f1292015-07-23 17:14:09 -0700418 return updateAndGet(key, Match.any(), Match.ifValue(oldVersion), newValue)
Flavio Castro6e044612015-08-13 14:13:58 -0700419 .whenComplete((r, e) -> timer.stop(e))
Flavio Castro5e1f1292015-07-23 17:14:09 -0700420 .thenApply(v -> v.updated());
Madan Jampani346d4f52015-05-04 11:09:39 -0700421 }
422
Madan Jampani14a38da2015-11-16 11:29:00 -0800423 /**
424 * Pre-update hook for performing required checks/actions before going forward with an update operation.
425 * @param key map key.
426 */
427 protected void beforeUpdate(K key) {
428 checkIfUnmodifiable();
429 }
430
HIGUCHI Yuta14e865d2015-11-25 20:42:32 -0800431 private Set<K> newMappingKeySet(Set<String> s) {
432 return new MappingSet<>(s, Collections::unmodifiableSet,
433 this::sK, this::dK);
434 }
435
436 private Set<Entry<K, Versioned<V>>> newMappingEntrySet(Set<Entry<String, Versioned<byte[]>>> s) {
437 return new MappingSet<>(s, Collections::unmodifiableSet,
438 this::reverseMapRawEntry, this::mapRawEntry);
439 }
440
Madan Jampani7804c992015-07-20 13:20:19 -0700441 private Map.Entry<K, Versioned<V>> mapRawEntry(Map.Entry<String, Versioned<byte[]>> e) {
442 return Maps.immutableEntry(dK(e.getKey()), e.getValue().<V>map(serializer::decode));
443 }
444
HIGUCHI Yuta14e865d2015-11-25 20:42:32 -0800445 private Map.Entry<String, Versioned<byte[]>> reverseMapRawEntry(Map.Entry<K, Versioned<V>> e) {
446 return Maps.immutableEntry(sK(e.getKey()), e.getValue().map(serializer::encode));
447 }
448
Madan Jampani7804c992015-07-20 13:20:19 -0700449 private CompletableFuture<UpdateResult<K, V>> updateAndGet(K key,
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700450 Match<V> oldValueMatch,
451 Match<Long> oldVersionMatch,
452 V value) {
Madan Jampani14a38da2015-11-16 11:29:00 -0800453 beforeUpdate(key);
Madan Jampani7804c992015-07-20 13:20:19 -0700454 return database.mapUpdate(name,
HIGUCHI Yuta14e865d2015-11-25 20:42:32 -0800455 sK(key),
Flavio Castro5e1f1292015-07-23 17:14:09 -0700456 oldValueMatch.map(serializer::encode),
457 oldVersionMatch,
458 value == null ? null : serializer.encode(value))
Madan Jampani7804c992015-07-20 13:20:19 -0700459 .thenApply(this::unwrapResult)
Madan Jampani85668632015-08-10 10:46:40 -0700460 .thenApply(r -> r.<K, V>map(this::dK, serializer::decode));
Madan Jampani7c521002015-03-23 12:23:01 -0700461 }
Madan Jampanibff6d8f2015-03-31 16:53:47 -0700462
463 private <T> T unwrapResult(Result<T> result) {
464 if (result.status() == Result.Status.LOCKED) {
465 throw new ConsistentMapException.ConcurrentModification();
466 } else if (result.success()) {
467 return result.value();
468 } else {
469 throw new IllegalStateException("Must not be here");
470 }
471 }
Madan Jampani02b7fb82015-05-01 13:01:20 -0700472
473 private void checkIfUnmodifiable() {
474 if (readOnly) {
475 throw new UnsupportedOperationException();
476 }
477 }
Madan Jampani50589ac2015-06-08 11:38:46 -0700478
479 @Override
Madan Jampanidfde6ba2016-01-13 21:36:09 -0800480 public CompletableFuture<Void> addListener(MapEventListener<K, V> listener) {
Madan Jampani50589ac2015-06-08 11:38:46 -0700481 listeners.add(listener);
Madan Jampanidfde6ba2016-01-13 21:36:09 -0800482 return CompletableFuture.completedFuture(null);
Madan Jampani50589ac2015-06-08 11:38:46 -0700483 }
484
485 @Override
Madan Jampanidfde6ba2016-01-13 21:36:09 -0800486 public CompletableFuture<Void> removeListener(MapEventListener<K, V> listener) {
Madan Jampani50589ac2015-06-08 11:38:46 -0700487 listeners.remove(listener);
Madan Jampanidfde6ba2016-01-13 21:36:09 -0800488 return CompletableFuture.completedFuture(null);
Madan Jampani50589ac2015-06-08 11:38:46 -0700489 }
490
491 protected void notifyListeners(MapEvent<K, V> event) {
Madan Jampani85668632015-08-10 10:46:40 -0700492 if (event == null) {
493 return;
494 }
495 listeners.forEach(listener -> {
496 try {
497 listener.event(event);
498 } catch (Exception e) {
499 log.warn("Failure notifying listener about {}", event, e);
Madan Jampani50589ac2015-06-08 11:38:46 -0700500 }
Madan Jampani85668632015-08-10 10:46:40 -0700501 });
Madan Jampani50589ac2015-06-08 11:38:46 -0700502 }
Madan Jampanibab51a42015-08-10 13:53:35 -0700503}