001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.data.cache;
003
004import java.io.FileNotFoundException;
005import java.io.IOException;
006import java.net.URL;
007import java.util.HashSet;
008import java.util.List;
009import java.util.Map;
010import java.util.Random;
011import java.util.Set;
012import java.util.concurrent.ConcurrentHashMap;
013import java.util.concurrent.ConcurrentMap;
014import java.util.concurrent.LinkedBlockingDeque;
015import java.util.concurrent.ThreadPoolExecutor;
016import java.util.concurrent.TimeUnit;
017import java.util.logging.Level;
018import java.util.logging.Logger;
019
020import org.apache.commons.jcs.access.behavior.ICacheAccess;
021import org.apache.commons.jcs.engine.behavior.ICacheElement;
022import org.openstreetmap.gui.jmapviewer.FeatureAdapter;
023import org.openstreetmap.josm.Main;
024import org.openstreetmap.josm.data.cache.ICachedLoaderListener.LoadResult;
025import org.openstreetmap.josm.data.preferences.IntegerProperty;
026import org.openstreetmap.josm.tools.HttpClient;
027import org.openstreetmap.josm.tools.Utils;
028
029/**
030 * @author Wiktor Niesiobędzki
031 *
032 * @param <K> cache entry key type
033 * @param <V> cache value type
034 *
035 * Generic loader for HTTP based tiles. Uses custom attribute, to check, if entry has expired
036 * according to HTTP headers sent with tile. If so, it tries to verify using Etags
037 * or If-Modified-Since / Last-Modified.
038 *
039 * If the tile is not valid, it will try to download it from remote service and put it
040 * to cache. If remote server will fail it will try to use stale entry.
041 *
042 * This class will keep only one Job running for specified tile. All others will just finish, but
043 * listeners will be gathered and notified, once download job will be finished
044 *
045 * @since 8168
046 */
047public abstract class JCSCachedTileLoaderJob<K, V extends CacheEntry> implements ICachedLoaderJob<K>, Runnable {
048    private static final Logger log = FeatureAdapter.getLogger(JCSCachedTileLoaderJob.class.getCanonicalName());
049    protected static final long DEFAULT_EXPIRE_TIME = 1000L * 60 * 60 * 24 * 7; // 7 days
050    // Limit for the max-age value send by the server.
051    protected static final long EXPIRE_TIME_SERVER_LIMIT = 1000L * 60 * 60 * 24 * 28; // 4 weeks
052    // Absolute expire time limit. Cached tiles that are older will not be used,
053    // even if the refresh from the server fails.
054    protected static final long ABSOLUTE_EXPIRE_TIME_LIMIT = 1000L * 60 * 60 * 24 * 365; // 1 year
055
056    /**
057     * maximum download threads that will be started
058     */
059    public static final IntegerProperty THREAD_LIMIT = new IntegerProperty("cache.jcs.max_threads", 10);
060
061    /*
062     * ThreadPoolExecutor starts new threads, until THREAD_LIMIT is reached. Then it puts tasks into LinkedBlockingDeque.
063     *
064     * The queue works FIFO, so one needs to take care about ordering of the entries submitted
065     *
066     * 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
067     * the response, so later it could be used). We could actually cancel what is in LIFOQueue, but this is a tradeoff between simplicity
068     * and performance (we do want to have something to offer to worker threads before tasks will be resubmitted by class consumer)
069     */
070
071    private static ThreadPoolExecutor DEFAULT_DOWNLOAD_JOB_DISPATCHER = new ThreadPoolExecutor(
072            2, // we have a small queue, so threads will be quickly started (threads are started only, when queue is full)
073            THREAD_LIMIT.get().intValue(), // do not this number of threads
074            30, // keepalive for thread
075            TimeUnit.SECONDS,
076            // make queue of LIFO type - so recently requested tiles will be loaded first (assuming that these are which user is waiting to see)
077            new LinkedBlockingDeque<Runnable>(),
078            Utils.newThreadFactory("JCS-downloader-%d", Thread.NORM_PRIORITY)
079            );
080
081
082
083    private static ConcurrentMap<String, Set<ICachedLoaderListener>> inProgress = new ConcurrentHashMap<>();
084    private static ConcurrentMap<String, Boolean> useHead = new ConcurrentHashMap<>();
085
086    protected long now; // when the job started
087
088    private ICacheAccess<K, V> cache;
089    private ICacheElement<K, V> cacheElement;
090    protected V cacheData;
091    protected CacheEntryAttributes attributes;
092
093    // HTTP connection parameters
094    private int connectTimeout;
095    private int readTimeout;
096    private Map<String, String> headers;
097    private ThreadPoolExecutor downloadJobExecutor;
098    private Runnable finishTask;
099    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
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    public V get() {
145        ensureCacheElement();
146        return cacheData;
147    }
148
149    @Override
150    public void submit(ICachedLoaderListener listener, boolean force) throws IOException {
151        this.force = force;
152        boolean first = false;
153        URL url = getUrl();
154        String deduplicationKey = null;
155        if (url != null) {
156            // url might be null, for example when Bing Attribution is not loaded yet
157            deduplicationKey = url.toString();
158        }
159        if (deduplicationKey == null) {
160            log.log(Level.WARNING, "No url returned for: {0}, skipping", getCacheKey());
161            throw new IllegalArgumentException("No url returned");
162        }
163        synchronized (inProgress) {
164            Set<ICachedLoaderListener> newListeners = inProgress.get(deduplicationKey);
165            if (newListeners == null) {
166                newListeners = new HashSet<>();
167                inProgress.put(deduplicationKey, newListeners);
168                first = true;
169            }
170            newListeners.add(listener);
171        }
172
173        if (first || force) {
174            // submit all jobs to separate thread, so calling thread is not blocked with IO when loading from disk
175            log.log(Level.FINE, "JCS - Submitting job for execution for url: {0}", getUrlNoException());
176            downloadJobExecutor.execute(this);
177        }
178    }
179
180    /**
181     * This method is run when job has finished
182     */
183    protected void executionFinished() {
184        if (finishTask != null) {
185            finishTask.run();
186        }
187    }
188
189    /**
190     *
191     * @return checks if object from cache has sufficient data to be returned
192     */
193    protected boolean isObjectLoadable() {
194        if (cacheData == null) {
195            return false;
196        }
197        byte[] content = cacheData.getContent();
198        return content != null && content.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        return getUrlNoException().getHost();
216    }
217
218    @Override
219    public void run() {
220        final Thread currentThread = Thread.currentThread();
221        final String oldName = currentThread.getName();
222        currentThread.setName("JCS Downloading: " + getUrlNoException());
223        log.log(Level.FINE, "JCS - starting fetch of url: {0} ", getUrlNoException());
224        ensureCacheElement();
225        try {
226            // try to fetch from cache
227            if (!force && cacheElement != null && isCacheElementValid() && isObjectLoadable()) {
228                // we got something in cache, and it's valid, so lets return it
229                log.log(Level.FINE, "JCS - Returning object from cache: {0}", getCacheKey());
230                finishLoading(LoadResult.SUCCESS);
231                return;
232            }
233
234            // try to load object from remote resource
235            if (loadObject()) {
236                finishLoading(LoadResult.SUCCESS);
237            } else {
238                // if loading failed - check if we can return stale entry
239                if (isObjectLoadable()) {
240                    // try to get stale entry in cache
241                    finishLoading(LoadResult.SUCCESS);
242                    log.log(Level.FINE, "JCS - found stale object in cache: {0}", getUrlNoException());
243                } else {
244                    // failed completely
245                    finishLoading(LoadResult.FAILURE);
246                }
247            }
248        } finally {
249            executionFinished();
250            currentThread.setName(oldName);
251        }
252    }
253
254    private void finishLoading(LoadResult result) {
255        Set<ICachedLoaderListener> listeners = null;
256        synchronized (inProgress) {
257            listeners = inProgress.remove(getUrlNoException().toString());
258        }
259        if (listeners == null) {
260            log.log(Level.WARNING, "Listener not found for URL: {0}. Listener not notified!", getUrlNoException());
261            return;
262        }
263        for (ICachedLoaderListener l: listeners) {
264            l.loadingFinished(cacheData, attributes, result);
265        }
266    }
267
268    protected boolean isCacheElementValid() {
269        long expires = attributes.getExpirationTime();
270
271        // check by expire date set by server
272        if (expires != 0L) {
273            // put a limit to the expire time (some servers send a value
274            // that is too large)
275            expires = Math.min(expires, attributes.getCreateTime() + EXPIRE_TIME_SERVER_LIMIT);
276            if (now > expires) {
277                log.log(Level.FINE, "JCS - Object {0} has expired -> valid to {1}, now is: {2}",
278                        new Object[]{getUrlNoException(), Long.toString(expires), Long.toString(now)});
279                return false;
280            }
281        } else if (attributes.getLastModification() > 0 &&
282                now - attributes.getLastModification() > DEFAULT_EXPIRE_TIME) {
283            // check by file modification date
284            log.log(Level.FINE, "JCS - Object has expired, maximum file age reached {0}", getUrlNoException());
285            return false;
286        } else if (now - attributes.getCreateTime() > DEFAULT_EXPIRE_TIME) {
287            log.log(Level.FINE, "JCS - Object has expired, maximum time since object creation reached {0}", getUrlNoException());
288            return false;
289        }
290        return true;
291    }
292
293    /**
294     * @return true if object was successfully downloaded, false, if there was a loading failure
295     */
296
297    private boolean loadObject() {
298        if (attributes == null) {
299            attributes = new CacheEntryAttributes();
300        }
301        try {
302            // if we have object in cache, and host doesn't support If-Modified-Since nor If-None-Match
303            // then just use HEAD request and check returned values
304            if (isObjectLoadable() &&
305                    Boolean.TRUE.equals(useHead.get(getServerKey())) &&
306                    isCacheValidUsingHead()) {
307                log.log(Level.FINE, "JCS - cache entry verified using HEAD request: {0}", getUrl());
308                return true;
309            }
310
311            final HttpClient request = getRequest("GET", true);
312
313            if (isObjectLoadable()  &&
314                    (now - attributes.getLastModification()) <= ABSOLUTE_EXPIRE_TIME_LIMIT) {
315                request.setIfModifiedSince(attributes.getLastModification());
316            }
317            if (isObjectLoadable() && attributes.getEtag() != null) {
318                request.setHeader("If-None-Match", attributes.getEtag());
319            }
320
321            final HttpClient.Response urlConn = request.connect();
322
323            if (urlConn.getResponseCode() == 304) {
324                // If isModifiedSince or If-None-Match has been set
325                // and the server answers with a HTTP 304 = "Not Modified"
326                log.log(Level.FINE, "JCS - If-Modified-Since/ETag test: local version is up to date: {0}", getUrl());
327                return true;
328            } else if (isObjectLoadable() // we have an object in cache, but we haven't received 304 response code
329                    && (
330                            (attributes.getEtag() != null && attributes.getEtag().equals(urlConn.getHeaderField("ETag"))) ||
331                            attributes.getLastModification() == urlConn.getLastModified())
332                    ) {
333                // we sent ETag or If-Modified-Since, but didn't get 304 response code
334                // for further requests - use HEAD
335                String serverKey = getServerKey();
336                log.log(Level.INFO, "JCS - Host: {0} found not to return 304 codes for If-Modified-Since or If-None-Match headers",
337                        serverKey);
338                useHead.put(serverKey, Boolean.TRUE);
339            }
340
341
342            attributes = parseHeaders(urlConn);
343
344            for (int i = 0; i < 5; ++i) {
345                if (urlConn.getResponseCode() == 503) {
346                    Thread.sleep(5000+(new Random()).nextInt(5000));
347                    continue;
348                }
349
350                attributes.setResponseCode(urlConn.getResponseCode());
351                byte[] raw;
352                if (urlConn.getResponseCode() == 200) {
353                    raw = Utils.readBytesFromStream(urlConn.getContent());
354                } else {
355                    raw = new byte[]{};
356                }
357
358                if (isResponseLoadable(urlConn.getHeaderFields(), urlConn.getResponseCode(), raw)) {
359                    // we need to check cacheEmpty, so for cases, when data is returned, but we want to store
360                    // as empty (eg. empty tile images) to save some space
361                    cacheData = createCacheEntry(raw);
362                    cache.put(getCacheKey(), cacheData, attributes);
363                    log.log(Level.FINE, "JCS - downloaded key: {0}, length: {1}, url: {2}",
364                            new Object[] {getCacheKey(), raw.length, getUrl()});
365                    return true;
366                } else if (cacheAsEmpty()) {
367                    cacheData = createCacheEntry(new byte[]{});
368                    cache.put(getCacheKey(), cacheData, attributes);
369                    log.log(Level.FINE, "JCS - Caching empty object {0}", getUrl());
370                    return true;
371                } else {
372                    log.log(Level.FINE, "JCS - failure during load - reponse is not loadable nor cached as empty");
373                    return false;
374                }
375            }
376        } catch (FileNotFoundException e) {
377            log.log(Level.FINE, "JCS - Caching empty object as server returned 404 for: {0}", getUrlNoException());
378            attributes.setResponseCode(404);
379            attributes.setErrorMessage(e.toString());
380            boolean doCache = isResponseLoadable(null, 404, null) || cacheAsEmpty();
381            if (doCache) {
382                cacheData = createCacheEntry(new byte[]{});
383                cache.put(getCacheKey(), cacheData, attributes);
384            }
385            return doCache;
386        } catch (IOException e) {
387            log.log(Level.FINE, "JCS - IOExecption during communication with server for: {0}", getUrlNoException());
388            attributes.setErrorMessage(e.toString());
389            attributes.setResponseCode(499); // set dummy error code
390            boolean doCache = isResponseLoadable(null, 499, null) || cacheAsEmpty(); //generic 499 error code returned
391            if (doCache) {
392                cacheData = createCacheEntry(new byte[]{});
393                cache.put(getCacheKey(), createCacheEntry(new byte[]{}), attributes);
394            }
395            return doCache;
396        } catch (Exception e) {
397            attributes.setErrorMessage(e.toString());
398            log.log(Level.WARNING, "JCS - Exception during download {0}",  getUrlNoException());
399            Main.warn(e);
400        }
401        log.log(Level.WARNING, "JCS - Silent failure during download: {0}", getUrlNoException());
402        return false;
403
404    }
405
406    /**
407     * Check if the object is loadable. This means, if the data will be parsed, and if this response
408     * will finish as successful retrieve.
409     *
410     * This simple implementation doesn't load empty response, nor client (4xx) and server (5xx) errors
411     *
412     * @param headerFields headers sent by server
413     * @param responseCode http status code
414     * @param raw data read from server
415     * @return true if object should be cached and returned to listener
416     */
417    protected boolean isResponseLoadable(Map<String, List<String>> headerFields, int responseCode, byte[] raw) {
418        if (raw == null || raw.length == 0 || responseCode >= 400) {
419            return false;
420        }
421        return true;
422    }
423
424    protected abstract V createCacheEntry(byte[] content);
425
426    protected CacheEntryAttributes parseHeaders(HttpClient.Response urlConn) {
427        CacheEntryAttributes ret = new CacheEntryAttributes();
428
429        Long lng = urlConn.getExpiration();
430        if (lng.equals(0L)) {
431            try {
432                String str = urlConn.getHeaderField("Cache-Control");
433                if (str != null) {
434                    for (String token: str.split(",")) {
435                        if (token.startsWith("max-age=")) {
436                            lng = Long.parseLong(token.substring(8)) * 1000 +
437                                    System.currentTimeMillis();
438                        }
439                    }
440                }
441            } catch (NumberFormatException e) {
442                // ignore malformed Cache-Control headers
443                if (Main.isTraceEnabled()) {
444                    Main.trace(e.getMessage());
445                }
446            }
447        }
448
449        ret.setExpirationTime(lng);
450        ret.setLastModification(now);
451        ret.setEtag(urlConn.getHeaderField("ETag"));
452
453        return ret;
454    }
455
456    private HttpClient getRequest(String requestMethod, boolean noCache) throws IOException {
457        final HttpClient urlConn = HttpClient.create(getUrl(), requestMethod);
458        urlConn.setAccept("text/html, image/png, image/jpeg, image/gif, */*");
459        urlConn.setReadTimeout(readTimeout); // 30 seconds read timeout
460        urlConn.setConnectTimeout(connectTimeout);
461        if (headers != null) {
462            urlConn.setHeaders(headers);
463        }
464
465        if (force || noCache) {
466            urlConn.useCache(false);
467        }
468        return urlConn;
469    }
470
471    private boolean isCacheValidUsingHead() throws IOException {
472        final HttpClient.Response urlConn = getRequest("HEAD", false).connect();
473        long lastModified = urlConn.getLastModified();
474        return (attributes.getEtag() != null && attributes.getEtag().equals(urlConn.getHeaderField("ETag"))) ||
475                (lastModified != 0 && lastModified <= attributes.getLastModification());
476    }
477
478    /**
479     * TODO: move to JobFactory
480     * cancels all outstanding tasks in the queue.
481     */
482    public void cancelOutstandingTasks() {
483        for (Runnable r: downloadJobExecutor.getQueue()) {
484            if (downloadJobExecutor.remove(r) && r instanceof JCSCachedTileLoaderJob) {
485                ((JCSCachedTileLoaderJob<?, ?>) r).handleJobCancellation();
486            }
487        }
488    }
489
490    /**
491     * Sets a job, that will be run, when job will finish execution
492     * @param runnable that will be executed
493     */
494    public void setFinishedTask(Runnable runnable) {
495        this.finishTask = runnable;
496
497    }
498
499    /**
500     * Marks this job as canceled
501     */
502    public void handleJobCancellation() {
503        finishLoading(LoadResult.CANCELED);
504    }
505
506    private URL getUrlNoException() {
507        try {
508            return getUrl();
509        } catch (IOException e) {
510            return null;
511        }
512    }
513}