1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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
69
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
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) {
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 }