View Javadoc
1   /**
2    * This file Copyright (c) 2009-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.imaging.caching;
35  
36  import info.magnolia.cms.beans.runtime.FileProperties;
37  import info.magnolia.cms.core.Content;
38  import info.magnolia.cms.core.HierarchyManager;
39  import info.magnolia.cms.core.NodeData;
40  import info.magnolia.cms.util.ContentUtil;
41  import info.magnolia.cms.util.NodeDataUtil;
42  import info.magnolia.context.MgnlContext;
43  import info.magnolia.imaging.ImageGenerator;
44  import info.magnolia.imaging.ImageStreamer;
45  import info.magnolia.imaging.ImagingException;
46  import info.magnolia.imaging.ParameterProvider;
47  
48  import java.io.ByteArrayInputStream;
49  import java.io.ByteArrayOutputStream;
50  import java.io.IOException;
51  import java.io.InputStream;
52  import java.io.OutputStream;
53  import java.util.Calendar;
54  import java.util.concurrent.ExecutionException;
55  import java.util.concurrent.TimeUnit;
56  import java.util.concurrent.locks.ReentrantLock;
57  
58  import javax.jcr.PropertyType;
59  import javax.jcr.RepositoryException;
60  
61  import org.apache.commons.io.IOUtils;
62  
63  import com.google.common.cache.CacheBuilder;
64  import com.google.common.cache.CacheLoader;
65  import com.google.common.cache.LoadingCache;
66  
67  /**
68   * An ImageStreamer which stores and serves generated images to/from a specific workspace.
69   *
70   * @param <P> type of ParameterProvider's parameter
71   */
72  
73  public class CachingImageStreamer<P> implements ImageStreamer<P> {
74      private static final String GENERATED_IMAGE_PROPERTY = "generated-image";
75  
76      private final HierarchyManager hm;
77      private final CachingStrategy<P> cachingStrategy;
78      private final ImageStreamer<P> delegate;
79  
80      /**
81       * This LoadingCache is the key to understanding how this class works.
82       * By using a LoadingCache, we are essentially locking all requests
83       * coming in for the same image (ImageGenerationJob) except the first one.
84       *
85       * CacheBuilder.build() returns a LoadingCache implemented as such that the
86       * first call to get(K) will generate the value (by calling <V> Function.apply(<K>).
87       * Further calls are blocked until the value is generated, and they all retrieve the same value.
88       *
89       * TODO: make static if we don't use the exact same instance for all threads ?
90       */
91      private final LoadingCache<ImageGenerationJob<P>, NodeData> currentJobs;
92  
93      /**
94       * Despite the currentJobs doing quite a good job at avoiding multiple requests
95       * for the same job, we still need to lock around JCR operations, otherwise multiple
96       * requests end up creating the same cachePath (or parts of it), thus yielding
97       * InvalidItemStateException: "Item cannot be saved because it has been modified externally".
98       * TODO - this is currently static because we *know* ImagingServlet uses a different instance
99       * of CachingImageStreamer for every request. This is not exactly the most elegant.
100      * TODO - see related TODO in currentJobs and info.magnolia.imaging.ImagingServlet#getStreamer
101      */
102     private static final ReentrantLock lock = new ReentrantLock();
103 
104     public CachingImageStreamer(HierarchyManager hm, CachingStrategy<P> cachingStrategy, ImageStreamer<P> delegate) {
105         this.hm = hm;
106         this.cachingStrategy = cachingStrategy;
107         this.delegate = delegate;
108 
109         CacheBuilder<Object, Object> cb = CacheBuilder.newBuilder();
110         this.currentJobs = cb
111                 // entries from the LoadingCache will be removed 500ms after their creation,
112                 // thus unblocking further requests for an equivalent job.
113                 .expireAfterWrite(500, TimeUnit.MILLISECONDS)
114 
115                 .build(new CacheLoader<ImageGenerationJob<P>, NodeData>() {
116 
117                     @Override
118                     public NodeData load(ImageGenerationJob<P> job) throws Exception {
119                         try {
120                             return generateAndStore(job.getGenerator(), job.getParams());
121                         } catch (IOException e) {
122                             // the LoadingCache will further wrap these in ExecutionExceptions, and we will, in turn, unwrap them ...
123                             throw new RuntimeException(e);
124                         } catch (ImagingException e) {
125                             // the LoadingCache will further wrap these in ExecutionExceptions, and we will, in turn, unwrap them ...
126                             throw new RuntimeException(e);
127                         }
128                     }
129 
130                 });
131     }
132 
133     @Override
134     public void serveImage(ImageGenerator<ParameterProvider<P>> generator, ParameterProvider<P> params, OutputStream out) throws IOException, ImagingException {
135         NodeData imgProp = fetchFromCache(generator, params);
136         if (imgProp == null) {
137             // image is not in cache or should be regenerated
138             try {
139                 imgProp = currentJobs.get(new ImageGenerationJob<P>(generator, params));
140             } catch (ExecutionException e) {
141                 // thrown if the LoadingCache's Function failed
142                 unwrapRuntimeException(e);
143             }
144         }
145         serve(imgProp, out);
146     }
147 
148     /**
149      * Gets the binary property (NodeData) for the appropriate image, ready to be served,
150      * or null if the image should be regenerated.
151      */
152     protected NodeData fetchFromCache(ImageGenerator<ParameterProvider<P>> generator, ParameterProvider<P> parameterProvider) {
153         final String cachePath = cachingStrategy.getCachePath(generator, parameterProvider);
154         if (cachePath == null) {
155             // the CachingStrategy decided it doesn't want us to cache :(
156             return null;
157         }
158         try {
159             if (!hm.isExist(cachePath)) {
160                 return null;
161             }
162             final Content imageNode = hm.getContent(cachePath);
163             final NodeData nodeData = imageNode.getNodeData(GENERATED_IMAGE_PROPERTY);
164             if (!nodeData.isExist()) {
165                 return null;
166             }
167             InputStream in = null;
168             try {
169                 in = nodeData.getStream();
170             } catch (Exception e) {
171                 // will happen, when stream is not yet stored properly (generateAndStore)
172                 // we prefer this handling over having to lock because of better performance especially with big images
173                 return null;
174             }
175             IOUtils.closeQuietly(in);
176 
177             if (cachingStrategy.shouldRegenerate(nodeData, parameterProvider)) {
178                 return null;
179             }
180             return nodeData;
181         } catch (RepositoryException e) {
182             throw new RuntimeException(e); // TODO
183         }
184     }
185 
186 
187     protected void serve(NodeData binary, OutputStream out) throws IOException {
188         final InputStream in = binary.getStream();
189         if (in == null) {
190             throw new IllegalStateException("Can't get InputStream from " + binary.getHandle());
191         }
192         IOUtils.copy(in, out);
193         IOUtils.closeQuietly(in);
194         IOUtils.closeQuietly(out);
195     }
196 
197     protected NodeData generateAndStore(final ImageGenerator<ParameterProvider<P>> generator, final ParameterProvider<P> parameterProvider) throws IOException, ImagingException {
198         // generate
199         final ByteArrayOutputStream tempOut = new ByteArrayOutputStream();
200         delegate.serveImage(generator, parameterProvider, tempOut);
201 
202         // it's time to lock now, we can only save one node at a time, since we'll be working on the same nodes as other threads
203         lock.lock();
204         try {
205             return MgnlContext.doInSystemContext(new MgnlContext.Op<NodeData, RepositoryException>() {
206                 @Override
207                 public NodeData exec() throws RepositoryException {
208                     HierarchyManager systemHM = MgnlContext.getHierarchyManager(hm.getName());
209                     // create cachePath if needed
210                     final String cachePath = cachingStrategy.getCachePath(generator, parameterProvider);
211                     final Content cacheNode = ContentUtil.createPath(systemHM, cachePath, false);
212                     final NodeData imageData = NodeDataUtil.getOrCreate(cacheNode, GENERATED_IMAGE_PROPERTY, PropertyType.BINARY);
213 
214                     // store generated image
215                     final ByteArrayInputStream tempIn = new ByteArrayInputStream(tempOut.toByteArray());
216                     imageData.setValue(tempIn);
217                     // TODO mimetype, lastmod, and other attributes ?
218                     imageData.setAttribute(FileProperties.PROPERTY_CONTENTTYPE, "image/" + generator.getOutputFormat(parameterProvider).getFormatName());
219                     imageData.setAttribute(FileProperties.PROPERTY_LASTMODIFIED, Calendar.getInstance());
220 
221                     // Update metadata of the cache *after* a succesfull image generation (creationDate has been set when creating
222                     // Since this might be called from a different thread than the actual request, we can't call cacheNode.updateMetaData(), which by default tries to set the authorId by using the current context
223                     cacheNode.getMetaData().setModificationDate();
224 
225                     // finally save it all
226                     systemHM.save();
227                     return imageData;
228                 }
229             });
230         } catch (RepositoryException e) {
231             throw new ImagingException("Can't store rendered image: " + e.getMessage(), e);
232         } finally {
233             lock.unlock();
234         }
235     }
236 
237     /**
238      * Unwrap ExecutionExceptions wrapping a RuntimeException wrapping an ImagingException or IOException,
239      * as thrown by the Function of the computing map.
240      *
241      * @see #currentJobs
242      */
243     private void unwrapRuntimeException(Exception e) throws ImagingException, IOException {
244         final Throwable cause = e.getCause();
245         if (cause instanceof ImagingException) {
246             throw (ImagingException) cause;
247         } else if (cause instanceof IOException) {
248             throw (IOException) cause;
249         } else if (cause instanceof RuntimeException) {
250             unwrapRuntimeException((RuntimeException) cause);
251         } else if (cause == null) {
252             // This really, really, should not happen... but we'll let this exception bubble up
253             throw new IllegalStateException("Unexpected and unhandled exception: " + (e.getMessage() != null ? e.getMessage() : ""), e);
254         } else {
255             // this shouldn't happen either, actually.
256             throw new ImagingException(e.getMessage(), cause);
257         }
258     }
259 }