blob: 27cfd346b4a5b0b961df7eceec322a869c248bbc [file] [log] [blame]
Jordan Halterman3b137372018-04-30 14:42:41 -07001/*
2 * Copyright 2018-present Open Networking Foundation
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 */
16package org.onosproject.store.primitives.impl;
17
18import java.util.Collection;
19import java.util.Objects;
20import java.util.concurrent.CompletableFuture;
21import java.util.function.Consumer;
22import java.util.stream.Collectors;
23
24import com.google.common.cache.CacheBuilder;
25import com.google.common.cache.CacheLoader;
26import com.google.common.cache.LoadingCache;
27import com.google.common.collect.ImmutableSet;
28import org.onosproject.store.service.AsyncConsistentMultimap;
29import org.onosproject.store.service.MultimapEventListener;
30import org.onosproject.store.service.Versioned;
31import org.slf4j.Logger;
32
33import static org.onosproject.store.service.DistributedPrimitive.Status.INACTIVE;
34import static org.onosproject.store.service.DistributedPrimitive.Status.SUSPENDED;
35import static org.slf4j.LoggerFactory.getLogger;
36
37/**
38 * Caching {@link AsyncConsistentMultimap} implementation.
39 */
40public class CachingAsyncConsistentMultimap<K, V> extends DelegatingAsyncConsistentMultimap<K, V> {
41 private static final int DEFAULT_CACHE_SIZE = 10000;
42 private final Logger log = getLogger(getClass());
43
44 private final LoadingCache<K, CompletableFuture<Versioned<Collection<? extends V>>>> cache;
45 private final MultimapEventListener<K, V> cacheUpdater;
46 private final Consumer<Status> statusListener;
47
48 /**
49 * Default constructor.
50 *
51 * @param backingMap a distributed, strongly consistent map for backing
52 */
53 public CachingAsyncConsistentMultimap(AsyncConsistentMultimap<K, V> backingMap) {
54 this(backingMap, DEFAULT_CACHE_SIZE);
55 }
56
57 /**
58 * Constructor to configure cache size.
59 *
60 * @param backingMap a distributed, strongly consistent map for backing
61 * @param cacheSize the maximum size of the cache
62 */
63 public CachingAsyncConsistentMultimap(AsyncConsistentMultimap<K, V> backingMap, int cacheSize) {
64 super(backingMap);
65 cache = CacheBuilder.newBuilder()
66 .maximumSize(cacheSize)
67 .build(CacheLoader.from(CachingAsyncConsistentMultimap.super::get));
68 cacheUpdater = event -> {
69 V oldValue = event.oldValue();
70 V newValue = event.newValue();
71 CompletableFuture<Versioned<Collection<? extends V>>> future = cache.getUnchecked(event.key());
72 switch (event.type()) {
73 case INSERT:
74 if (future.isDone()) {
75 Versioned<Collection<? extends V>> oldVersioned = future.join();
76 Versioned<Collection<? extends V>> newVersioned = new Versioned<>(
77 ImmutableSet.<V>builder().addAll(oldVersioned.value()).add(newValue).build(),
78 oldVersioned.version(),
79 oldVersioned.creationTime());
80 cache.put(event.key(), CompletableFuture.completedFuture(newVersioned));
81 } else {
82 cache.put(event.key(), future.thenApply(versioned -> new Versioned<>(
83 ImmutableSet.<V>builder().addAll(versioned.value()).add(newValue).build(),
84 versioned.version(),
85 versioned.creationTime())));
86 }
87 break;
88 case REMOVE:
89 if (future.isDone()) {
90 Versioned<Collection<? extends V>> oldVersioned = future.join();
91 cache.put(event.key(), CompletableFuture.completedFuture(new Versioned<>(oldVersioned.value()
92 .stream()
93 .filter(value -> !Objects.equals(value, oldValue))
94 .collect(Collectors.toSet()), oldVersioned.version(), oldVersioned.creationTime())));
95 } else {
96 cache.put(event.key(), future.thenApply(versioned -> new Versioned<>(versioned.value()
97 .stream()
98 .filter(value -> !Objects.equals(value, oldValue))
99 .collect(Collectors.toSet()), versioned.version(), versioned.creationTime())));
100 }
101 break;
102 default:
103 break;
104 }
105 };
106 statusListener = status -> {
107 log.debug("{} status changed to {}", this.name(), status);
108 // If the status of the underlying map is SUSPENDED or INACTIVE
109 // we can no longer guarantee that the cache will be in sync.
110 if (status == SUSPENDED || status == INACTIVE) {
111 cache.invalidateAll();
112 }
113 };
114 super.addListener(cacheUpdater);
115 super.addStatusChangeListener(statusListener);
116 }
117
118 @Override
119 public CompletableFuture<Boolean> containsKey(K key) {
120 return get(key).thenApply(value -> value != null && !value.value().isEmpty());
121 }
122
123 @Override
124 public CompletableFuture<Boolean> put(K key, V value) {
125 return super.put(key, value)
126 .whenComplete((r, e) -> cache.invalidate(key));
127 }
128
129 @Override
130 public CompletableFuture<Boolean> remove(K key, V value) {
131 return super.remove(key, value)
132 .whenComplete((r, e) -> cache.invalidate(key));
133 }
134
135 @Override
136 public CompletableFuture<Boolean> removeAll(K key, Collection<? extends V> values) {
137 return super.removeAll(key, values)
138 .whenComplete((r, e) -> cache.invalidate(key));
139 }
140
141 @Override
142 public CompletableFuture<Versioned<Collection<? extends V>>> removeAll(K key) {
143 return super.removeAll(key)
144 .whenComplete((r, e) -> cache.invalidate(key));
145 }
146
147 @Override
148 public CompletableFuture<Boolean> putAll(K key, Collection<? extends V> values) {
149 return super.putAll(key, values)
150 .whenComplete((r, e) -> cache.invalidate(key));
151 }
152
153 @Override
154 public CompletableFuture<Versioned<Collection<? extends V>>> replaceValues(K key, Collection<V> values) {
155 return super.replaceValues(key, values)
156 .whenComplete((r, e) -> cache.invalidate(key));
157 }
158
159 @Override
160 public CompletableFuture<Void> clear() {
161 return super.clear()
162 .whenComplete((r, e) -> cache.invalidateAll());
163 }
164
165 @Override
166 public CompletableFuture<Versioned<Collection<? extends V>>> get(K key) {
167 return cache.getUnchecked(key)
168 .whenComplete((r, e) -> {
169 if (e != null) {
170 cache.invalidate(key);
171 }
172 });
173 }
174
175 @Override
176 public CompletableFuture<Void> destroy() {
177 super.removeStatusChangeListener(statusListener);
178 return super.destroy().thenCompose(v -> removeListener(cacheUpdater));
179 }
180}