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