View Javadoc
1   /**
2    * This file Copyright (c) 2008-2015 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.OncePerRequestAbstractMgnlFilter;
38  import info.magnolia.context.MgnlContext;
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.exception.MgnlLockTimeoutException;
48  import info.magnolia.module.cache.mbean.CacheMonitor;
49  
50  import java.io.IOException;
51  
52  import javax.inject.Inject;
53  import javax.servlet.FilterChain;
54  import javax.servlet.FilterConfig;
55  import javax.servlet.ServletException;
56  import javax.servlet.http.HttpServletRequest;
57  import javax.servlet.http.HttpServletResponse;
58  
59  import org.apache.commons.lang3.exception.ExceptionUtils;
60  
61  /**
62   * Uses the CachePolicy to determine the cache behavior. Uses then the
63   * ContentCachingConfiguration to get the executors to be executed.
64   */
65  public class CacheFilter extends OncePerRequestAbstractMgnlFilter implements CacheModuleLifecycleListener {
66  
67      /**
68       * @deprecated since 5.4, use {@link AbstractCacheModule#DEFAULT_CACHE_CONFIG}.
69       */
70      @Deprecated
71      public static final String DEFAULT_CONTENT_CACHING_CONFIGURATION_NAME = "defaultPageCache";
72  
73      private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(CacheFilter.class);
74  
75      private final CacheModule cacheModule;
76      private final CacheMonitor monitor;
77      private String defaultContentCachingConfigurationName;
78      private Cache cache;
79      private ContentCachingConfiguration contentCaching;
80  
81      @Inject
82      public CacheFilter(CacheModule cacheModule, CacheMonitor cacheMonitor) {
83          this.cacheModule = cacheModule;
84          this.monitor = cacheMonitor;
85      }
86  
87      /**
88       * @deprecated since 5.4, use {@link #getDefaultContentCachingConfigurationName()}.
89       */
90      @Deprecated
91      public String getCacheConfigurationName() {
92          return getDefaultContentCachingConfigurationName();
93      }
94  
95      /**
96       * @deprecated since 5.4, use {@link #setDefaultContentCachingConfigurationName(String)}.
97       */
98      @Deprecated
99      public void setCacheConfigurationName(String cacheConfigurationName) {
100         setDefaultContentCachingConfigurationName(cacheConfigurationName);
101     }
102 
103     public String getDefaultContentCachingConfigurationName() {
104         return defaultContentCachingConfigurationName;
105     }
106 
107     public void setDefaultContentCachingConfigurationName(String defaultContentCachingConfigurationName) {
108         this.defaultContentCachingConfigurationName = defaultContentCachingConfigurationName;
109     }
110 
111     @Override
112     public void init(FilterConfig filterConfig) throws ServletException {
113         super.init(filterConfig);
114         cacheModule.register(this);
115         // filters are started *after* modules - so we have to force a call onCacheModuleStart() here
116         onCacheModuleStart();
117     }
118 
119     @Override
120     public void onCacheModuleStart() {
121 
122         if (defaultContentCachingConfigurationName == null) {
123             log.warn("The {} property is not set for the {} CacheFilter, falling back to {}.", "defaultContentCachingConfigurationName", getName(), AbstractCacheModule.DEFAULT_CACHE_CONFIG);
124             this.defaultContentCachingConfigurationName = AbstractCacheModule.DEFAULT_CACHE_CONFIG;
125         }
126         this.contentCaching = cacheModule.getContentCaching(defaultContentCachingConfigurationName);
127         cache = cacheModule.getCacheFactory().getCache(contentCaching.getCacheName());
128 
129         if (contentCaching == null || cache == null) {
130             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.");
131             setEnabled(false);
132         }
133     }
134 
135     protected Cache getCurrentPageCache() {
136         return cache;
137     }
138 
139     protected CacheModule getModule() {
140         return cacheModule;
141     }
142 
143     @Override
144     public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
145 
146         final AggregationState aggregationState = MgnlContext.getAggregationState();
147         final CachePolicyResult cachePolicyResult;
148         final Cache cache = this.getCurrentPageCache();
149         int blockingTimeout = -1;
150         if (cache instanceof BlockingCache) {
151             blockingTimeout = ((BlockingCache) cache).getBlockingTimeout();
152         }
153         final ContentCachingConfiguration contentCachingConfiguration = cacheModule.getContentCaching(cache.getName());
154         try {
155             cachePolicyResult = contentCachingConfiguration.getCachePolicy().shouldCache(cache, aggregationState, contentCachingConfiguration.getFlushPolicy());
156             CachePolicyResult.setCurrent(cachePolicyResult);
157         } catch (MgnlLockTimeoutException timeout) {
158             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());
159             throw timeout;
160         }
161 
162         log.debug("Cache policy result: {}", cachePolicyResult);
163 
164         final CachePolicyResult.CachePolicyBehaviour behaviour = cachePolicyResult.getBehaviour();
165         monitor.logBehavior(behaviour.getName());
166         monitor.logAccess(cachePolicyResult.getCacheKey());
167         final CachePolicyExecutor executor = contentCachingConfiguration.getExecutor(behaviour);
168         if (executor == null) {
169             throw new IllegalStateException("Unexpected cache policy result: " + cachePolicyResult);
170         }
171 
172         try {
173             final long start = System.currentTimeMillis();
174             executor.processCacheRequest(request, response, chain, cache, cachePolicyResult);
175             final long end = System.currentTimeMillis();
176 
177             if (blockingTimeout != -1 && (end - start) >= blockingTimeout) {
178                 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());
179             }
180         } catch (Throwable th) {
181             if (cachePolicyResult.getBehaviour() == CachePolicyResult.store && cache instanceof BlockingCache) {
182                 log.error("A request started to cache but failed with an exception ({}). [url={}]", ExceptionUtils.getRootCauseMessage(th), request.getRequestURL());
183                 ((BlockingCache) cache).unlock(cachePolicyResult.getCacheKey());
184             }
185             if (th instanceof RuntimeException) { // no need to rewrap RuntimeException
186                 throw (RuntimeException) th;
187             }
188             throw new RuntimeException(th);
189         }
190     }
191 }