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.ehcache;
35  
36  import info.magnolia.cms.core.Path;
37  import info.magnolia.cms.util.DeprecationUtil;
38  import info.magnolia.cms.util.MBeanUtil;
39  import info.magnolia.init.MagnoliaInitPaths;
40  import info.magnolia.module.cache.Cache;
41  import info.magnolia.module.cache.CacheFactory;
42  import info.magnolia.module.cache.CacheModule;
43  import info.magnolia.module.cache.mbean.CacheMonitor;
44  import info.magnolia.objectfactory.Components;
45  
46  import java.util.Arrays;
47  import java.util.HashMap;
48  import java.util.List;
49  import java.util.Map;
50  
51  import javax.inject.Inject;
52  import javax.management.MBeanServer;
53  
54  import org.apache.commons.lang3.StringUtils;
55  
56  import net.sf.ehcache.CacheManager;
57  import net.sf.ehcache.Ehcache;
58  import net.sf.ehcache.config.Configuration;
59  import net.sf.ehcache.config.DiskStoreConfiguration;
60  import net.sf.ehcache.config.generator.ConfigurationSource;
61  import net.sf.ehcache.constructs.blocking.BlockingCache;
62  import net.sf.ehcache.management.ManagementService;
63  
64  /**
65   * A CacheFactory based on ehcache and which wraps BlockingCache instances.
66   */
67  public class EhCacheFactory implements CacheFactory {
68      private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(EhCacheFactory.class);
69  
70      private final CacheMonitor cacheMonitor;
71  
72      private CacheManager cacheManager;
73      private CacheModule cacheModule;
74      private MagnoliaInitPaths magnoliaInitPaths;
75      private Map<String, EhCacheConfiguration> caches = new HashMap<String, EhCacheConfiguration>();
76      private String diskStorePath;
77      // 0 == do not timeout ever, set to 10s by default.
78      private int blockingTimeout = 10000;
79  
80      @Inject
81      public EhCacheFactory(CacheMonitor cacheMonitor, CacheModule cacheModule, MagnoliaInitPaths magnoliaInitPaths) {
82          this.cacheMonitor = cacheMonitor;
83          this.cacheModule = cacheModule;
84          this.magnoliaInitPaths = magnoliaInitPaths;
85          diskStorePath = Path.getCacheDirectoryPath();
86      }
87  
88      /**
89       * @deprecated since 5.4. Use {@link #EhCacheFactory(info.magnolia.module.cache.mbean.CacheMonitor, info.magnolia.module.cache.CacheModule, info.magnolia.init.MagnoliaInitPaths)} instead.
90       */
91      public EhCacheFactory(CacheMonitor cacheMonitor) {
92          this(cacheMonitor, Components.getComponent(CacheModule.class), Components.getComponent(MagnoliaInitPaths.class));
93      }
94  
95      @Deprecated
96      public EhCacheConfiguration getDefaultCacheConfiguration() {
97          DeprecationUtil.isDeprecated("Code should not be calling info.magnolia.module.cache.ehcache.EhCacheFactory#getDefaultCacheConfiguration");
98          return getCaches().get(DEFAULT_CACHE_NAME);
99      }
100 
101     // There is no absolute guarantee that the caches Map will be populated before Node2Bean calls setDefaultCacheConfiguration(), but we know that's how it behaves (populates subnodes first)
102     @Deprecated
103     public void setDefaultCacheConfiguration(EhCacheConfiguration defaultCacheConfiguration) {
104         if (!isDefaultCacheName(defaultCacheConfiguration.getName())) {
105             log.warn("Calling setDefaultCacheConfiguration with a CacheConfiguration of name " + defaultCacheConfiguration.getName() + "; it should be unnamed.");
106         }
107         if (!getCaches().containsKey(DEFAULT_CACHE_NAME)) {
108             DeprecationUtil.isDeprecated("Configure your default cache settings under modules/cache/configuration/cacheFactory/caches/default rather than modules/cache/configuration/cacheFactory/defaultCacheConfiguration");
109             getCaches().put(DEFAULT_CACHE_NAME, defaultCacheConfiguration);
110         } else {
111             log.warn("You already have a configuration at modules/cache/configuration/cacheFactory/caches/default, ignoring modules/cache/configuration/cacheFactory/defaultCacheConfiguration");
112         }
113     }
114 
115     /**
116      * These are cache configurations. We call this method getCaches() to make it nicer to configure than if it was called getCacheConfigurations().
117      */
118     public Map<String, EhCacheConfiguration> getCaches() {
119         return caches;
120     }
121 
122     public void setCaches(Map<String, EhCacheConfiguration> caches) {
123         this.caches = caches;
124     }
125 
126     public String getDiskStorePath() {
127         return diskStorePath;
128     }
129 
130     public void setDiskStorePath(String diskStorePath) {
131         this.diskStorePath = diskStorePath;
132     }
133 
134     public int getBlockingTimeout() {
135         return blockingTimeout;
136     }
137 
138     public void setBlockingTimeout(int blockingTimeout) {
139         this.blockingTimeout = blockingTimeout;
140     }
141 
142     /**
143      * Caches currently known by the underlying CacheManager (which includes all configured caches as well as those created on-demand based on the default config).
144      */
145     @Override
146     public List getCacheNames() {
147         return Arrays.asList(cacheManager.getCacheNames());
148     }
149 
150     @Override
151     public Cache getCache(String name) {
152         if (isDefaultCacheName(name)) {
153             throw new IllegalArgumentException("'" + name + "' is not a valid cache name.");
154         }
155         Ehcache ehcache = cacheManager.getEhcache(name);
156 
157         // cacheManager will return null if there is no explicit cache configuration for this name
158         if (ehcache == null) {
159             // then we need to explicitly create/register it
160             createCache(name);
161             return getCache(name);
162         }
163         // cacheManager will return a non-wrapped instance of Ehcache if there is an explicit configuration with this name
164         // Recent versions of EhCache introduced a CacheDecoratorFactory, but that would imply configuring this for every cache, it forces an empty constructor and passes Properties around to the decorate() method. Not very elegant.
165         if (!(ehcache instanceof BlockingCache)) {
166             ehcache = decorateAndSubstitute(ehcache);
167         }
168         return wrap(name, ehcache);
169     }
170 
171     // Adds a cache to the cacheManager, which is somehow able to retrieve items previously stored
172     protected void createCache(String name) {
173         synchronized (this.getClass()) {
174             cacheManager.addCache(name);
175         }
176     }
177 
178     protected BlockingCache decorateAndSubstitute(Ehcache ehcache) {
179         synchronized (this.getClass()) {
180             BlockingCache newBlockingCache = new BlockingCache(ehcache);
181             newBlockingCache.setTimeoutMillis(getBlockingTimeout());
182             cacheManager.replaceCacheWithDecoratedCache(ehcache, newBlockingCache);
183             return newBlockingCache;
184         }
185     }
186 
187     protected EhCacheWrapper wrap(String name, Ehcache ehcache) {
188         return new EhCacheWrapper(cacheModule, ehcache, cacheMonitor, name);
189     }
190 
191     private boolean isDefaultCacheName(String name) {
192         return DEFAULT_CACHE_NAME.equals(name) || name == null;
193     }
194 
195     @Override
196     public void start(boolean isRestart) {
197         final Configuration cfg = new Configuration();
198 
199         // This methods gets called whenever the module's config changes, so this is fine - TODO we just need to double what happens with existing cache/cacheManager
200         for (EhCacheConfiguration cacheConfig : caches.values()) {
201             // skip "default", which is not an actual cache but just a "template" config.
202             if (!isDefaultCacheName(cacheConfig.getName())) {
203                 cfg.addCache(cacheConfig);
204             }
205         }
206 
207         EhCacheConfiguration defaultCacheConfiguration = caches.get(DEFAULT_CACHE_NAME);
208         if (defaultCacheConfiguration != null) {
209             // The defaultCacheConfiguration should not have a name (it has one here, as a side-effect of node2bean auto-calling the setName method with a node's name)
210             defaultCacheConfiguration.resetName();
211         } else {
212             log.warn("Default cache configuration is not set.");
213             defaultCacheConfiguration = new EhCacheConfiguration();
214             defaultCacheConfiguration.setMaxEntriesLocalHeap(10000);
215         }
216         cfg.setDefaultCacheConfiguration(defaultCacheConfiguration);
217 
218 
219         if (!caches.isEmpty()) {
220             cfg.setSource(new DescribingConfigurationSource("Magnolia-based cache configuration"));
221         }
222         if (diskStorePath != null) {
223             cfg.diskStore(new DiskStoreConfiguration().path(diskStorePath));
224             cfg.setSource(new DescribingConfigurationSource("Magnolia-based diskStorePath"));
225         }
226         cfg.setName(this.getCacheManagerIdentifier());
227         cacheManager = CacheManager.getCacheManager(cfg.getName());
228         if (cacheManager == null) { //module start
229             cacheManager = new CacheManager(cfg);
230             final MBeanServer mBeanServer = MBeanUtil.getMBeanServer();
231             ManagementService.registerMBeans(cacheManager, mBeanServer, true, true, true, true, false);
232         }
233     }
234 
235     private String getCacheManagerIdentifier() {
236         return StringUtils.removeStart(magnoliaInitPaths.getContextPath(), "/") + "#" + getClass().getName() + "#cacheManager";
237     }
238 
239     @Override
240     public void stop(boolean isRestart) {
241         if (!isRestart) {
242             cacheManager.shutdown();
243         }
244     }
245 
246     public CacheManager getWrappedCacheManager() {
247         return cacheManager;
248     }
249 
250     private static final class DescribingConfigurationSource extends ConfigurationSource {
251         private final String description;
252 
253         private DescribingConfigurationSource(String description) {
254             this.description = description;
255         }
256 
257         @Override
258         public Configuration createConfiguration() {
259             throw new IllegalStateException("not implemented - not needed");
260         }
261 
262         @Override
263         public String toString() {
264             return description;
265         }
266     }
267 }