1 | // License: GPL. For details, see LICENSE file.
|
---|
2 | package org.openstreetmap.josm.data.cache;
|
---|
3 |
|
---|
4 | import java.io.File;
|
---|
5 | import java.io.IOException;
|
---|
6 | import java.nio.channels.FileChannel;
|
---|
7 | import java.nio.channels.FileLock;
|
---|
8 | import java.nio.file.StandardOpenOption;
|
---|
9 | import java.util.Arrays;
|
---|
10 | import java.util.Properties;
|
---|
11 | import java.util.logging.Handler;
|
---|
12 | import java.util.logging.Level;
|
---|
13 | import java.util.logging.LogRecord;
|
---|
14 | import java.util.logging.Logger;
|
---|
15 | import java.util.logging.SimpleFormatter;
|
---|
16 |
|
---|
17 | import org.apache.commons.jcs.access.CacheAccess;
|
---|
18 | import org.apache.commons.jcs.auxiliary.AuxiliaryCache;
|
---|
19 | import org.apache.commons.jcs.auxiliary.AuxiliaryCacheFactory;
|
---|
20 | import org.apache.commons.jcs.auxiliary.disk.behavior.IDiskCacheAttributes;
|
---|
21 | import org.apache.commons.jcs.auxiliary.disk.block.BlockDiskCacheAttributes;
|
---|
22 | import org.apache.commons.jcs.auxiliary.disk.block.BlockDiskCacheFactory;
|
---|
23 | import org.apache.commons.jcs.auxiliary.disk.indexed.IndexedDiskCacheAttributes;
|
---|
24 | import org.apache.commons.jcs.auxiliary.disk.indexed.IndexedDiskCacheFactory;
|
---|
25 | import org.apache.commons.jcs.engine.CompositeCacheAttributes;
|
---|
26 | import org.apache.commons.jcs.engine.behavior.ICompositeCacheAttributes.DiskUsagePattern;
|
---|
27 | import org.apache.commons.jcs.engine.control.CompositeCache;
|
---|
28 | import org.apache.commons.jcs.engine.control.CompositeCacheManager;
|
---|
29 | import org.apache.commons.jcs.utils.serialization.StandardSerializer;
|
---|
30 | import org.openstreetmap.josm.data.preferences.BooleanProperty;
|
---|
31 | import org.openstreetmap.josm.data.preferences.IntegerProperty;
|
---|
32 | import org.openstreetmap.josm.spi.preferences.Config;
|
---|
33 | import org.openstreetmap.josm.tools.Logging;
|
---|
34 | import org.openstreetmap.josm.tools.Utils;
|
---|
35 |
|
---|
36 | /**
|
---|
37 | * Wrapper class for JCS Cache. Sets some sane environment and returns instances of cache objects.
|
---|
38 | * Static configuration for now assumes some small LRU cache in memory and larger LRU cache on disk
|
---|
39 | *
|
---|
40 | * @author Wiktor Niesiobędzki
|
---|
41 | * @since 8168
|
---|
42 | */
|
---|
43 | public final class JCSCacheManager {
|
---|
44 | private static volatile CompositeCacheManager cacheManager;
|
---|
45 | private static final long maxObjectTTL = -1;
|
---|
46 | private static final String PREFERENCE_PREFIX = "jcs.cache";
|
---|
47 | public static final BooleanProperty USE_BLOCK_CACHE = new BooleanProperty(PREFERENCE_PREFIX + ".use_block_cache", true);
|
---|
48 |
|
---|
49 | private static final AuxiliaryCacheFactory DISK_CACHE_FACTORY =
|
---|
50 | USE_BLOCK_CACHE.get() ? new BlockDiskCacheFactory() : new IndexedDiskCacheFactory();
|
---|
51 | private static FileLock cacheDirLock;
|
---|
52 |
|
---|
53 | /**
|
---|
54 | * default objects to be held in memory by JCS caches (per region)
|
---|
55 | */
|
---|
56 | public static final IntegerProperty DEFAULT_MAX_OBJECTS_IN_MEMORY = new IntegerProperty(PREFERENCE_PREFIX + ".max_objects_in_memory", 1000);
|
---|
57 |
|
---|
58 | private static final Logger jcsLog;
|
---|
59 |
|
---|
60 | static {
|
---|
61 | // raising logging level gives ~500x performance gain
|
---|
62 | // http://westsworld.dk/blog/2008/01/jcs-and-performance/
|
---|
63 | jcsLog = Logger.getLogger("org.apache.commons.jcs");
|
---|
64 | jcsLog.setLevel(Level.INFO);
|
---|
65 | jcsLog.setUseParentHandlers(false);
|
---|
66 | // we need a separate handler from Main's, as we downgrade LEVEL.INFO to DEBUG level
|
---|
67 | Arrays.stream(jcsLog.getHandlers()).forEach(jcsLog::removeHandler);
|
---|
68 | jcsLog.addHandler(new Handler() {
|
---|
69 | final SimpleFormatter formatter = new SimpleFormatter();
|
---|
70 |
|
---|
71 | @Override
|
---|
72 | public void publish(LogRecord record) {
|
---|
73 | String msg = formatter.formatMessage(record);
|
---|
74 | if (record.getLevel().intValue() >= Level.SEVERE.intValue()) {
|
---|
75 | Logging.error(msg);
|
---|
76 | } else if (record.getLevel().intValue() >= Level.WARNING.intValue()) {
|
---|
77 | Logging.warn(msg);
|
---|
78 | // downgrade INFO level to debug, as JCS is too verbose at INFO level
|
---|
79 | } else if (record.getLevel().intValue() >= Level.INFO.intValue()) {
|
---|
80 | Logging.debug(msg);
|
---|
81 | } else {
|
---|
82 | Logging.trace(msg);
|
---|
83 | }
|
---|
84 | }
|
---|
85 |
|
---|
86 | @Override
|
---|
87 | public void flush() {
|
---|
88 | // nothing to be done on flush
|
---|
89 | }
|
---|
90 |
|
---|
91 | @Override
|
---|
92 | public void close() {
|
---|
93 | // nothing to be done on close
|
---|
94 | }
|
---|
95 | });
|
---|
96 | }
|
---|
97 |
|
---|
98 | private JCSCacheManager() {
|
---|
99 | // Hide implicit public constructor for utility classes
|
---|
100 | }
|
---|
101 |
|
---|
102 | @SuppressWarnings("resource")
|
---|
103 | private static void initialize() throws IOException {
|
---|
104 | File cacheDir = new File(Config.getDirs().getCacheDirectory(true), "jcs");
|
---|
105 |
|
---|
106 | if (!cacheDir.exists() && !cacheDir.mkdirs())
|
---|
107 | throw new IOException("Cannot access cache directory");
|
---|
108 |
|
---|
109 | File cacheDirLockPath = new File(cacheDir, ".lock");
|
---|
110 | if (!cacheDirLockPath.exists() && !cacheDirLockPath.createNewFile()) {
|
---|
111 | Logging.warn("Cannot create cache dir lock file");
|
---|
112 | }
|
---|
113 | cacheDirLock = FileChannel.open(cacheDirLockPath.toPath(), StandardOpenOption.WRITE).tryLock();
|
---|
114 |
|
---|
115 | if (cacheDirLock == null)
|
---|
116 | Logging.warn("Cannot lock cache directory. Will not use disk cache");
|
---|
117 |
|
---|
118 | // this could be moved to external file
|
---|
119 | Properties props = new Properties();
|
---|
120 | // these are default common to all cache regions
|
---|
121 | // use of auxiliary cache and sizing of the caches is done with giving proper geCache(...) params
|
---|
122 | // CHECKSTYLE.OFF: SingleSpaceSeparator
|
---|
123 | props.setProperty("jcs.default.cacheattributes", CompositeCacheAttributes.class.getCanonicalName());
|
---|
124 | props.setProperty("jcs.default.cacheattributes.MaxObjects", DEFAULT_MAX_OBJECTS_IN_MEMORY.get().toString());
|
---|
125 | props.setProperty("jcs.default.cacheattributes.UseMemoryShrinker", "true");
|
---|
126 | props.setProperty("jcs.default.cacheattributes.DiskUsagePatternName", "UPDATE"); // store elements on disk on put
|
---|
127 | props.setProperty("jcs.default.elementattributes", CacheEntryAttributes.class.getCanonicalName());
|
---|
128 | props.setProperty("jcs.default.elementattributes.IsEternal", "false");
|
---|
129 | props.setProperty("jcs.default.elementattributes.MaxLife", Long.toString(maxObjectTTL));
|
---|
130 | props.setProperty("jcs.default.elementattributes.IdleTime", Long.toString(maxObjectTTL));
|
---|
131 | props.setProperty("jcs.default.elementattributes.IsSpool", "true");
|
---|
132 | // CHECKSTYLE.ON: SingleSpaceSeparator
|
---|
133 | CompositeCacheManager cm = CompositeCacheManager.getUnconfiguredInstance();
|
---|
134 | cm.configure(props);
|
---|
135 | cacheManager = cm;
|
---|
136 | }
|
---|
137 |
|
---|
138 | /**
|
---|
139 | * Returns configured cache object for named cache region
|
---|
140 | * @param <K> key type
|
---|
141 | * @param <V> value type
|
---|
142 | * @param cacheName region name
|
---|
143 | * @return cache access object
|
---|
144 | * @throws IOException if directory is not found
|
---|
145 | */
|
---|
146 | public static <K, V> CacheAccess<K, V> getCache(String cacheName) throws IOException {
|
---|
147 | return getCache(cacheName, DEFAULT_MAX_OBJECTS_IN_MEMORY.get().intValue(), 0, null);
|
---|
148 | }
|
---|
149 |
|
---|
150 | /**
|
---|
151 | * Returns configured cache object with defined limits of memory cache and disk cache
|
---|
152 | * @param <K> key type
|
---|
153 | * @param <V> value type
|
---|
154 | * @param cacheName region name
|
---|
155 | * @param maxMemoryObjects number of objects to keep in memory
|
---|
156 | * @param maxDiskObjects maximum size of the objects stored on disk in kB
|
---|
157 | * @param cachePath path to disk cache. if null, no disk cache will be created
|
---|
158 | * @return cache access object
|
---|
159 | * @throws IOException if directory is not found
|
---|
160 | */
|
---|
161 | public static <K, V> CacheAccess<K, V> getCache(String cacheName, int maxMemoryObjects, int maxDiskObjects, String cachePath)
|
---|
162 | throws IOException {
|
---|
163 | if (cacheManager != null)
|
---|
164 | return getCacheInner(cacheName, maxMemoryObjects, maxDiskObjects, cachePath);
|
---|
165 |
|
---|
166 | synchronized (JCSCacheManager.class) {
|
---|
167 | if (cacheManager == null)
|
---|
168 | initialize();
|
---|
169 | return getCacheInner(cacheName, maxMemoryObjects, maxDiskObjects, cachePath);
|
---|
170 | }
|
---|
171 | }
|
---|
172 |
|
---|
173 | @SuppressWarnings("unchecked")
|
---|
174 | private static <K, V> CacheAccess<K, V> getCacheInner(String cacheName, int maxMemoryObjects, int maxDiskObjects, String cachePath)
|
---|
175 | throws IOException {
|
---|
176 | CompositeCache<K, V> cc = cacheManager.getCache(cacheName, getCacheAttributes(maxMemoryObjects));
|
---|
177 |
|
---|
178 | if (cachePath != null && cacheDirLock != null) {
|
---|
179 | IDiskCacheAttributes diskAttributes = getDiskCacheAttributes(maxDiskObjects, cachePath, cacheName);
|
---|
180 | try {
|
---|
181 | if (cc.getAuxCaches().length == 0) {
|
---|
182 | cc.setAuxCaches(new AuxiliaryCache[]{DISK_CACHE_FACTORY.createCache(
|
---|
183 | diskAttributes, cacheManager, null, new StandardSerializer())});
|
---|
184 | }
|
---|
185 | } catch (IOException e) {
|
---|
186 | throw e;
|
---|
187 | } catch (Exception e) { // NOPMD
|
---|
188 | throw new IOException(e);
|
---|
189 | }
|
---|
190 | }
|
---|
191 | return new CacheAccess<>(cc);
|
---|
192 | }
|
---|
193 |
|
---|
194 | /**
|
---|
195 | * Close all files to ensure, that all indexes and data are properly written
|
---|
196 | */
|
---|
197 | public static void shutdown() {
|
---|
198 | // use volatile semantics to get consistent object
|
---|
199 | CompositeCacheManager localCacheManager = cacheManager;
|
---|
200 | if (localCacheManager != null) {
|
---|
201 | localCacheManager.shutDown();
|
---|
202 | }
|
---|
203 | }
|
---|
204 |
|
---|
205 | private static IDiskCacheAttributes getDiskCacheAttributes(int maxDiskObjects, String cachePath, String cacheName) {
|
---|
206 | IDiskCacheAttributes ret;
|
---|
207 | removeStaleFiles(cachePath + File.separator + cacheName, USE_BLOCK_CACHE.get() ? "_INDEX_v2" : "_BLOCK_v2");
|
---|
208 | String newCacheName = cacheName + (USE_BLOCK_CACHE.get() ? "_BLOCK_v2" : "_INDEX_v2");
|
---|
209 |
|
---|
210 | if (USE_BLOCK_CACHE.get()) {
|
---|
211 | BlockDiskCacheAttributes blockAttr = new BlockDiskCacheAttributes();
|
---|
212 | /*
|
---|
213 | * BlockDiskCache never optimizes the file, so when file size is reduced, it will never be truncated to desired size.
|
---|
214 | *
|
---|
215 | * If for some mysterious reason, file size is greater than the value set in preferences, just use the whole file. If the user
|
---|
216 | * wants to reduce the file size, (s)he may just go to preferences and there it should be handled (by removing old file)
|
---|
217 | */
|
---|
218 | File diskCacheFile = new File(cachePath + File.separator + newCacheName + ".data");
|
---|
219 | if (diskCacheFile.exists()) {
|
---|
220 | blockAttr.setMaxKeySize((int) Math.max(maxDiskObjects, diskCacheFile.length()/1024));
|
---|
221 | } else {
|
---|
222 | blockAttr.setMaxKeySize(maxDiskObjects);
|
---|
223 | }
|
---|
224 | blockAttr.setBlockSizeBytes(4096); // use 4k blocks
|
---|
225 | ret = blockAttr;
|
---|
226 | } else {
|
---|
227 | IndexedDiskCacheAttributes indexAttr = new IndexedDiskCacheAttributes();
|
---|
228 | indexAttr.setMaxKeySize(maxDiskObjects);
|
---|
229 | ret = indexAttr;
|
---|
230 | }
|
---|
231 | ret.setDiskLimitType(IDiskCacheAttributes.DiskLimitType.SIZE);
|
---|
232 | File path = new File(cachePath);
|
---|
233 | if (!path.exists() && !path.mkdirs()) {
|
---|
234 | Logging.warn("Failed to create cache path: {0}", cachePath);
|
---|
235 | } else {
|
---|
236 | ret.setDiskPath(cachePath);
|
---|
237 | }
|
---|
238 | ret.setCacheName(newCacheName);
|
---|
239 |
|
---|
240 | return ret;
|
---|
241 | }
|
---|
242 |
|
---|
243 | private static void removeStaleFiles(String basePathPart, String suffix) {
|
---|
244 | deleteCacheFiles(basePathPart + suffix);
|
---|
245 | }
|
---|
246 |
|
---|
247 | private static void deleteCacheFiles(String basePathPart) {
|
---|
248 | Utils.deleteFileIfExists(new File(basePathPart + ".key"));
|
---|
249 | Utils.deleteFileIfExists(new File(basePathPart + ".data"));
|
---|
250 | }
|
---|
251 |
|
---|
252 | private static CompositeCacheAttributes getCacheAttributes(int maxMemoryElements) {
|
---|
253 | CompositeCacheAttributes ret = new CompositeCacheAttributes();
|
---|
254 | ret.setMaxObjects(maxMemoryElements);
|
---|
255 | ret.setDiskUsagePattern(DiskUsagePattern.UPDATE);
|
---|
256 | return ret;
|
---|
257 | }
|
---|
258 | }
|
---|