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.jcs3.JCS;
|
---|
18 | import org.apache.commons.jcs3.access.CacheAccess;
|
---|
19 | import org.apache.commons.jcs3.auxiliary.AuxiliaryCache;
|
---|
20 | import org.apache.commons.jcs3.auxiliary.AuxiliaryCacheFactory;
|
---|
21 | import org.apache.commons.jcs3.auxiliary.disk.behavior.IDiskCacheAttributes;
|
---|
22 | import org.apache.commons.jcs3.auxiliary.disk.block.BlockDiskCacheAttributes;
|
---|
23 | import org.apache.commons.jcs3.auxiliary.disk.block.BlockDiskCacheFactory;
|
---|
24 | import org.apache.commons.jcs3.auxiliary.disk.indexed.IndexedDiskCacheAttributes;
|
---|
25 | import org.apache.commons.jcs3.auxiliary.disk.indexed.IndexedDiskCacheFactory;
|
---|
26 | import org.apache.commons.jcs3.engine.CompositeCacheAttributes;
|
---|
27 | import org.apache.commons.jcs3.engine.behavior.ICompositeCacheAttributes.DiskUsagePattern;
|
---|
28 | import org.apache.commons.jcs3.engine.control.CompositeCache;
|
---|
29 | import org.apache.commons.jcs3.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 final long maxObjectTTL = -1;
|
---|
45 | private static final String PREFERENCE_PREFIX = "jcs.cache";
|
---|
46 | public static final BooleanProperty USE_BLOCK_CACHE = new BooleanProperty(PREFERENCE_PREFIX + ".use_block_cache", true);
|
---|
47 |
|
---|
48 | private static final AuxiliaryCacheFactory DISK_CACHE_FACTORY =
|
---|
49 | USE_BLOCK_CACHE.get() ? new BlockDiskCacheFactory() : new IndexedDiskCacheFactory();
|
---|
50 | private static FileLock cacheDirLock;
|
---|
51 |
|
---|
52 | /**
|
---|
53 | * default objects to be held in memory by JCS caches (per region)
|
---|
54 | */
|
---|
55 | public static final IntegerProperty DEFAULT_MAX_OBJECTS_IN_MEMORY = new IntegerProperty(PREFERENCE_PREFIX + ".max_objects_in_memory", 1000);
|
---|
56 |
|
---|
57 | private static final Logger jcsLog;
|
---|
58 |
|
---|
59 | static {
|
---|
60 | // raising logging level gives ~500x performance gain
|
---|
61 | // http://westsworld.dk/blog/2008/01/jcs-and-performance/
|
---|
62 | jcsLog = Logger.getLogger("org.apache.commons.jcs3");
|
---|
63 | try {
|
---|
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 | } catch (Exception e) {
|
---|
97 | Logging.log(Logging.LEVEL_ERROR, "Unable to configure JCS logs", e);
|
---|
98 | }
|
---|
99 | }
|
---|
100 |
|
---|
101 | private JCSCacheManager() {
|
---|
102 | // Hide implicit public constructor for utility classes
|
---|
103 | }
|
---|
104 |
|
---|
105 | static {
|
---|
106 | File cacheDir = new File(Config.getDirs().getCacheDirectory(true), "jcs");
|
---|
107 |
|
---|
108 | try {
|
---|
109 | if (!cacheDir.exists() && !cacheDir.mkdirs()) {
|
---|
110 | Logging.warn("Cache directory " + cacheDir.toString() + " does not exists and could not create it");
|
---|
111 | } else {
|
---|
112 | File cacheDirLockPath = new File(cacheDir, ".lock");
|
---|
113 | try {
|
---|
114 | if (!cacheDirLockPath.exists() && !cacheDirLockPath.createNewFile()) {
|
---|
115 | Logging.warn("Cannot create cache dir lock file");
|
---|
116 | }
|
---|
117 | cacheDirLock = FileChannel.open(cacheDirLockPath.toPath(), StandardOpenOption.WRITE).tryLock();
|
---|
118 |
|
---|
119 | if (cacheDirLock == null)
|
---|
120 | Logging.warn("Cannot lock cache directory. Will not use disk cache");
|
---|
121 | } catch (IOException e) {
|
---|
122 | Logging.log(Logging.LEVEL_WARN, "Cannot create cache dir \"" + cacheDirLockPath + "\" lock file:", e);
|
---|
123 | Logging.warn("Will not use disk cache");
|
---|
124 | }
|
---|
125 | }
|
---|
126 | } catch (Exception e) {
|
---|
127 | Logging.log(Logging.LEVEL_WARN, "Unable to configure disk cache. Will not use it", e);
|
---|
128 | }
|
---|
129 |
|
---|
130 | // this could be moved to external file
|
---|
131 | Properties props = new Properties();
|
---|
132 | // these are default common to all cache regions
|
---|
133 | // use of auxiliary cache and sizing of the caches is done with giving proper getCache(...) params
|
---|
134 | // CHECKSTYLE.OFF: SingleSpaceSeparator
|
---|
135 | props.setProperty("jcs.default.cacheattributes", CompositeCacheAttributes.class.getCanonicalName());
|
---|
136 | props.setProperty("jcs.default.cacheattributes.MaxObjects", DEFAULT_MAX_OBJECTS_IN_MEMORY.get().toString());
|
---|
137 | props.setProperty("jcs.default.cacheattributes.UseMemoryShrinker", "true");
|
---|
138 | props.setProperty("jcs.default.cacheattributes.DiskUsagePatternName", "UPDATE"); // store elements on disk on put
|
---|
139 | props.setProperty("jcs.default.elementattributes", CacheEntryAttributes.class.getCanonicalName());
|
---|
140 | props.setProperty("jcs.default.elementattributes.IsEternal", "false");
|
---|
141 | props.setProperty("jcs.default.elementattributes.MaxLife", Long.toString(maxObjectTTL));
|
---|
142 | props.setProperty("jcs.default.elementattributes.IdleTime", Long.toString(maxObjectTTL));
|
---|
143 | props.setProperty("jcs.default.elementattributes.IsSpool", "true");
|
---|
144 | // CHECKSTYLE.ON: SingleSpaceSeparator
|
---|
145 | try {
|
---|
146 | JCS.setConfigProperties(props);
|
---|
147 | } catch (Exception e) {
|
---|
148 | Logging.log(Logging.LEVEL_WARN, "Unable to initialize JCS", e);
|
---|
149 | }
|
---|
150 | }
|
---|
151 |
|
---|
152 | /**
|
---|
153 | * Returns configured cache object for named cache region
|
---|
154 | * @param <K> key type
|
---|
155 | * @param <V> value type
|
---|
156 | * @param cacheName region name
|
---|
157 | * @return cache access object
|
---|
158 | */
|
---|
159 | public static <K, V> CacheAccess<K, V> getCache(String cacheName) {
|
---|
160 | return getCache(cacheName, DEFAULT_MAX_OBJECTS_IN_MEMORY.get().intValue(), 0, null);
|
---|
161 | }
|
---|
162 |
|
---|
163 | /**
|
---|
164 | * Returns configured cache object with defined limits of memory cache and disk cache
|
---|
165 | * @param <K> key type
|
---|
166 | * @param <V> value type
|
---|
167 | * @param cacheName region name
|
---|
168 | * @param maxMemoryObjects number of objects to keep in memory
|
---|
169 | * @param maxDiskObjects maximum size of the objects stored on disk in kB
|
---|
170 | * @param cachePath path to disk cache. if null, no disk cache will be created
|
---|
171 | * @return cache access object
|
---|
172 | */
|
---|
173 | @SuppressWarnings("unchecked")
|
---|
174 | public static <K, V> CacheAccess<K, V> getCache(String cacheName, int maxMemoryObjects, int maxDiskObjects, String cachePath) {
|
---|
175 | CacheAccess<K, V> cacheAccess = JCS.getInstance(cacheName, getCacheAttributes(maxMemoryObjects));
|
---|
176 | CompositeCache<K, V> cc = cacheAccess.getCacheControl();
|
---|
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, null, null, new StandardSerializer())});
|
---|
184 | }
|
---|
185 | } catch (Exception e) { // NOPMD
|
---|
186 | // in case any error in setting auxiliary cache, do not use disk cache at all - only memory
|
---|
187 | cc.setAuxCaches(new AuxiliaryCache[0]);
|
---|
188 | Logging.debug(e);
|
---|
189 | }
|
---|
190 | }
|
---|
191 | return cacheAccess;
|
---|
192 | }
|
---|
193 |
|
---|
194 | /**
|
---|
195 | * Close all files to ensure, that all indexes and data are properly written
|
---|
196 | */
|
---|
197 | public static void shutdown() {
|
---|
198 | JCS.shutdown();
|
---|
199 | }
|
---|
200 |
|
---|
201 | private static IDiskCacheAttributes getDiskCacheAttributes(int maxDiskObjects, String cachePath, String cacheName) {
|
---|
202 | IDiskCacheAttributes ret;
|
---|
203 | removeStaleFiles(cachePath + File.separator + cacheName, USE_BLOCK_CACHE.get() ? "_INDEX_v2" : "_BLOCK_v2");
|
---|
204 | String newCacheName = cacheName + (USE_BLOCK_CACHE.get() ? "_BLOCK_v2" : "_INDEX_v2");
|
---|
205 |
|
---|
206 | if (USE_BLOCK_CACHE.get()) {
|
---|
207 | BlockDiskCacheAttributes blockAttr = new BlockDiskCacheAttributes();
|
---|
208 | /*
|
---|
209 | * BlockDiskCache never optimizes the file, so when file size is reduced, it will never be truncated to desired size.
|
---|
210 | *
|
---|
211 | * If for some mysterious reason, file size is greater than the value set in preferences, just use the whole file. If the user
|
---|
212 | * wants to reduce the file size, (s)he may just go to preferences and there it should be handled (by removing old file)
|
---|
213 | */
|
---|
214 | File diskCacheFile = new File(cachePath + File.separator + newCacheName + ".data");
|
---|
215 | if (diskCacheFile.exists()) {
|
---|
216 | blockAttr.setMaxKeySize((int) Math.max(maxDiskObjects, diskCacheFile.length()/1024));
|
---|
217 | } else {
|
---|
218 | blockAttr.setMaxKeySize(maxDiskObjects);
|
---|
219 | }
|
---|
220 | blockAttr.setBlockSizeBytes(4096); // use 4k blocks
|
---|
221 | ret = blockAttr;
|
---|
222 | } else {
|
---|
223 | IndexedDiskCacheAttributes indexAttr = new IndexedDiskCacheAttributes();
|
---|
224 | indexAttr.setMaxKeySize(maxDiskObjects);
|
---|
225 | ret = indexAttr;
|
---|
226 | }
|
---|
227 | ret.setDiskLimitType(IDiskCacheAttributes.DiskLimitType.SIZE);
|
---|
228 | File path = new File(cachePath);
|
---|
229 | if (!path.exists() && !path.mkdirs()) {
|
---|
230 | Logging.warn("Failed to create cache path: {0}", cachePath);
|
---|
231 | } else {
|
---|
232 | ret.setDiskPath(cachePath);
|
---|
233 | }
|
---|
234 | ret.setCacheName(newCacheName);
|
---|
235 |
|
---|
236 | return ret;
|
---|
237 | }
|
---|
238 |
|
---|
239 | private static void removeStaleFiles(String basePathPart, String suffix) {
|
---|
240 | deleteCacheFiles(basePathPart + suffix);
|
---|
241 | }
|
---|
242 |
|
---|
243 | private static void deleteCacheFiles(String basePathPart) {
|
---|
244 | Utils.deleteFileIfExists(new File(basePathPart + ".key"));
|
---|
245 | Utils.deleteFileIfExists(new File(basePathPart + ".data"));
|
---|
246 | }
|
---|
247 |
|
---|
248 | private static CompositeCacheAttributes getCacheAttributes(int maxMemoryElements) {
|
---|
249 | CompositeCacheAttributes ret = new CompositeCacheAttributes();
|
---|
250 | ret.setMaxObjects(maxMemoryElements);
|
---|
251 | ret.setDiskUsagePattern(DiskUsagePattern.UPDATE);
|
---|
252 | return ret;
|
---|
253 | }
|
---|
254 | }
|
---|