View Javadoc
1   /*
2    * Copyright (C) 2010, Google Inc.
3    * and other copyright owners as documented in the project's IP log.
4    *
5    * This program and the accompanying materials are made available
6    * under the terms of the Eclipse Distribution License v1.0 which
7    * accompanies this distribution, is reproduced below, and is
8    * available at http://www.eclipse.org/org/documents/edl-v10.php
9    *
10   * All rights reserved.
11   *
12   * Redistribution and use in source and binary forms, with or
13   * without modification, are permitted provided that the following
14   * conditions are met:
15   *
16   * - Redistributions of source code must retain the above copyright
17   *   notice, this list of conditions and the following disclaimer.
18   *
19   * - Redistributions in binary form must reproduce the above
20   *   copyright notice, this list of conditions and the following
21   *   disclaimer in the documentation and/or other materials provided
22   *   with the distribution.
23   *
24   * - Neither the name of the Eclipse Foundation, Inc. nor the
25   *   names of its contributors may be used to endorse or promote
26   *   products derived from this software without specific prior
27   *   written permission.
28   *
29   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
30   * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
31   * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
33   * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
34   * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
35   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
36   * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
37   * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
38   * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
39   * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
40   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
41   * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42   */
43  
44  package org.eclipse.jgit.internal.storage.pack;
45  
46  import java.io.EOFException;
47  import java.io.IOException;
48  import java.io.OutputStream;
49  import java.util.zip.Deflater;
50  
51  import org.eclipse.jgit.errors.IncorrectObjectTypeException;
52  import org.eclipse.jgit.errors.LargeObjectException;
53  import org.eclipse.jgit.errors.MissingObjectException;
54  import org.eclipse.jgit.lib.ObjectReader;
55  import org.eclipse.jgit.lib.ProgressMonitor;
56  import org.eclipse.jgit.storage.pack.PackConfig;
57  import org.eclipse.jgit.util.TemporaryBuffer;
58  
59  final class DeltaWindow {
60  	private static final boolean NEXT_RES = false;
61  	private static final boolean NEXT_SRC = true;
62  
63  	private final PackConfig config;
64  	private final DeltaCache deltaCache;
65  	private final ObjectReader reader;
66  	private final ProgressMonitor monitor;
67  	private final long bytesPerUnit;
68  	private long bytesProcessed;
69  
70  	/** Maximum number of bytes to admit to the window at once. */
71  	private final long maxMemory;
72  
73  	/** Maximum depth we should create for any delta chain. */
74  	private final int maxDepth;
75  
76  	private final ObjectToPack[] toSearch;
77  	private int cur;
78  	private int end;
79  
80  	/** Amount of memory we have loaded right now. */
81  	private long loaded;
82  
83  	// The object we are currently considering needs a lot of state:
84  
85  	/** Window entry of the object we are currently considering. */
86  	private DeltaWindowEntry res;
87  
88  	/** If we have chosen a base, the window entry it was created from. */
89  	private DeltaWindowEntry bestBase;
90  	private int deltaLen;
91  	private Object deltaBuf;
92  
93  	/** Used to compress cached deltas. */
94  	private Deflater deflater;
95  
96  	DeltaWindow(PackConfig pc, DeltaCache dc, ObjectReader or,
97  			ProgressMonitor pm, long bpu,
98  			ObjectToPack[] in, int beginIndex, int endIndex) {
99  		config = pc;
100 		deltaCache = dc;
101 		reader = or;
102 		monitor = pm;
103 		bytesPerUnit = bpu;
104 		toSearch = in;
105 		cur = beginIndex;
106 		end = endIndex;
107 
108 		maxMemory = Math.max(0, config.getDeltaSearchMemoryLimit());
109 		maxDepth = config.getMaxDeltaDepth();
110 		res = DeltaWindowEntry.createWindow(config.getDeltaSearchWindowSize());
111 	}
112 
113 	synchronized DeltaTask.Slice remaining() {
114 		int e = end;
115 		int halfRemaining = (e - cur) >>> 1;
116 		if (0 == halfRemaining)
117 			return null;
118 
119 		int split = e - halfRemaining;
120 		int h = toSearch[split].getPathHash();
121 
122 		// Attempt to split on the next path after the 50% split point.
123 		for (int n = split + 1; n < e; n++) {
124 			if (h != toSearch[n].getPathHash())
125 				return new DeltaTask.Slice(n, e);
126 		}
127 
128 		if (h != toSearch[cur].getPathHash()) {
129 			// Try to split on the path before the 50% split point.
130 			// Do not split the path currently being processed.
131 			for (int p = split - 1; cur < p; p--) {
132 				if (h != toSearch[p].getPathHash())
133 					return new DeltaTask.Slice(p + 1, e);
134 			}
135 		}
136 		return null;
137 	}
138 
139 	synchronized boolean tryStealWork(DeltaTask.Slice s) {
140 		if (s.beginIndex <= cur || end <= s.beginIndex)
141 			return false;
142 		end = s.beginIndex;
143 		return true;
144 	}
145 
146 	void search() throws IOException {
147 		try {
148 			for (;;) {
149 				ObjectToPack next;
150 				synchronized (this) {
151 					if (end <= cur)
152 						break;
153 					next = toSearch[cur++];
154 				}
155 				if (maxMemory != 0) {
156 					clear(res);
157 					final long need = estimateSize(next);
158 					DeltaWindowEntry n = res.next;
159 					for (; maxMemory < loaded + need && n != res; n = n.next)
160 						clear(n);
161 				}
162 				res.set(next);
163 
164 				if (res.object.isEdge() || res.object.doNotAttemptDelta()) {
165 					// We don't actually want to make a delta for
166 					// them, just need to push them into the window
167 					// so they can be read by other objects.
168 					keepInWindow();
169 				} else {
170 					// Search for a delta for the current window slot.
171 					if (bytesPerUnit <= (bytesProcessed += next.getWeight())) {
172 						int d = (int) (bytesProcessed / bytesPerUnit);
173 						monitor.update(d);
174 						bytesProcessed -= d * bytesPerUnit;
175 					}
176 					searchInWindow();
177 				}
178 			}
179 		} finally {
180 			if (deflater != null)
181 				deflater.end();
182 		}
183 	}
184 
185 	private static long estimateSize(ObjectToPack ent) {
186 		return DeltaIndex.estimateIndexSize(ent.getWeight());
187 	}
188 
189 	private static long estimateIndexSize(DeltaWindowEntry ent) {
190 		if (ent.buffer == null)
191 			return estimateSize(ent.object);
192 
193 		int len = ent.buffer.length;
194 		return DeltaIndex.estimateIndexSize(len) - len;
195 	}
196 
197 	private void clear(DeltaWindowEntry ent) {
198 		if (ent.index != null)
199 			loaded -= ent.index.getIndexSize();
200 		else if (ent.buffer != null)
201 			loaded -= ent.buffer.length;
202 		ent.set(null);
203 	}
204 
205 	private void searchInWindow() throws IOException {
206 		// Loop through the window backwards, considering every entry.
207 		// This lets us look at the bigger objects that came before.
208 		for (DeltaWindowEntry src = res.prev; src != res; src = src.prev) {
209 			if (src.empty())
210 				break;
211 			if (delta(src) /* == NEXT_SRC */)
212 				continue;
213 			bestBase = null;
214 			deltaBuf = null;
215 			return;
216 		}
217 
218 		// We couldn't find a suitable delta for this object, but it may
219 		// still be able to act as a base for another one.
220 		if (bestBase == null) {
221 			keepInWindow();
222 			return;
223 		}
224 
225 		// Select this best matching delta as the base for the object.
226 		//
227 		ObjectToPack srcObj = bestBase.object;
228 		ObjectToPack resObj = res.object;
229 		if (srcObj.isEdge()) {
230 			// The source (the delta base) is an edge object outside of the
231 			// pack. Its part of the common base set that the peer already
232 			// has on hand, so we don't want to send it. We have to store
233 			// an ObjectId and *NOT* an ObjectToPack for the base to ensure
234 			// the base isn't included in the outgoing pack file.
235 			resObj.setDeltaBase(srcObj.copy());
236 		} else {
237 			// The base is part of the pack we are sending, so it should be
238 			// a direct pointer to the base.
239 			resObj.setDeltaBase(srcObj);
240 		}
241 
242 		int depth = srcObj.getDeltaDepth() + 1;
243 		resObj.setDeltaDepth(depth);
244 		resObj.clearReuseAsIs();
245 		cacheDelta(srcObj, resObj);
246 
247 		if (depth < maxDepth) {
248 			// Reorder the window so that the best base will be tested
249 			// first for the next object, and the current object will
250 			// be the second candidate to consider before any others.
251 			res.makeNext(bestBase);
252 			res = bestBase.next;
253 		}
254 
255 		bestBase = null;
256 		deltaBuf = null;
257 	}
258 
259 	private boolean delta(final DeltaWindowEntry src)
260 			throws IOException {
261 		// Objects must use only the same type as their delta base.
262 		if (src.type() != res.type()) {
263 			keepInWindow();
264 			return NEXT_RES;
265 		}
266 
267 		// If the sizes are radically different, this is a bad pairing.
268 		if (res.size() < src.size() >>> 4)
269 			return NEXT_SRC;
270 
271 		int msz = deltaSizeLimit(src);
272 		if (msz <= 8) // Nearly impossible to fit useful delta.
273 			return NEXT_SRC;
274 
275 		// If we have to insert a lot to make this work, find another.
276 		if (res.size() - src.size() > msz)
277 			return NEXT_SRC;
278 
279 		DeltaIndex srcIndex;
280 		try {
281 			srcIndex = index(src);
282 		} catch (LargeObjectException tooBig) {
283 			// If the source is too big to work on, skip it.
284 			return NEXT_SRC;
285 		} catch (IOException notAvailable) {
286 			if (src.object.isEdge()) // Missing edges are OK.
287 				return NEXT_SRC;
288 			throw notAvailable;
289 		}
290 
291 		byte[] resBuf;
292 		try {
293 			resBuf = buffer(res);
294 		} catch (LargeObjectException tooBig) {
295 			// If its too big, move on to another item.
296 			return NEXT_RES;
297 		}
298 
299 		try {
300 			OutputStream delta = msz <= (8 << 10)
301 				? new ArrayStream(msz)
302 				: new TemporaryBuffer.Heap(msz);
303 			if (srcIndex.encode(delta, resBuf, msz))
304 				selectDeltaBase(src, delta);
305 		} catch (IOException deltaTooBig) {
306 			// Unlikely, encoder should see limit and return false.
307 		}
308 		return NEXT_SRC;
309 	}
310 
311 	private void selectDeltaBase(DeltaWindowEntry src, OutputStream delta) {
312 		bestBase = src;
313 
314 		if (delta instanceof ArrayStream) {
315 			ArrayStream a = (ArrayStream) delta;
316 			deltaBuf = a.buf;
317 			deltaLen = a.cnt;
318 		} else {
319 			TemporaryBuffer.Heap b = (TemporaryBuffer.Heap) delta;
320 			deltaBuf = b;
321 			deltaLen = (int) b.length();
322 		}
323 	}
324 
325 	private int deltaSizeLimit(DeltaWindowEntry src) {
326 		if (bestBase == null) {
327 			// Any delta should be no more than 50% of the original size
328 			// (for text files deflate of whole form should shrink 50%).
329 			int n = res.size() >>> 1;
330 
331 			// Evenly distribute delta size limits over allowed depth.
332 			// If src is non-delta (depth = 0), delta <= 50% of original.
333 			// If src is almost at limit (9/10), delta <= 10% of original.
334 			return n * (maxDepth - src.depth()) / maxDepth;
335 		}
336 
337 		// With a delta base chosen any new delta must be "better".
338 		// Retain the distribution described above.
339 		int d = bestBase.depth();
340 		int n = deltaLen;
341 
342 		// If src is whole (depth=0) and base is near limit (depth=9/10)
343 		// any delta using src can be 10x larger and still be better.
344 		//
345 		// If src is near limit (depth=9/10) and base is whole (depth=0)
346 		// a new delta dependent on src must be 1/10th the size.
347 		return n * (maxDepth - src.depth()) / (maxDepth - d);
348 	}
349 
350 	private void cacheDelta(ObjectToPack srcObj, ObjectToPack resObj) {
351 		if (deltaCache.canCache(deltaLen, srcObj, resObj)) {
352 			try {
353 				byte[] zbuf = new byte[deflateBound(deltaLen)];
354 				ZipStream zs = new ZipStream(deflater(), zbuf);
355 				if (deltaBuf instanceof byte[])
356 					zs.write((byte[]) deltaBuf, 0, deltaLen);
357 				else
358 					((TemporaryBuffer.Heap) deltaBuf).writeTo(zs, null);
359 				deltaBuf = null;
360 				int len = zs.finish();
361 
362 				resObj.setCachedDelta(deltaCache.cache(zbuf, len, deltaLen));
363 				resObj.setCachedSize(deltaLen);
364 			} catch (IOException err) {
365 				deltaCache.credit(deltaLen);
366 			} catch (OutOfMemoryError err) {
367 				deltaCache.credit(deltaLen);
368 			}
369 		}
370 	}
371 
372 	private static int deflateBound(int insz) {
373 		return insz + ((insz + 7) >> 3) + ((insz + 63) >> 6) + 11;
374 	}
375 
376 	private void keepInWindow() {
377 		res = res.next;
378 	}
379 
380 	private DeltaIndex index(DeltaWindowEntry ent)
381 			throws MissingObjectException, IncorrectObjectTypeException,
382 			IOException, LargeObjectException {
383 		DeltaIndex idx = ent.index;
384 		if (idx == null) {
385 			checkLoadable(ent, estimateIndexSize(ent));
386 
387 			try {
388 				idx = new DeltaIndex(buffer(ent));
389 			} catch (OutOfMemoryError noMemory) {
390 				LargeObjectException.OutOfMemory e;
391 				e = new LargeObjectException.OutOfMemory(noMemory);
392 				e.setObjectId(ent.object);
393 				throw e;
394 			}
395 			if (maxMemory != 0)
396 				loaded += idx.getIndexSize() - idx.getSourceSize();
397 			ent.index = idx;
398 		}
399 		return idx;
400 	}
401 
402 	private byte[] buffer(DeltaWindowEntry ent) throws MissingObjectException,
403 			IncorrectObjectTypeException, IOException, LargeObjectException {
404 		byte[] buf = ent.buffer;
405 		if (buf == null) {
406 			checkLoadable(ent, ent.size());
407 
408 			buf = PackWriter.buffer(config, reader, ent.object);
409 			if (maxMemory != 0)
410 				loaded += buf.length;
411 			ent.buffer = buf;
412 		}
413 		return buf;
414 	}
415 
416 	private void checkLoadable(DeltaWindowEntry ent, long need) {
417 		if (maxMemory == 0)
418 			return;
419 
420 		DeltaWindowEntry n = res.next;
421 		for (; maxMemory < loaded + need; n = n.next) {
422 			clear(n);
423 			if (n == ent)
424 				throw new LargeObjectException.ExceedsLimit(
425 						maxMemory, loaded + need);
426 		}
427 	}
428 
429 	private Deflater deflater() {
430 		if (deflater == null)
431 			deflater = new Deflater(config.getCompressionLevel());
432 		else
433 			deflater.reset();
434 		return deflater;
435 	}
436 
437 	static final class ZipStream extends OutputStream {
438 		private final Deflater deflater;
439 
440 		private final byte[] zbuf;
441 
442 		private int outPtr;
443 
444 		ZipStream(Deflater deflater, byte[] zbuf) {
445 			this.deflater = deflater;
446 			this.zbuf = zbuf;
447 		}
448 
449 		int finish() throws IOException {
450 			deflater.finish();
451 			for (;;) {
452 				if (outPtr == zbuf.length)
453 					throw new EOFException();
454 
455 				int n = deflater.deflate(zbuf, outPtr, zbuf.length - outPtr);
456 				if (n == 0) {
457 					if (deflater.finished())
458 						return outPtr;
459 					throw new IOException();
460 				}
461 				outPtr += n;
462 			}
463 		}
464 
465 		@Override
466 		public void write(byte[] b, int off, int len) throws IOException {
467 			deflater.setInput(b, off, len);
468 			for (;;) {
469 				if (outPtr == zbuf.length)
470 					throw new EOFException();
471 
472 				int n = deflater.deflate(zbuf, outPtr, zbuf.length - outPtr);
473 				if (n == 0) {
474 					if (deflater.needsInput())
475 						break;
476 					throw new IOException();
477 				}
478 				outPtr += n;
479 			}
480 		}
481 
482 		@Override
483 		public void write(int b) throws IOException {
484 			throw new UnsupportedOperationException();
485 		}
486 	}
487 
488 	static final class ArrayStream extends OutputStream {
489 		final byte[] buf;
490 		int cnt;
491 
492 		ArrayStream(int max) {
493 			buf = new byte[max];
494 		}
495 
496 		@Override
497 		public void write(int b) throws IOException {
498 			if (cnt == buf.length)
499 				throw new IOException();
500 			buf[cnt++] = (byte) b;
501 		}
502 
503 		@Override
504 		public void write(byte[] b, int off, int len) throws IOException {
505 			if (len > buf.length - cnt)
506 				throw new IOException();
507 			System.arraycopy(b, off, buf, cnt, len);
508 			cnt += len;
509 		}
510 	}
511 }