blob: 7c2613e83d2512af593a180018ba6c32d7503930 [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 Jampani648451f2015-07-21 22:09:05 -070025import org.onlab.util.SharedExecutors;
Madan Jampani346d4f52015-05-04 11:09:39 -070026import org.onlab.util.Tools;
Madan Jampanie8af1cc2015-06-23 14:23:31 -070027import org.onosproject.core.ApplicationId;
Madan Jampani7c521002015-03-23 12:23:01 -070028import org.onosproject.store.service.AsyncConsistentMap;
Madan Jampanibff6d8f2015-03-31 16:53:47 -070029import org.onosproject.store.service.ConsistentMapException;
Madan Jampanic7f49f92015-12-10 11:35:06 -080030import org.onosproject.store.service.ConsistentMapException.ConcurrentModification;
Madan Jampani50589ac2015-06-08 11:38:46 -070031import org.onosproject.store.service.MapEvent;
32import org.onosproject.store.service.MapEventListener;
Madan Jampani7c521002015-03-23 12:23:01 -070033import org.onosproject.store.service.Serializer;
34import org.onosproject.store.service.Versioned;
Madan Jampani50589ac2015-06-08 11:38:46 -070035import org.slf4j.Logger;
Madan Jampani7c521002015-03-23 12:23:01 -070036
Flavio Castro41b1f3a2015-07-31 13:51:32 -070037import java.util.Collection;
HIGUCHI Yuta14e865d2015-11-25 20:42:32 -080038import java.util.Collections;
Flavio Castro41b1f3a2015-07-31 13:51:32 -070039import java.util.Map;
40import java.util.Map.Entry;
41import java.util.Objects;
42import java.util.Set;
43import java.util.concurrent.CompletableFuture;
44import java.util.concurrent.CopyOnWriteArraySet;
45import java.util.concurrent.atomic.AtomicReference;
46import java.util.function.BiFunction;
47import java.util.function.Function;
48import java.util.function.Predicate;
49import java.util.stream.Collectors;
50
51import static com.google.common.base.Preconditions.checkNotNull;
Madan Jampania6d787b2015-08-11 11:02:02 -070052import static org.onosproject.store.consistent.impl.StateMachineUpdate.Target.MAP_UPDATE;
Madan Jampanibab51a42015-08-10 13:53:35 -070053import static org.onosproject.store.consistent.impl.StateMachineUpdate.Target.TX_COMMIT;
Flavio Castro41b1f3a2015-07-31 13:51:32 -070054import static org.slf4j.LoggerFactory.getLogger;
Madan Jampani7c521002015-03-23 12:23:01 -070055
56/**
57 * AsyncConsistentMap implementation that is backed by a Raft consensus
58 * based database.
59 *
60 * @param <K> type of key.
61 * @param <V> type of value.
62 */
Flavio Castro41b1f3a2015-07-31 13:51:32 -070063public class DefaultAsyncConsistentMap<K, V> implements AsyncConsistentMap<K, V> {
Madan Jampani7c521002015-03-23 12:23:01 -070064
65 private final String name;
Madan Jampanie8af1cc2015-06-23 14:23:31 -070066 private final ApplicationId applicationId;
Madan Jampanif1b8e172015-03-23 11:42:02 -070067 private final Database database;
Madan Jampani7c521002015-03-23 12:23:01 -070068 private final Serializer serializer;
Madan Jampani02b7fb82015-05-01 13:01:20 -070069 private final boolean readOnly;
Madan Jampanie8af1cc2015-06-23 14:23:31 -070070 private final boolean purgeOnUninstall;
Madan Jampani50589ac2015-06-08 11:38:46 -070071
Flavio Castro41b1f3a2015-07-31 13:51:32 -070072 private static final String PRIMITIVE_NAME = "consistentMap";
Flavio Castro5e1f1292015-07-23 17:14:09 -070073 private static final String SIZE = "size";
74 private static final String IS_EMPTY = "isEmpty";
75 private static final String CONTAINS_KEY = "containsKey";
76 private static final String CONTAINS_VALUE = "containsValue";
77 private static final String GET = "get";
78 private static final String COMPUTE_IF = "computeIf";
79 private static final String PUT = "put";
80 private static final String PUT_AND_GET = "putAndGet";
81 private static final String PUT_IF_ABSENT = "putIfAbsent";
82 private static final String REMOVE = "remove";
83 private static final String CLEAR = "clear";
84 private static final String KEY_SET = "keySet";
85 private static final String VALUES = "values";
86 private static final String ENTRY_SET = "entrySet";
87 private static final String REPLACE = "replace";
88 private static final String COMPUTE_IF_ABSENT = "computeIfAbsent";
89
Madan Jampani50589ac2015-06-08 11:38:46 -070090 private final Set<MapEventListener<K, V>> listeners = new CopyOnWriteArraySet<>();
91
92 private final Logger log = getLogger(getClass());
Flavio Castro41b1f3a2015-07-31 13:51:32 -070093 private final MeteringAgent monitor;
Madan Jampani7c521002015-03-23 12:23:01 -070094
95 private static final String ERROR_NULL_KEY = "Key cannot be null";
96 private static final String ERROR_NULL_VALUE = "Null values are not allowed";
97
HIGUCHI Yuta14e865d2015-11-25 20:42:32 -080098 // String representation of serialized byte[] -> original key Object
99 private final LoadingCache<String, K> keyCache = CacheBuilder.newBuilder()
Madan Jampani7c521002015-03-23 12:23:01 -0700100 .softValues()
HIGUCHI Yuta14e865d2015-11-25 20:42:32 -0800101 .build(new CacheLoader<String, K>() {
Madan Jampani7c521002015-03-23 12:23:01 -0700102
103 @Override
HIGUCHI Yuta14e865d2015-11-25 20:42:32 -0800104 public K load(String key) {
105 return serializer.decode(HexString.fromHexString(key));
Madan Jampani7c521002015-03-23 12:23:01 -0700106 }
107 });
108
HIGUCHI Yuta14e865d2015-11-25 20:42:32 -0800109 protected String sK(K key) {
110 String s = HexString.toHexString(serializer.encode(key));
111 keyCache.put(s, key);
112 return s;
113 }
114
Madan Jampani7c521002015-03-23 12:23:01 -0700115 protected K dK(String key) {
HIGUCHI Yuta14e865d2015-11-25 20:42:32 -0800116 return keyCache.getUnchecked(key);
Madan Jampani7c521002015-03-23 12:23:01 -0700117 }
118
119 public DefaultAsyncConsistentMap(String name,
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700120 ApplicationId applicationId,
121 Database database,
122 Serializer serializer,
123 boolean readOnly,
124 boolean purgeOnUninstall,
125 boolean meteringEnabled) {
Madan Jampani7c521002015-03-23 12:23:01 -0700126 this.name = checkNotNull(name, "map name cannot be null");
Madan Jampanie8af1cc2015-06-23 14:23:31 -0700127 this.applicationId = applicationId;
Madan Jampanif1b8e172015-03-23 11:42:02 -0700128 this.database = checkNotNull(database, "database cannot be null");
Madan Jampani7c521002015-03-23 12:23:01 -0700129 this.serializer = checkNotNull(serializer, "serializer cannot be null");
Madan Jampani02b7fb82015-05-01 13:01:20 -0700130 this.readOnly = readOnly;
Madan Jampanie8af1cc2015-06-23 14:23:31 -0700131 this.purgeOnUninstall = purgeOnUninstall;
Madan Jampani648451f2015-07-21 22:09:05 -0700132 this.database.registerConsumer(update -> {
133 SharedExecutors.getSingleThreadExecutor().execute(() -> {
Madan Jampani9eb55d12015-08-14 07:47:56 -0700134 if (listeners.isEmpty()) {
135 return;
136 }
137 try {
138 if (update.target() == MAP_UPDATE) {
139 Result<UpdateResult<String, byte[]>> result = update.output();
140 if (result.success() && result.value().mapName().equals(name)) {
141 MapEvent<K, V> mapEvent = result.value()
142 .<K, V>map(this::dK,
143 v -> serializer.decode(Tools.copyOf(v)))
144 .toMapEvent();
145 notifyListeners(mapEvent);
146 }
147 } else if (update.target() == TX_COMMIT) {
148 CommitResponse response = update.output();
149 if (response.success()) {
150 response.updates().forEach(u -> {
151 if (u.mapName().equals(name)) {
152 MapEvent<K, V> mapEvent =
153 u.<K, V>map(this::dK,
154 v -> serializer.decode(Tools.copyOf(v)))
155 .toMapEvent();
156 notifyListeners(mapEvent);
157 }
158 });
159 }
Madan Jampani648451f2015-07-21 22:09:05 -0700160 }
Madan Jampani9eb55d12015-08-14 07:47:56 -0700161 } catch (Exception e) {
162 log.warn("Error notifying listeners", e);
Madan Jampani648451f2015-07-21 22:09:05 -0700163 }
164 });
165 });
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700166 this.monitor = new MeteringAgent(PRIMITIVE_NAME, name, meteringEnabled);
Madan Jampani50589ac2015-06-08 11:38:46 -0700167 }
168
169 /**
170 * Returns this map name.
171 * @return map name
172 */
173 public String name() {
174 return name;
175 }
176
177 /**
178 * Returns the serializer for map entries.
179 * @return map entry serializer
180 */
181 public Serializer serializer() {
182 return serializer;
Madan Jampani7c521002015-03-23 12:23:01 -0700183 }
184
Madan Jampanie8af1cc2015-06-23 14:23:31 -0700185 /**
186 * Returns the applicationId owning this map.
187 * @return application Id
188 */
189 public ApplicationId applicationId() {
190 return applicationId;
191 }
192
193 /**
194 * Returns whether the map entries should be purged when the application
195 * owning it is uninstalled.
196 * @return true is map needs to cleared on app uninstall; false otherwise
197 */
198 public boolean purgeOnUninstall() {
199 return purgeOnUninstall;
200 }
201
Madan Jampani7c521002015-03-23 12:23:01 -0700202 @Override
203 public CompletableFuture<Integer> size() {
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700204 final MeteringAgent.Context timer = monitor.startTimer(SIZE);
Flavio Castro5e1f1292015-07-23 17:14:09 -0700205 return database.mapSize(name)
Flavio Castro6e044612015-08-13 14:13:58 -0700206 .whenComplete((r, e) -> timer.stop(e));
Madan Jampani7c521002015-03-23 12:23:01 -0700207 }
208
209 @Override
210 public CompletableFuture<Boolean> isEmpty() {
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700211 final MeteringAgent.Context timer = monitor.startTimer(IS_EMPTY);
Flavio Castro5e1f1292015-07-23 17:14:09 -0700212 return database.mapIsEmpty(name)
Flavio Castro6e044612015-08-13 14:13:58 -0700213 .whenComplete((r, e) -> timer.stop(e));
Madan Jampani7c521002015-03-23 12:23:01 -0700214 }
215
216 @Override
217 public CompletableFuture<Boolean> containsKey(K key) {
218 checkNotNull(key, ERROR_NULL_KEY);
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700219 final MeteringAgent.Context timer = monitor.startTimer(CONTAINS_KEY);
HIGUCHI Yuta14e865d2015-11-25 20:42:32 -0800220 return database.mapContainsKey(name, sK(key))
Flavio Castro6e044612015-08-13 14:13:58 -0700221 .whenComplete((r, e) -> timer.stop(e));
Madan Jampani7c521002015-03-23 12:23:01 -0700222 }
223
224 @Override
225 public CompletableFuture<Boolean> containsValue(V value) {
226 checkNotNull(value, ERROR_NULL_VALUE);
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700227 final MeteringAgent.Context timer = monitor.startTimer(CONTAINS_VALUE);
Flavio Castro5e1f1292015-07-23 17:14:09 -0700228 return database.mapContainsValue(name, serializer.encode(value))
Flavio Castro6e044612015-08-13 14:13:58 -0700229 .whenComplete((r, e) -> timer.stop(e));
Madan Jampani7c521002015-03-23 12:23:01 -0700230 }
231
232 @Override
233 public CompletableFuture<Versioned<V>> get(K key) {
234 checkNotNull(key, ERROR_NULL_KEY);
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700235 final MeteringAgent.Context timer = monitor.startTimer(GET);
HIGUCHI Yuta14e865d2015-11-25 20:42:32 -0800236 return database.mapGet(name, sK(key))
Flavio Castro6e044612015-08-13 14:13:58 -0700237 .whenComplete((r, e) -> timer.stop(e))
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700238 .thenApply(v -> v != null ? v.map(serializer::decode) : null);
Madan Jampani7c521002015-03-23 12:23:01 -0700239 }
240
241 @Override
Madan Jampani346d4f52015-05-04 11:09:39 -0700242 public CompletableFuture<Versioned<V>> computeIfAbsent(K key,
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700243 Function<? super K, ? extends V> mappingFunction) {
Madan Jampani7804c992015-07-20 13:20:19 -0700244 checkNotNull(key, ERROR_NULL_KEY);
245 checkNotNull(mappingFunction, "Mapping function cannot be null");
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700246 final MeteringAgent.Context timer = monitor.startTimer(COMPUTE_IF_ABSENT);
Flavio Castro5e1f1292015-07-23 17:14:09 -0700247 return updateAndGet(key, Match.ifNull(), Match.any(), mappingFunction.apply(key))
Flavio Castro6e044612015-08-13 14:13:58 -0700248 .whenComplete((r, e) -> timer.stop(e))
Flavio Castro5e1f1292015-07-23 17:14:09 -0700249 .thenApply(v -> v.newValue());
Madan Jampani346d4f52015-05-04 11:09:39 -0700250 }
251
252 @Override
253 public CompletableFuture<Versioned<V>> computeIfPresent(K key,
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700254 BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
Madan Jampani346d4f52015-05-04 11:09:39 -0700255 return computeIf(key, Objects::nonNull, remappingFunction);
256 }
257
258 @Override
259 public CompletableFuture<Versioned<V>> compute(K key,
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700260 BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
Madan Jampani346d4f52015-05-04 11:09:39 -0700261 return computeIf(key, v -> true, remappingFunction);
262 }
263
264 @Override
265 public CompletableFuture<Versioned<V>> computeIf(K key,
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700266 Predicate<? super V> condition,
267 BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
Madan Jampani346d4f52015-05-04 11:09:39 -0700268 checkNotNull(key, ERROR_NULL_KEY);
269 checkNotNull(condition, "predicate function cannot be null");
270 checkNotNull(remappingFunction, "Remapping function cannot be null");
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700271 final MeteringAgent.Context timer = monitor.startTimer(COMPUTE_IF);
Madan Jampani346d4f52015-05-04 11:09:39 -0700272 return get(key).thenCompose(r1 -> {
273 V existingValue = r1 == null ? null : r1.value();
274 // if the condition evaluates to false, return existing value.
275 if (!condition.test(existingValue)) {
276 return CompletableFuture.completedFuture(r1);
277 }
278
279 AtomicReference<V> computedValue = new AtomicReference<>();
280 // if remappingFunction throws an exception, return the exception.
281 try {
282 computedValue.set(remappingFunction.apply(key, existingValue));
283 } catch (Exception e) {
284 return Tools.exceptionalFuture(e);
285 }
Madan Jampani7804c992015-07-20 13:20:19 -0700286 if (computedValue.get() == null && r1 == null) {
287 return CompletableFuture.completedFuture(null);
Madan Jampani346d4f52015-05-04 11:09:39 -0700288 }
Madan Jampani7804c992015-07-20 13:20:19 -0700289 Match<V> valueMatcher = r1 == null ? Match.ifNull() : Match.any();
290 Match<Long> versionMatcher = r1 == null ? Match.any() : Match.ifValue(r1.version());
291 return updateAndGet(key, valueMatcher, versionMatcher, computedValue.get())
Flavio Castro6e044612015-08-13 14:13:58 -0700292 .whenComplete((r, e) -> timer.stop(e))
Madan Jampani7804c992015-07-20 13:20:19 -0700293 .thenApply(v -> {
294 if (v.updated()) {
295 return v.newValue();
296 } else {
Madan Jampanic7f49f92015-12-10 11:35:06 -0800297 throw new ConcurrentModification("Concurrent update to " + name + " detected");
Madan Jampani7804c992015-07-20 13:20:19 -0700298 }
299 });
300 });
Madan Jampani346d4f52015-05-04 11:09:39 -0700301 }
302
303 @Override
Madan Jampani7c521002015-03-23 12:23:01 -0700304 public CompletableFuture<Versioned<V>> put(K key, V value) {
305 checkNotNull(key, ERROR_NULL_KEY);
306 checkNotNull(value, ERROR_NULL_VALUE);
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700307 final MeteringAgent.Context timer = monitor.startTimer(PUT);
Flavio Castro5e1f1292015-07-23 17:14:09 -0700308 return updateAndGet(key, Match.any(), Match.any(), value).thenApply(v -> v.oldValue())
Flavio Castro6e044612015-08-13 14:13:58 -0700309 .whenComplete((r, e) -> timer.stop(e));
Madan Jampani346d4f52015-05-04 11:09:39 -0700310 }
311
312 @Override
313 public CompletableFuture<Versioned<V>> putAndGet(K key, V value) {
314 checkNotNull(key, ERROR_NULL_KEY);
315 checkNotNull(value, ERROR_NULL_VALUE);
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700316 final MeteringAgent.Context timer = monitor.startTimer(PUT_AND_GET);
Flavio Castro5e1f1292015-07-23 17:14:09 -0700317 return updateAndGet(key, Match.any(), Match.any(), value).thenApply(v -> v.newValue())
Flavio Castro6e044612015-08-13 14:13:58 -0700318 .whenComplete((r, e) -> timer.stop(e));
Madan Jampani7c521002015-03-23 12:23:01 -0700319 }
320
321 @Override
322 public CompletableFuture<Versioned<V>> remove(K key) {
323 checkNotNull(key, ERROR_NULL_KEY);
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700324 final MeteringAgent.Context timer = monitor.startTimer(REMOVE);
Flavio Castro5e1f1292015-07-23 17:14:09 -0700325 return updateAndGet(key, Match.any(), Match.any(), null).thenApply(v -> v.oldValue())
Flavio Castro6e044612015-08-13 14:13:58 -0700326 .whenComplete((r, e) -> timer.stop(e));
Madan Jampani7c521002015-03-23 12:23:01 -0700327 }
328
329 @Override
330 public CompletableFuture<Void> clear() {
Madan Jampani02b7fb82015-05-01 13:01:20 -0700331 checkIfUnmodifiable();
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700332 final MeteringAgent.Context timer = monitor.startTimer(CLEAR);
Flavio Castro5e1f1292015-07-23 17:14:09 -0700333 return database.mapClear(name).thenApply(this::unwrapResult)
Flavio Castro6e044612015-08-13 14:13:58 -0700334 .whenComplete((r, e) -> timer.stop(e));
Madan Jampani7c521002015-03-23 12:23:01 -0700335 }
336
337 @Override
338 public CompletableFuture<Set<K>> keySet() {
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700339 final MeteringAgent.Context timer = monitor.startTimer(KEY_SET);
Madan Jampani7804c992015-07-20 13:20:19 -0700340 return database.mapKeySet(name)
HIGUCHI Yuta14e865d2015-11-25 20:42:32 -0800341 .thenApply(s -> newMappingKeySet(s))
Flavio Castro6e044612015-08-13 14:13:58 -0700342 .whenComplete((r, e) -> timer.stop(e));
Madan Jampani7c521002015-03-23 12:23:01 -0700343 }
344
345 @Override
346 public CompletableFuture<Collection<Versioned<V>>> values() {
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700347 final MeteringAgent.Context timer = monitor.startTimer(VALUES);
Flavio Castro5e1f1292015-07-23 17:14:09 -0700348 return database.mapValues(name)
Flavio Castro6e044612015-08-13 14:13:58 -0700349 .whenComplete((r, e) -> timer.stop(e))
Flavio Castro5e1f1292015-07-23 17:14:09 -0700350 .thenApply(c -> c
351 .stream()
352 .map(v -> v.<V>map(serializer::decode))
353 .collect(Collectors.toList()));
Madan Jampani7c521002015-03-23 12:23:01 -0700354 }
355
356 @Override
357 public CompletableFuture<Set<Entry<K, Versioned<V>>>> entrySet() {
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700358 final MeteringAgent.Context timer = monitor.startTimer(ENTRY_SET);
Flavio Castro5e1f1292015-07-23 17:14:09 -0700359 return database.mapEntrySet(name)
Flavio Castro6e044612015-08-13 14:13:58 -0700360 .whenComplete((r, e) -> timer.stop(e))
HIGUCHI Yuta14e865d2015-11-25 20:42:32 -0800361 .thenApply(s -> newMappingEntrySet(s));
Madan Jampani7c521002015-03-23 12:23:01 -0700362 }
363
364 @Override
365 public CompletableFuture<Versioned<V>> putIfAbsent(K key, V value) {
366 checkNotNull(key, ERROR_NULL_KEY);
367 checkNotNull(value, ERROR_NULL_VALUE);
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700368 final MeteringAgent.Context timer = monitor.startTimer(PUT_IF_ABSENT);
Flavio Castro5e1f1292015-07-23 17:14:09 -0700369 return updateAndGet(key, Match.ifNull(), Match.any(), value)
Flavio Castro6e044612015-08-13 14:13:58 -0700370 .whenComplete((r, e) -> timer.stop(e))
Flavio Castro5e1f1292015-07-23 17:14:09 -0700371 .thenApply(v -> v.oldValue());
Madan Jampani7c521002015-03-23 12:23:01 -0700372 }
373
374 @Override
375 public CompletableFuture<Boolean> remove(K key, V value) {
376 checkNotNull(key, ERROR_NULL_KEY);
377 checkNotNull(value, ERROR_NULL_VALUE);
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700378 final MeteringAgent.Context timer = monitor.startTimer(REMOVE);
Flavio Castro5e1f1292015-07-23 17:14:09 -0700379 return updateAndGet(key, Match.ifValue(value), Match.any(), null)
Flavio Castro6e044612015-08-13 14:13:58 -0700380 .whenComplete((r, e) -> timer.stop(e))
Flavio Castro5e1f1292015-07-23 17:14:09 -0700381 .thenApply(v -> v.updated());
Madan Jampani7c521002015-03-23 12:23:01 -0700382 }
383
384 @Override
385 public CompletableFuture<Boolean> remove(K key, long version) {
386 checkNotNull(key, ERROR_NULL_KEY);
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700387 final MeteringAgent.Context timer = monitor.startTimer(REMOVE);
Flavio Castro5e1f1292015-07-23 17:14:09 -0700388 return updateAndGet(key, Match.any(), Match.ifValue(version), null)
Flavio Castro6e044612015-08-13 14:13:58 -0700389 .whenComplete((r, e) -> timer.stop(e))
Flavio Castro5e1f1292015-07-23 17:14:09 -0700390 .thenApply(v -> v.updated());
Madan Jampani7c521002015-03-23 12:23:01 -0700391 }
392
393 @Override
394 public CompletableFuture<Boolean> replace(K key, V oldValue, V newValue) {
395 checkNotNull(key, ERROR_NULL_KEY);
Madan Jampani7804c992015-07-20 13:20:19 -0700396 checkNotNull(oldValue, ERROR_NULL_VALUE);
Madan Jampani7c521002015-03-23 12:23:01 -0700397 checkNotNull(newValue, ERROR_NULL_VALUE);
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700398 final MeteringAgent.Context timer = monitor.startTimer(REPLACE);
Flavio Castro5e1f1292015-07-23 17:14:09 -0700399 return updateAndGet(key, Match.ifValue(oldValue), Match.any(), newValue)
Flavio Castro6e044612015-08-13 14:13:58 -0700400 .whenComplete((r, e) -> timer.stop(e))
Flavio Castro5e1f1292015-07-23 17:14:09 -0700401 .thenApply(v -> v.updated());
Madan Jampani7c521002015-03-23 12:23:01 -0700402 }
403
404 @Override
405 public CompletableFuture<Boolean> replace(K key, long oldVersion, V newValue) {
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700406 final MeteringAgent.Context timer = monitor.startTimer(REPLACE);
Flavio Castro5e1f1292015-07-23 17:14:09 -0700407 return updateAndGet(key, Match.any(), Match.ifValue(oldVersion), newValue)
Flavio Castro6e044612015-08-13 14:13:58 -0700408 .whenComplete((r, e) -> timer.stop(e))
Flavio Castro5e1f1292015-07-23 17:14:09 -0700409 .thenApply(v -> v.updated());
Madan Jampani346d4f52015-05-04 11:09:39 -0700410 }
411
Madan Jampani14a38da2015-11-16 11:29:00 -0800412 /**
413 * Pre-update hook for performing required checks/actions before going forward with an update operation.
414 * @param key map key.
415 */
416 protected void beforeUpdate(K key) {
417 checkIfUnmodifiable();
418 }
419
HIGUCHI Yuta14e865d2015-11-25 20:42:32 -0800420 private Set<K> newMappingKeySet(Set<String> s) {
421 return new MappingSet<>(s, Collections::unmodifiableSet,
422 this::sK, this::dK);
423 }
424
425 private Set<Entry<K, Versioned<V>>> newMappingEntrySet(Set<Entry<String, Versioned<byte[]>>> s) {
426 return new MappingSet<>(s, Collections::unmodifiableSet,
427 this::reverseMapRawEntry, this::mapRawEntry);
428 }
429
Madan Jampani7804c992015-07-20 13:20:19 -0700430 private Map.Entry<K, Versioned<V>> mapRawEntry(Map.Entry<String, Versioned<byte[]>> e) {
431 return Maps.immutableEntry(dK(e.getKey()), e.getValue().<V>map(serializer::decode));
432 }
433
HIGUCHI Yuta14e865d2015-11-25 20:42:32 -0800434 private Map.Entry<String, Versioned<byte[]>> reverseMapRawEntry(Map.Entry<K, Versioned<V>> e) {
435 return Maps.immutableEntry(sK(e.getKey()), e.getValue().map(serializer::encode));
436 }
437
Madan Jampani7804c992015-07-20 13:20:19 -0700438 private CompletableFuture<UpdateResult<K, V>> updateAndGet(K key,
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700439 Match<V> oldValueMatch,
440 Match<Long> oldVersionMatch,
441 V value) {
Madan Jampani14a38da2015-11-16 11:29:00 -0800442 beforeUpdate(key);
Madan Jampani7804c992015-07-20 13:20:19 -0700443 return database.mapUpdate(name,
HIGUCHI Yuta14e865d2015-11-25 20:42:32 -0800444 sK(key),
Flavio Castro5e1f1292015-07-23 17:14:09 -0700445 oldValueMatch.map(serializer::encode),
446 oldVersionMatch,
447 value == null ? null : serializer.encode(value))
Madan Jampani7804c992015-07-20 13:20:19 -0700448 .thenApply(this::unwrapResult)
Madan Jampani85668632015-08-10 10:46:40 -0700449 .thenApply(r -> r.<K, V>map(this::dK, serializer::decode));
Madan Jampani7c521002015-03-23 12:23:01 -0700450 }
Madan Jampanibff6d8f2015-03-31 16:53:47 -0700451
452 private <T> T unwrapResult(Result<T> result) {
453 if (result.status() == Result.Status.LOCKED) {
454 throw new ConsistentMapException.ConcurrentModification();
455 } else if (result.success()) {
456 return result.value();
457 } else {
458 throw new IllegalStateException("Must not be here");
459 }
460 }
Madan Jampani02b7fb82015-05-01 13:01:20 -0700461
462 private void checkIfUnmodifiable() {
463 if (readOnly) {
464 throw new UnsupportedOperationException();
465 }
466 }
Madan Jampani50589ac2015-06-08 11:38:46 -0700467
468 @Override
469 public void addListener(MapEventListener<K, V> listener) {
470 listeners.add(listener);
471 }
472
473 @Override
474 public void removeListener(MapEventListener<K, V> listener) {
475 listeners.remove(listener);
476 }
477
478 protected void notifyListeners(MapEvent<K, V> event) {
Madan Jampani85668632015-08-10 10:46:40 -0700479 if (event == null) {
480 return;
481 }
482 listeners.forEach(listener -> {
483 try {
484 listener.event(event);
485 } catch (Exception e) {
486 log.warn("Failure notifying listener about {}", event, e);
Madan Jampani50589ac2015-06-08 11:38:46 -0700487 }
Madan Jampani85668632015-08-10 10:46:40 -0700488 });
Madan Jampani50589ac2015-06-08 11:38:46 -0700489 }
Flavio Castro5e1f1292015-07-23 17:14:09 -0700490
Madan Jampanibab51a42015-08-10 13:53:35 -0700491}