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

Last change on this file since 12809 was 12765, checked in by wiktorn, 7 years ago

Use tools.Logging instead of FeatureAdapter.getLogger

See: #15229

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