source: josm/trunk/src/org/openstreetmap/josm/data/cache/JCSCacheManager.java@ 13643

Last change on this file since 13643 was 13643, checked in by wiktorn, 6 years ago

In case of any IOExceptions when creating disk cache return memory-only cache

Closes: #16193

  • Property svn:eol-style set to native
File size: 11.9 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.data.cache;
3
4import java.io.File;
5import java.io.IOException;
6import java.nio.channels.FileChannel;
7import java.nio.channels.FileLock;
8import java.nio.file.StandardOpenOption;
9import java.util.Arrays;
10import java.util.Properties;
11import java.util.logging.Handler;
12import java.util.logging.Level;
13import java.util.logging.LogRecord;
14import java.util.logging.Logger;
15import java.util.logging.SimpleFormatter;
16
17import org.apache.commons.jcs.access.CacheAccess;
18import org.apache.commons.jcs.auxiliary.AuxiliaryCache;
19import org.apache.commons.jcs.auxiliary.AuxiliaryCacheFactory;
20import org.apache.commons.jcs.auxiliary.disk.behavior.IDiskCacheAttributes;
21import org.apache.commons.jcs.auxiliary.disk.block.BlockDiskCacheAttributes;
22import org.apache.commons.jcs.auxiliary.disk.block.BlockDiskCacheFactory;
23import org.apache.commons.jcs.auxiliary.disk.indexed.IndexedDiskCacheAttributes;
24import org.apache.commons.jcs.auxiliary.disk.indexed.IndexedDiskCacheFactory;
25import org.apache.commons.jcs.engine.CompositeCacheAttributes;
26import org.apache.commons.jcs.engine.behavior.ICompositeCacheAttributes.DiskUsagePattern;
27import org.apache.commons.jcs.engine.control.CompositeCache;
28import org.apache.commons.jcs.engine.control.CompositeCacheManager;
29import org.apache.commons.jcs.utils.serialization.StandardSerializer;
30import org.openstreetmap.josm.data.preferences.BooleanProperty;
31import org.openstreetmap.josm.data.preferences.IntegerProperty;
32import org.openstreetmap.josm.spi.preferences.Config;
33import org.openstreetmap.josm.tools.Logging;
34import 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 */
43public 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() {
104 File cacheDir = new File(Config.getDirs().getCacheDirectory(true), "jcs");
105
106 if (!cacheDir.exists() && !cacheDir.mkdirs()) {
107 Logging.warn("Cache directory " + cacheDir.toString() + " does not exists and could not create it");
108 } else {
109 File cacheDirLockPath = new File(cacheDir, ".lock");
110 try {
111 if (!cacheDirLockPath.exists() && !cacheDirLockPath.createNewFile()) {
112 Logging.warn("Cannot create cache dir lock file");
113 }
114 cacheDirLock = FileChannel.open(cacheDirLockPath.toPath(), StandardOpenOption.WRITE).tryLock();
115
116 if (cacheDirLock == null)
117 Logging.warn("Cannot lock cache directory. Will not use disk cache");
118 } catch (IOException e) {
119 Logging.warn("Cannot create cache dir \"" + cacheDirLockPath.toString() + "\" lock file: " + e.toString());
120 Logging.warn("Will not use disk cache");
121 }
122 }
123 // this could be moved to external file
124 Properties props = new Properties();
125 // these are default common to all cache regions
126 // use of auxiliary cache and sizing of the caches is done with giving proper geCache(...) params
127 // CHECKSTYLE.OFF: SingleSpaceSeparator
128 props.setProperty("jcs.default.cacheattributes", CompositeCacheAttributes.class.getCanonicalName());
129 props.setProperty("jcs.default.cacheattributes.MaxObjects", DEFAULT_MAX_OBJECTS_IN_MEMORY.get().toString());
130 props.setProperty("jcs.default.cacheattributes.UseMemoryShrinker", "true");
131 props.setProperty("jcs.default.cacheattributes.DiskUsagePatternName", "UPDATE"); // store elements on disk on put
132 props.setProperty("jcs.default.elementattributes", CacheEntryAttributes.class.getCanonicalName());
133 props.setProperty("jcs.default.elementattributes.IsEternal", "false");
134 props.setProperty("jcs.default.elementattributes.MaxLife", Long.toString(maxObjectTTL));
135 props.setProperty("jcs.default.elementattributes.IdleTime", Long.toString(maxObjectTTL));
136 props.setProperty("jcs.default.elementattributes.IsSpool", "true");
137 // CHECKSTYLE.ON: SingleSpaceSeparator
138 CompositeCacheManager cm = CompositeCacheManager.getUnconfiguredInstance();
139 cm.configure(props);
140 cacheManager = cm;
141 }
142
143 /**
144 * Returns configured cache object for named cache region
145 * @param <K> key type
146 * @param <V> value type
147 * @param cacheName region name
148 * @return cache access object
149 */
150 public static <K, V> CacheAccess<K, V> getCache(String cacheName) {
151 return getCache(cacheName, DEFAULT_MAX_OBJECTS_IN_MEMORY.get().intValue(), 0, null);
152 }
153
154 /**
155 * Returns configured cache object with defined limits of memory cache and disk cache
156 * @param <K> key type
157 * @param <V> value type
158 * @param cacheName region name
159 * @param maxMemoryObjects number of objects to keep in memory
160 * @param maxDiskObjects maximum size of the objects stored on disk in kB
161 * @param cachePath path to disk cache. if null, no disk cache will be created
162 * @return cache access object
163 */
164 public static <K, V> CacheAccess<K, V> getCache(String cacheName, int maxMemoryObjects, int maxDiskObjects, String cachePath) {
165 if (cacheManager != null)
166 return getCacheInner(cacheName, maxMemoryObjects, maxDiskObjects, cachePath);
167
168 synchronized (JCSCacheManager.class) {
169 if (cacheManager == null)
170 initialize();
171 return getCacheInner(cacheName, maxMemoryObjects, maxDiskObjects, cachePath);
172 }
173 }
174
175 @SuppressWarnings("unchecked")
176 private static <K, V> CacheAccess<K, V> getCacheInner(String cacheName, int maxMemoryObjects, int maxDiskObjects, String cachePath) {
177 CompositeCache<K, V> cc = cacheManager.getCache(cacheName, getCacheAttributes(maxMemoryObjects));
178
179 if (cachePath != null && cacheDirLock != null) {
180 IDiskCacheAttributes diskAttributes = getDiskCacheAttributes(maxDiskObjects, cachePath, cacheName);
181 try {
182 if (cc.getAuxCaches().length == 0) {
183 cc.setAuxCaches(new AuxiliaryCache[]{DISK_CACHE_FACTORY.createCache(
184 diskAttributes, cacheManager, null, new StandardSerializer())});
185 }
186 } catch (Exception e) {
187 // in case any error in setting auxiliary cache, do not use disk cache at all - only memory
188 cc.setAuxCaches(new AuxiliaryCache[0]);
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}
Note: See TracBrowser for help on using the repository browser.