source: josm/trunk/src/org/openstreetmap/josm/data/cache/JCSCachedTileLoaderJob.java@ 8602

Last change on this file since 8602 was 8602, checked in by wiktorn, 9 years ago

Properly handle file based tile sources.

  • move getThreadFactory(String name) to Utils class, so it's easily usable across JOSM
  • rollback changes in [8485]
  • detect that we are working with filesystem TileSource in AbstractTileSourceLayer and if so, do not use JCS as caching mechanism, as tiles are already local
  • change return value of getTileSourceInfo in AbstractTileSourceLayer to AbstractTMSTileSource, as this is anyway - lowest we can work with
  • add test data for testing file base tile sources

closes: #11548

File size: 19.7 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.data.cache;
3
4import java.io.FileNotFoundException;
5import java.io.IOException;
6import java.net.HttpURLConnection;
7import java.net.URL;
8import java.net.URLConnection;
9import java.util.HashSet;
10import java.util.List;
11import java.util.Map;
12import java.util.Random;
13import java.util.Set;
14import java.util.concurrent.ConcurrentHashMap;
15import java.util.concurrent.ConcurrentMap;
16import java.util.concurrent.LinkedBlockingDeque;
17import java.util.concurrent.ThreadPoolExecutor;
18import java.util.concurrent.TimeUnit;
19import java.util.logging.Level;
20import java.util.logging.Logger;
21
22import org.apache.commons.jcs.access.behavior.ICacheAccess;
23import org.apache.commons.jcs.engine.behavior.ICacheElement;
24import org.openstreetmap.gui.jmapviewer.FeatureAdapter;
25import org.openstreetmap.josm.Main;
26import org.openstreetmap.josm.data.cache.ICachedLoaderListener.LoadResult;
27import org.openstreetmap.josm.data.preferences.IntegerProperty;
28import org.openstreetmap.josm.tools.Utils;
29
30/**
31 * @author Wiktor Niesiobędzki
32 *
33 * @param <K> cache entry key type
34 * @param <V> cache value type
35 *
36 * Generic loader for HTTP based tiles. Uses custom attribute, to check, if entry has expired
37 * according to HTTP headers sent with tile. If so, it tries to verify using Etags
38 * or If-Modified-Since / Last-Modified.
39 *
40 * If the tile is not valid, it will try to download it from remote service and put it
41 * to cache. If remote server will fail it will try to use stale entry.
42 *
43 * This class will keep only one Job running for specified tile. All others will just finish, but
44 * listeners will be gathered and notified, once download job will be finished
45 *
46 * @since 8168
47 */
48public abstract class JCSCachedTileLoaderJob<K, V extends CacheEntry> implements ICachedLoaderJob<K>, Runnable {
49 private static final Logger log = FeatureAdapter.getLogger(JCSCachedTileLoaderJob.class.getCanonicalName());
50 protected static final long DEFAULT_EXPIRE_TIME = 1000L * 60 * 60 * 24 * 7; // 7 days
51 // Limit for the max-age value send by the server.
52 protected static final long EXPIRE_TIME_SERVER_LIMIT = 1000L * 60 * 60 * 24 * 28; // 4 weeks
53 // Absolute expire time limit. Cached tiles that are older will not be used,
54 // even if the refresh from the server fails.
55 protected static final long ABSOLUTE_EXPIRE_TIME_LIMIT = Long.MAX_VALUE; // unlimited
56
57 /**
58 * maximum download threads that will be started
59 */
60 public static final IntegerProperty THREAD_LIMIT = new IntegerProperty("cache.jcs.max_threads", 10);
61
62 /*
63 * ThreadPoolExecutor starts new threads, until THREAD_LIMIT is reached. Then it puts tasks into LinkedBlockingDeque.
64 *
65 * The queue works FIFO, so one needs to take care about ordering of the entries submitted
66 *
67 * There is no point in canceling tasks, that are already taken by worker threads (if we made so much effort, we can at least cache
68 * the response, so later it could be used). We could actually cancel what is in LIFOQueue, but this is a tradeoff between simplicity
69 * and performance (we do want to have something to offer to worker threads before tasks will be resubmitted by class consumer)
70 */
71
72 private static ThreadPoolExecutor DEFAULT_DOWNLOAD_JOB_DISPATCHER = new ThreadPoolExecutor(
73 2, // we have a small queue, so threads will be quickly started (threads are started only, when queue is full)
74 THREAD_LIMIT.get().intValue(), // do not this number of threads
75 30, // keepalive for thread
76 TimeUnit.SECONDS,
77 // make queue of LIFO type - so recently requested tiles will be loaded first (assuming that these are which user is waiting to see)
78 new LinkedBlockingDeque<Runnable>(),
79 Utils.getNamedThreadFactory("JCS downloader")
80 );
81
82
83
84 private static ConcurrentMap<String, Set<ICachedLoaderListener>> inProgress = new ConcurrentHashMap<>();
85 private static ConcurrentMap<String, Boolean> useHead = new ConcurrentHashMap<>();
86
87 protected long now; // when the job started
88
89 private ICacheAccess<K, V> cache;
90 private ICacheElement<K, V> cacheElement;
91 protected V cacheData = null;
92 protected CacheEntryAttributes attributes = null;
93
94 // HTTP connection parameters
95 private int connectTimeout;
96 private int readTimeout;
97 private Map<String, String> headers;
98 private ThreadPoolExecutor downloadJobExecutor;
99 private Runnable finishTask;
100 private boolean force = false;
101
102 /**
103 * @param cache cache instance that we will work on
104 * @param headers HTTP headers to be sent together with request
105 * @param readTimeout when connecting to remote resource
106 * @param connectTimeout when connecting to remote resource
107 * @param downloadJobExecutor that will be executing the jobs
108 */
109 public JCSCachedTileLoaderJob(ICacheAccess<K, V> cache,
110 int connectTimeout, int readTimeout,
111 Map<String, String> headers,
112 ThreadPoolExecutor downloadJobExecutor) {
113
114 this.cache = cache;
115 this.now = System.currentTimeMillis();
116 this.connectTimeout = connectTimeout;
117 this.readTimeout = readTimeout;
118 this.headers = headers;
119 this.downloadJobExecutor = downloadJobExecutor;
120 }
121
122 /**
123 * @param cache cache instance that we will work on
124 * @param headers HTTP headers to be sent together with request
125 * @param readTimeout when connecting to remote resource
126 * @param connectTimeout when connecting to remote resource
127 */
128 public JCSCachedTileLoaderJob(ICacheAccess<K, V> cache,
129 int connectTimeout, int readTimeout,
130 Map<String, String> headers) {
131 this(cache, connectTimeout, readTimeout,
132 headers, DEFAULT_DOWNLOAD_JOB_DISPATCHER);
133 }
134
135 private void ensureCacheElement() {
136 if (cacheElement == null && getCacheKey() != null) {
137 cacheElement = cache.getCacheElement(getCacheKey());
138 if (cacheElement != null) {
139 attributes = (CacheEntryAttributes) cacheElement.getElementAttributes();
140 cacheData = cacheElement.getVal();
141 }
142 }
143 }
144
145 public V get() {
146 ensureCacheElement();
147 return cacheData;
148 }
149
150 @Override
151 public void submit(ICachedLoaderListener listener, boolean force) {
152 this.force = force;
153 boolean first = false;
154 URL url = getUrl();
155 String deduplicationKey = null;
156 if (url != null) {
157 // url might be null, for example when Bing Attribution is not loaded yet
158 deduplicationKey = url.toString();
159 }
160 if (deduplicationKey == null) {
161 log.log(Level.WARNING, "No url returned for: {0}, skipping", getCacheKey());
162 return;
163 }
164 synchronized (inProgress) {
165 Set<ICachedLoaderListener> newListeners = inProgress.get(deduplicationKey);
166 if (newListeners == null) {
167 newListeners = new HashSet<>();
168 inProgress.put(deduplicationKey, newListeners);
169 first = true;
170 }
171 newListeners.add(listener);
172 }
173
174 if (first || force) {
175 ensureCacheElement();
176 if (!force && cacheElement != null && isCacheElementValid() && isObjectLoadable()) {
177 // we got something in cache, and it's valid, so lets return it
178 log.log(Level.FINE, "JCS - Returning object from cache: {0}", getCacheKey());
179 finishLoading(LoadResult.SUCCESS);
180 return;
181 }
182 // object not in cache, so submit work to separate thread
183 downloadJobExecutor.execute(this);
184 }
185 }
186
187 /**
188 * This method is run when job has finished
189 */
190 protected void executionFinished() {
191 if (finishTask != null) {
192 finishTask.run();
193 }
194 }
195
196 /**
197 *
198 * @return checks if object from cache has sufficient data to be returned
199 */
200 protected boolean isObjectLoadable() {
201 byte[] content = cacheData.getContent();
202 return content != null && content.length > 0;
203 }
204
205 /**
206 * Simple implementation. All errors should be cached as empty. Though some JDK (JDK8 on Windows for example)
207 * doesn't return 4xx error codes, instead they do throw an FileNotFoundException or IOException
208 *
209 * @return true if we should put empty object into cache, regardless of what remote resource has returned
210 */
211 protected boolean cacheAsEmpty() {
212 return attributes.getResponseCode() < 500;
213 }
214
215 /**
216 * @return key under which discovered server settings will be kept
217 */
218 protected String getServerKey() {
219 return getUrl().getHost();
220 }
221
222 @Override
223 public void run() {
224 final Thread currentThread = Thread.currentThread();
225 final String oldName = currentThread.getName();
226 currentThread.setName("JCS Downloading: " + getUrl());
227 try {
228 // try to load object from remote resource
229 if (loadObject()) {
230 finishLoading(LoadResult.SUCCESS);
231 } else {
232 // if loading failed - check if we can return stale entry
233 if (isObjectLoadable()) {
234 // try to get stale entry in cache
235 finishLoading(LoadResult.SUCCESS);
236 log.log(Level.FINE, "JCS - found stale object in cache: {0}", getUrl());
237 } else {
238 // failed completely
239 finishLoading(LoadResult.FAILURE);
240 }
241 }
242 } finally {
243 executionFinished();
244 currentThread.setName(oldName);
245 }
246 }
247
248 private void finishLoading(LoadResult result) {
249 Set<ICachedLoaderListener> listeners = null;
250 synchronized (inProgress) {
251 listeners = inProgress.remove(getUrl().toString());
252 }
253 if (listeners == null) {
254 log.log(Level.WARNING, "Listener not found for URL: {0}. Listener not notified!", getUrl());
255 return;
256 }
257 for (ICachedLoaderListener l: listeners) {
258 l.loadingFinished(cacheData, attributes, result);
259 }
260 }
261
262 private boolean isCacheElementValid() {
263 long expires = attributes.getExpirationTime();
264
265 // check by expire date set by server
266 if (expires != 0L) {
267 // put a limit to the expire time (some servers send a value
268 // that is too large)
269 expires = Math.min(expires, attributes.getCreateTime() + EXPIRE_TIME_SERVER_LIMIT);
270 if (now > expires) {
271 log.log(Level.FINE, "JCS - Object {0} has expired -> valid to {1}, now is: {2}",
272 new Object[]{getUrl(), Long.toString(expires), Long.toString(now)});
273 return false;
274 }
275 } else {
276 // check by file modification date
277 if (now - attributes.getLastModification() > DEFAULT_EXPIRE_TIME) {
278 log.log(Level.FINE, "JCS - Object has expired, maximum file age reached {0}", getUrl());
279 return false;
280 }
281 }
282 return true;
283 }
284
285 /**
286 * @return true if object was successfully downloaded, false, if there was a loading failure
287 */
288
289 private boolean loadObject() {
290 if (attributes == null) {
291 attributes = new CacheEntryAttributes();
292 }
293 try {
294 // if we have object in cache, and host doesn't support If-Modified-Since nor If-None-Match
295 // then just use HEAD request and check returned values
296 if (isObjectLoadable() &&
297 Boolean.TRUE.equals(useHead.get(getServerKey())) &&
298 isCacheValidUsingHead()) {
299 log.log(Level.FINE, "JCS - cache entry verified using HEAD request: {0}", getUrl());
300 return true;
301 }
302
303 HttpURLConnection urlConn = getURLConnection();
304
305 if (isObjectLoadable() &&
306 (now - attributes.getLastModification()) <= ABSOLUTE_EXPIRE_TIME_LIMIT) {
307 urlConn.setIfModifiedSince(attributes.getLastModification());
308 }
309 if (isObjectLoadable() && attributes.getEtag() != null) {
310 urlConn.addRequestProperty("If-None-Match", attributes.getEtag());
311 }
312 if (urlConn.getResponseCode() == 304) {
313 // If isModifiedSince or If-None-Match has been set
314 // and the server answers with a HTTP 304 = "Not Modified"
315 log.log(Level.FINE, "JCS - IfModifiedSince/Etag test: local version is up to date: {0}", getUrl());
316 return true;
317 } else if (isObjectLoadable() // we have an object in cache, but we haven't received 304 resposne code
318 && (
319 (attributes.getEtag() != null && attributes.getEtag().equals(urlConn.getRequestProperty("ETag"))) ||
320 attributes.getLastModification() == urlConn.getLastModified())
321 ) {
322 // we sent ETag or If-Modified-Since, but didn't get 304 response code
323 // for further requests - use HEAD
324 String serverKey = getServerKey();
325 log.log(Level.INFO, "JCS - Host: {0} found not to return 304 codes for If-Modifed-Since or If-None-Match headers",
326 serverKey);
327 useHead.put(serverKey, Boolean.TRUE);
328 }
329
330
331 attributes = parseHeaders(urlConn);
332
333 for (int i = 0; i < 5; ++i) {
334 if (urlConn.getResponseCode() == 503) {
335 Thread.sleep(5000+(new Random()).nextInt(5000));
336 continue;
337 }
338
339 attributes.setResponseCode(urlConn.getResponseCode());
340 byte[] raw = Utils.readBytesFromStream(urlConn.getInputStream());
341
342 if (isResponseLoadable(urlConn.getHeaderFields(), urlConn.getResponseCode(), raw)) {
343 // we need to check cacheEmpty, so for cases, when data is returned, but we want to store
344 // as empty (eg. empty tile images) to save some space
345 cacheData = createCacheEntry(raw);
346 cache.put(getCacheKey(), cacheData, attributes);
347 log.log(Level.FINE, "JCS - downloaded key: {0}, length: {1}, url: {2}",
348 new Object[] {getCacheKey(), raw.length, getUrl()});
349 return true;
350 } else if (cacheAsEmpty()) {
351 cacheData = createCacheEntry(new byte[]{});
352 cache.put(getCacheKey(), cacheData, attributes);
353 log.log(Level.FINE, "JCS - Caching empty object {0}", getUrl());
354 return true;
355 } else {
356 log.log(Level.FINE, "JCS - failure during load - reponse is not loadable nor cached as empty");
357 return false;
358 }
359 }
360 } catch (FileNotFoundException e) {
361 log.log(Level.FINE, "JCS - Caching empty object as server returned 404 for: {0}", getUrl());
362 attributes.setResponseCode(404);
363 boolean doCache = isResponseLoadable(null, 404, null) || cacheAsEmpty();
364 if (doCache) {
365 cacheData = createCacheEntry(new byte[]{});
366 cache.put(getCacheKey(), cacheData, attributes);
367 }
368 return doCache;
369 } catch (IOException e) {
370 log.log(Level.FINE, "JCS - IOExecption during communication with server for: {0}", getUrl());
371
372 attributes.setResponseCode(499); // set dummy error code
373 boolean doCache = isResponseLoadable(null, 499, null) || cacheAsEmpty(); //generic 499 error code returned
374 if (doCache) {
375 cacheData = createCacheEntry(new byte[]{});
376 cache.put(getCacheKey(), createCacheEntry(new byte[]{}), attributes);
377 }
378 return doCache;
379 } catch (Exception e) {
380 log.log(Level.WARNING, "JCS - Exception during download {0}", getUrl());
381 Main.warn(e);
382 }
383 log.log(Level.WARNING, "JCS - Silent failure during download: {0}", getUrl());
384 return false;
385
386 }
387
388 /**
389 * Check if the object is loadable. This means, if the data will be parsed, and if this response
390 * will finish as successful retrieve.
391 *
392 * This simple implementation doesn't load empty response, nor client (4xx) and server (5xx) errors
393 *
394 * @param headerFields headers sent by server
395 * @param responseCode http status code
396 * @param raw data read from server
397 * @return true if object should be cached and returned to listener
398 */
399 protected boolean isResponseLoadable(Map<String, List<String>> headerFields, int responseCode, byte[] raw) {
400 if (raw == null || raw.length == 0 || responseCode >= 400) {
401 return false;
402 }
403 return true;
404 }
405
406 protected abstract V createCacheEntry(byte[] content);
407
408 protected CacheEntryAttributes parseHeaders(URLConnection urlConn) {
409 CacheEntryAttributes ret = new CacheEntryAttributes();
410
411 Long lng = urlConn.getExpiration();
412 if (lng.equals(0L)) {
413 try {
414 String str = urlConn.getHeaderField("Cache-Control");
415 if (str != null) {
416 for (String token: str.split(",")) {
417 if (token.startsWith("max-age=")) {
418 lng = Long.parseLong(token.substring(8)) * 1000 +
419 System.currentTimeMillis();
420 }
421 }
422 }
423 } catch (NumberFormatException e) {
424 // ignore malformed Cache-Control headers
425 if (Main.isTraceEnabled()) {
426 Main.trace(e.getMessage());
427 }
428 }
429 }
430
431 ret.setExpirationTime(lng);
432 ret.setLastModification(now);
433 ret.setEtag(urlConn.getHeaderField("ETag"));
434 return ret;
435 }
436
437 private HttpURLConnection getURLConnection() throws IOException {
438 HttpURLConnection urlConn = (HttpURLConnection) getUrl().openConnection();
439 urlConn.setRequestProperty("Accept", "text/html, image/png, image/jpeg, image/gif, */*");
440 urlConn.setReadTimeout(readTimeout); // 30 seconds read timeout
441 urlConn.setConnectTimeout(connectTimeout);
442 for (Map.Entry<String, String> e: headers.entrySet()) {
443 urlConn.setRequestProperty(e.getKey(), e.getValue());
444 }
445 if (force) {
446 urlConn.setUseCaches(false);
447 }
448 return urlConn;
449 }
450
451 private boolean isCacheValidUsingHead() throws IOException {
452 HttpURLConnection urlConn = getURLConnection();
453 urlConn.setRequestMethod("HEAD");
454 long lastModified = urlConn.getLastModified();
455 return (attributes.getEtag() != null && attributes.getEtag().equals(urlConn.getRequestProperty("ETag"))) ||
456 (lastModified != 0 && lastModified <= attributes.getLastModification());
457 }
458
459 /**
460 * TODO: move to JobFactory
461 * cancels all outstanding tasks in the queue.
462 */
463 public void cancelOutstandingTasks() {
464 for (Runnable r: downloadJobExecutor.getQueue()) {
465 if (downloadJobExecutor.remove(r) && r instanceof JCSCachedTileLoaderJob) {
466 ((JCSCachedTileLoaderJob<?, ?>) r).handleJobCancellation();
467 }
468 }
469 }
470
471 /**
472 * Sets a job, that will be run, when job will finish execution
473 * @param runnable that will be executed
474 */
475 public void setFinishedTask(Runnable runnable) {
476 this.finishTask = runnable;
477
478 }
479
480 /**
481 * Marks this job as canceled
482 */
483 public void handleJobCancellation() {
484 finishLoading(LoadResult.CANCELED);
485 }
486}
Note: See TracBrowser for help on using the repository browser.