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

Last change on this file since 12620 was 12620, checked in by Don-vip, 7 years ago

see #15182 - deprecate all Main logging methods and introduce suitable replacements in Logging for most of them

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