View Javadoc
1   /**
2    * This file Copyright (c) 2008-2018 Magnolia International
3    * Ltd.  (http://www.magnolia-cms.com). All rights reserved.
4    *
5    *
6    * This file is dual-licensed under both the Magnolia
7    * Network Agreement and the GNU General Public License.
8    * You may elect to use one or the other of these licenses.
9    *
10   * This file is distributed in the hope that it will be
11   * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
12   * implied warranty of MERCHANTABILITY or FITNESS FOR A
13   * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
14   * Redistribution, except as permitted by whichever of the GPL
15   * or MNA you select, is prohibited.
16   *
17   * 1. For the GPL license (GPL), you can redistribute and/or
18   * modify this file under the terms of the GNU General
19   * Public License, Version 3, as published by the Free Software
20   * Foundation.  You should have received a copy of the GNU
21   * General Public License, Version 3 along with this program;
22   * if not, write to the Free Software Foundation, Inc., 51
23   * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
24   *
25   * 2. For the Magnolia Network Agreement (MNA), this file
26   * and the accompanying materials are made available under the
27   * terms of the MNA which accompanies this distribution, and
28   * is available at http://www.magnolia-cms.com/mna.html
29   *
30   * Any modifications to this file must keep this entire header
31   * intact.
32   *
33   */
34  package info.magnolia.module.cache.filter;
35  
36  import info.magnolia.cms.filters.AbstractMgnlFilter;
37  import info.magnolia.cms.util.ServletUtil;
38  import info.magnolia.context.WebContext;
39  import info.magnolia.module.cache.AbstractCacheModule;
40  import info.magnolia.module.cache.BlockingCache;
41  import info.magnolia.module.cache.Cache;
42  import info.magnolia.module.cache.CacheModule;
43  import info.magnolia.module.cache.CacheModuleLifecycleListener;
44  import info.magnolia.module.cache.CachePolicyExecutor;
45  import info.magnolia.module.cache.CachePolicyResult;
46  import info.magnolia.module.cache.ContentCachingConfiguration;
47  import info.magnolia.module.cache.cachepolicy.result.CachePolicyResultProvider;
48  import info.magnolia.module.cache.exception.MgnlLockTimeoutException;
49  import info.magnolia.module.cache.mbean.CacheMonitor;
50  
51  import java.io.IOException;
52  
53  import javax.inject.Inject;
54  import javax.inject.Provider;
55  import javax.servlet.FilterChain;
56  import javax.servlet.FilterConfig;
57  import javax.servlet.ServletException;
58  import javax.servlet.ServletResponse;
59  import javax.servlet.http.HttpServletRequest;
60  import javax.servlet.http.HttpServletResponse;
61  import javax.servlet.http.HttpServletResponseWrapper;
62  
63  import org.apache.commons.lang3.exception.ExceptionUtils;
64  import org.slf4j.Logger;
65  import org.slf4j.LoggerFactory;
66  
67  /**
68   * Uses the CachePolicy to determine the cache behavior. Uses then the
69   * ContentCachingConfiguration to get the executors to be executed.
70   */
71  public class CacheFilter extends AbstractMgnlFilter implements CacheModuleLifecycleListener {
72  
73      private static final Logger log = LoggerFactory.getLogger(CacheFilter.class);
74  
75  
76      private String defaultContentCachingConfigurationName;
77      private Cache cache;
78      private ContentCachingConfiguration contentCaching;
79  
80      private final CacheModule cacheModule;
81      private final CacheMonitor monitor;
82      private final Provider<WebContext> webContextProvider;
83      private final Provider<CachePolicyResultProvider> cachePolicyResultProviderProvider;
84  
85      @Inject
86      public CacheFilter(Provider<WebContext> webContextProvider, CacheModule cacheModule, CacheMonitor cacheMonitor, Provider<CachePolicyResultProvider> cachePolicyResultProvider) {
87          this.cacheModule = cacheModule;
88          this.monitor = cacheMonitor;
89          this.webContextProvider = webContextProvider;
90          this.cachePolicyResultProviderProvider = cachePolicyResultProvider;
91      }
92  
93      public String getDefaultContentCachingConfigurationName() {
94          return defaultContentCachingConfigurationName;
95      }
96  
97      public void setDefaultContentCachingConfigurationName(String defaultContentCachingConfigurationName) {
98          this.defaultContentCachingConfigurationName = defaultContentCachingConfigurationName;
99      }
100 
101     @Override
102     public void init(FilterConfig filterConfig) throws ServletException {
103         super.init(filterConfig);
104         cacheModule.register(this);
105         // filters are started *after* modules - so we have to force a call onCacheModuleStart() here
106         onCacheModuleStart();
107     }
108 
109     @Override
110     public void onCacheModuleStart() {
111 
112         if (defaultContentCachingConfigurationName == null) {
113             log.warn("The {} property is not set for the {} CacheFilter, falling back to {}.", "defaultContentCachingConfigurationName", getName(), AbstractCacheModule.DEFAULT_CACHE_CONFIG);
114             this.defaultContentCachingConfigurationName = AbstractCacheModule.DEFAULT_CACHE_CONFIG;
115         }
116         this.contentCaching = cacheModule.getContentCaching(defaultContentCachingConfigurationName);
117         cache = cacheModule.getCacheFactory().getCache(contentCaching.getCacheName());
118 
119         if (contentCaching == null || cache == null) {
120             log.error("The " + getName() + " CacheFilter is not properly configured, either default contentCaching(" + contentCaching + ") or cache(" + cache + ") is null. Check if " + defaultContentCachingConfigurationName + " is a valid content caching configuration name. Will disable temporarily.");
121             setEnabled(false);
122         }
123     }
124 
125     protected Cache getCurrentPageCache() {
126         return cache;
127     }
128 
129     protected CacheModule getModule() {
130         return cacheModule;
131     }
132 
133     @Override
134     public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
135 
136         final CachePolicyResult cachePolicyResult;
137         final Cache cache = this.getCurrentPageCache();
138         int blockingTimeout = -1;
139         if (cache instanceof BlockingCache) {
140             blockingTimeout = ((BlockingCache) cache).getBlockingTimeout();
141         }
142         final ContentCachingConfiguration contentCachingConfiguration = cacheModule.getContentCaching(cache.getName());
143         try {
144             cachePolicyResult = contentCachingConfiguration.getCachePolicy().shouldCache(cache, webContextProvider.get().getAggregationState(), contentCachingConfiguration.getFlushPolicy());
145             cachePolicyResult.setCacheName(cache.getName());
146             cachePolicyResultProviderProvider.get().setCachePolicyResult(cachePolicyResult);
147         } catch (MgnlLockTimeoutException timeout) {
148             log.warn("The following URL was blocked for longer than {} seconds and has timed-out. The request has been blocked as another request is already processing the same resource. [url={}]", blockingTimeout / 1000, request.getRequestURL());
149             throw timeout;
150         }
151 
152         log.debug("Cache policy result: {}", cachePolicyResult);
153 
154         final CachePolicyResult.CachePolicyBehaviour behaviour = cachePolicyResult.getBehaviour();
155         monitor.logBehavior(behaviour.getName());
156         monitor.logAccess(cachePolicyResult.getCacheKey());
157         final CachePolicyExecutor executor = contentCachingConfiguration.getExecutor(behaviour);
158         if (executor == null) {
159             throw new IllegalStateException("Unexpected cache policy result: " + cachePolicyResult);
160         }
161 
162         try {
163             final long start = System.currentTimeMillis();
164             executor.processCacheRequest(request, response, chain, cache, cachePolicyResult);
165             final long end = System.currentTimeMillis();
166 
167             if (blockingTimeout != -1 && (end - start) >= blockingTimeout) {
168                 log.warn("The following URL took longer than {} seconds ({} ms) to render. This might cause timeout exceptions on other requests to the same URI. [url={}]", blockingTimeout / 1000, (end - start), request.getRequestURL());
169             }
170         } catch (Throwable th) {
171             if (cachePolicyResult.getBehaviour() == CachePolicyResult.store && cache instanceof BlockingCache) {
172                 log.error("A request started to cache but failed with an exception ({}). [url={}]", ExceptionUtils.getRootCauseMessage(th), request.getRequestURL());
173                 ((BlockingCache) cache).unlock(cachePolicyResult.getCacheKey());
174             }
175             if (th instanceof RuntimeException) { // no need to rewrap RuntimeException
176                 throw (RuntimeException) th;
177             }
178             throw new RuntimeException(th);
179         }
180     }
181 
182     @Override
183     public boolean bypasses(HttpServletRequest request) {
184         if (request.getAttribute(ServletUtil.ERROR_REQUEST_STATUS_CODE_ATTRIBUTE) != null) {
185             return true;
186         }
187         ServletResponse responseWrapper = webContextProvider.get().getResponse();
188         while (responseWrapper instanceof HttpServletResponseWrapper) {
189             if (responseWrapper instanceof CacheResponseWrapper && !(responseWrapper instanceof GZipFilter.GZipCacheResponseWrapper)) {
190                 return true;
191             } else {
192                 responseWrapper = ((HttpServletResponseWrapper) responseWrapper).getResponse();
193             }
194         }
195         return super.bypasses(request);
196     }
197 }