View Javadoc
1   /**
2    * This file Copyright (c) 2008-2017 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.core.AggregationState;
37  import info.magnolia.cms.filters.AbstractMgnlFilter;
38  import info.magnolia.cms.util.ServletUtil;
39  import info.magnolia.context.WebContext;
40  import info.magnolia.module.cache.AbstractCacheModule;
41  import info.magnolia.module.cache.BlockingCache;
42  import info.magnolia.module.cache.Cache;
43  import info.magnolia.module.cache.CacheModule;
44  import info.magnolia.module.cache.CacheModuleLifecycleListener;
45  import info.magnolia.module.cache.CachePolicyExecutor;
46  import info.magnolia.module.cache.CachePolicyResult;
47  import info.magnolia.module.cache.ContentCachingConfiguration;
48  import info.magnolia.module.cache.cachepolicy.result.CachePolicyResultProvider;
49  import info.magnolia.module.cache.exception.MgnlLockTimeoutException;
50  import info.magnolia.module.cache.mbean.CacheMonitor;
51  import info.magnolia.objectfactory.Components;
52  
53  import java.io.IOException;
54  
55  import javax.inject.Inject;
56  import javax.inject.Provider;
57  import javax.servlet.FilterChain;
58  import javax.servlet.FilterConfig;
59  import javax.servlet.ServletException;
60  import javax.servlet.ServletResponse;
61  import javax.servlet.http.HttpServletRequest;
62  import javax.servlet.http.HttpServletResponse;
63  import javax.servlet.http.HttpServletResponseWrapper;
64  
65  import org.apache.commons.lang3.exception.ExceptionUtils;
66  import org.slf4j.Logger;
67  import org.slf4j.LoggerFactory;
68  
69  /**
70   * Uses the CachePolicy to determine the cache behavior. Uses then the
71   * ContentCachingConfiguration to get the executors to be executed.
72   */
73  public class CacheFilter extends AbstractMgnlFilter implements CacheModuleLifecycleListener {
74  
75      /**
76       * @deprecated since 5.4, use {@link AbstractCacheModule#DEFAULT_CACHE_CONFIG}.
77       */
78      @Deprecated
79      public static final String DEFAULT_CONTENT_CACHING_CONFIGURATION_NAME = AbstractCacheModule.DEFAULT_CACHE_CONFIG;
80  
81      private static final Logger log = LoggerFactory.getLogger(CacheFilter.class);
82  
83  
84      private String defaultContentCachingConfigurationName;
85      private Cache cache;
86      private ContentCachingConfiguration contentCaching;
87  
88      private final CacheModule cacheModule;
89      private final CacheMonitor monitor;
90      private final Provider<WebContext> webContextProvider;
91      private final Provider<CachePolicyResultProvider> cachePolicyResultProviderProvider;
92  
93      @Inject
94      public CacheFilter(Provider<WebContext> webContextProvider, CacheModule cacheModule, CacheMonitor cacheMonitor, Provider<CachePolicyResultProvider> cachePolicyResultProvider) {
95          this.cacheModule = cacheModule;
96          this.monitor = cacheMonitor;
97          this.webContextProvider = webContextProvider;
98          this.cachePolicyResultProviderProvider = cachePolicyResultProvider;
99      }
100 
101     /**
102      * @deprecated since 5.5. Use {@link #CacheFilter(Provider, CacheModule, CacheMonitor, Provider)} instead.
103      */
104     @Deprecated
105     public CacheFilter(CacheModule cacheModule, CacheMonitor cacheMonitor, Provider<AggregationState> aggregationStateProvider, Provider<CachePolicyResultProvider> cachePolicyResultProvider) {
106         this(new Provider<WebContext>() {
107             @Override
108             public WebContext get() {
109                 return Components.getComponent(WebContext.class);
110             }
111         }, cacheModule, cacheMonitor, cachePolicyResultProvider);
112     }
113 
114     /**
115      * @deprecated since 5.4.7. Use {@link #CacheFilter(Provider, CacheModule, CacheMonitor, Provider)} instead.
116      */
117     @Deprecated
118     public CacheFilter(CacheModule cacheModule, CacheMonitor cacheMonitor) {
119         this(new Provider<WebContext>() {
120                  @Override
121                  public WebContext get() {
122                      return Components.getComponent(WebContext.class);
123                  }
124              }, cacheModule, cacheMonitor, new Provider<CachePolicyResultProvider>() {
125                     @Override
126                     public CachePolicyResultProvider get() {
127                         return Components.getComponent(CachePolicyResultProvider.class);
128                     }
129                 }
130         );
131     }
132 
133     /**
134      * @deprecated since 5.4, use {@link #getDefaultContentCachingConfigurationName()}.
135      */
136     @Deprecated
137     public String getCacheConfigurationName() {
138         return getDefaultContentCachingConfigurationName();
139     }
140 
141     /**
142      * @deprecated since 5.4, use {@link #setDefaultContentCachingConfigurationName(String)}.
143      */
144     @Deprecated
145     public void setCacheConfigurationName(String cacheConfigurationName) {
146         setDefaultContentCachingConfigurationName(cacheConfigurationName);
147     }
148 
149     public String getDefaultContentCachingConfigurationName() {
150         return defaultContentCachingConfigurationName;
151     }
152 
153     public void setDefaultContentCachingConfigurationName(String defaultContentCachingConfigurationName) {
154         this.defaultContentCachingConfigurationName = defaultContentCachingConfigurationName;
155     }
156 
157     @Override
158     public void init(FilterConfig filterConfig) throws ServletException {
159         super.init(filterConfig);
160         cacheModule.register(this);
161         // filters are started *after* modules - so we have to force a call onCacheModuleStart() here
162         onCacheModuleStart();
163     }
164 
165     @Override
166     public void onCacheModuleStart() {
167 
168         if (defaultContentCachingConfigurationName == null) {
169             log.warn("The {} property is not set for the {} CacheFilter, falling back to {}.", "defaultContentCachingConfigurationName", getName(), AbstractCacheModule.DEFAULT_CACHE_CONFIG);
170             this.defaultContentCachingConfigurationName = AbstractCacheModule.DEFAULT_CACHE_CONFIG;
171         }
172         this.contentCaching = cacheModule.getContentCaching(defaultContentCachingConfigurationName);
173         cache = cacheModule.getCacheFactory().getCache(contentCaching.getCacheName());
174 
175         if (contentCaching == null || cache == null) {
176             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.");
177             setEnabled(false);
178         }
179     }
180 
181     protected Cache getCurrentPageCache() {
182         return cache;
183     }
184 
185     protected CacheModule getModule() {
186         return cacheModule;
187     }
188 
189     @Override
190     public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
191 
192         final CachePolicyResult cachePolicyResult;
193         final Cache cache = this.getCurrentPageCache();
194         int blockingTimeout = -1;
195         if (cache instanceof BlockingCache) {
196             blockingTimeout = ((BlockingCache) cache).getBlockingTimeout();
197         }
198         final ContentCachingConfiguration contentCachingConfiguration = cacheModule.getContentCaching(cache.getName());
199         try {
200             cachePolicyResult = contentCachingConfiguration.getCachePolicy().shouldCache(cache, webContextProvider.get().getAggregationState(), contentCachingConfiguration.getFlushPolicy());
201             cachePolicyResult.setCacheName(cache.getName());
202             cachePolicyResultProviderProvider.get().setCachePolicyResult(cachePolicyResult);
203         } catch (MgnlLockTimeoutException timeout) {
204             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());
205             throw timeout;
206         }
207 
208         log.debug("Cache policy result: {}", cachePolicyResult);
209 
210         final CachePolicyResult.CachePolicyBehaviour behaviour = cachePolicyResult.getBehaviour();
211         monitor.logBehavior(behaviour.getName());
212         monitor.logAccess(cachePolicyResult.getCacheKey());
213         final CachePolicyExecutor executor = contentCachingConfiguration.getExecutor(behaviour);
214         if (executor == null) {
215             throw new IllegalStateException("Unexpected cache policy result: " + cachePolicyResult);
216         }
217 
218         try {
219             final long start = System.currentTimeMillis();
220             executor.processCacheRequest(request, response, chain, cache, cachePolicyResult);
221             final long end = System.currentTimeMillis();
222 
223             if (blockingTimeout != -1 && (end - start) >= blockingTimeout) {
224                 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());
225             }
226         } catch (Throwable th) {
227             if (cachePolicyResult.getBehaviour() == CachePolicyResult.store && cache instanceof BlockingCache) {
228                 log.error("A request started to cache but failed with an exception ({}). [url={}]", ExceptionUtils.getRootCauseMessage(th), request.getRequestURL());
229                 ((BlockingCache) cache).unlock(cachePolicyResult.getCacheKey());
230             }
231             if (th instanceof RuntimeException) { // no need to rewrap RuntimeException
232                 throw (RuntimeException) th;
233             }
234             throw new RuntimeException(th);
235         }
236     }
237 
238     @Override
239     public boolean bypasses(HttpServletRequest request) {
240         if (request.getAttribute(ServletUtil.ERROR_REQUEST_STATUS_CODE_ATTRIBUTE) != null) {
241             return true;
242         }
243         ServletResponse responseWrapper = webContextProvider.get().getResponse();
244         while (responseWrapper instanceof HttpServletResponseWrapper) {
245             if (responseWrapper instanceof CacheResponseWrapper && !(responseWrapper instanceof GZipFilter.GZipCacheResponseWrapper)) {
246                 return true;
247             } else {
248                 responseWrapper = ((HttpServletResponseWrapper) responseWrapper).getResponse();
249             }
250         }
251         return super.bypasses(request);
252     }
253 }