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 				clearWindowOnTypeSwitch();
164 
165 				if (res.object.isEdge() || res.object.doNotAttemptDelta()) {
166 					// We don't actually want to make a delta for
167 					// them, just need to push them into the window
168 					// so they can be read by other objects.
169 					keepInWindow();
170 				} else {
171 					// Search for a delta for the current window slot.
172 					if (bytesPerUnit <= (bytesProcessed += next.getWeight())) {
173 						int d = (int) (bytesProcessed / bytesPerUnit);
174 						monitor.update(d);
175 						bytesProcessed -= d * bytesPerUnit;
176 					}
177 					searchInWindow();
178 				}
179 			}
180 		} finally {
181 			if (deflater != null)
182 				deflater.end();
183 		}
184 	}
185 
186 	private static long estimateSize(ObjectToPack ent) {
187 		return DeltaIndex.estimateIndexSize(ent.getWeight());
188 	}
189 
190 	private static long estimateIndexSize(DeltaWindowEntry ent) {
191 		if (ent.buffer == null)
192 			return estimateSize(ent.object);
193 
194 		int len = ent.buffer.length;
195 		return DeltaIndex.estimateIndexSize(len) - len;
196 	}
197 
198 	private void clearWindowOnTypeSwitch() {
199 		DeltaWindowEntry p = res.prev;
200 		if (!p.empty() && res.type() != p.type()) {
201 			for (; p != res; p = p.prev) {
202 				clear(p);
203 			}
204 		}
205 	}
206 
207 	private void clear(DeltaWindowEntry ent) {
208 		if (ent.index != null)
209 			loaded -= ent.index.getIndexSize();
210 		else if (ent.buffer != null)
211 			loaded -= ent.buffer.length;
212 		ent.set(null);
213 	}
214 
215 	private void searchInWindow() throws IOException {
216 		// Loop through the window backwards, considering every entry.
217 		// This lets us look at the bigger objects that came before.
218 		for (DeltaWindowEntry src = res.prev; src != res; src = src.prev) {
219 			if (src.empty())
220 				break;
221 			if (delta(src) /* == NEXT_SRC */)
222 				continue;
223 			bestBase = null;
224 			deltaBuf = null;
225 			return;
226 		}
227 
228 		// We couldn't find a suitable delta for this object, but it may
229 		// still be able to act as a base for another one.
230 		if (bestBase == null) {
231 			keepInWindow();
232 			return;
233 		}
234 
235 		// Select this best matching delta as the base for the object.
236 		//
237 		ObjectToPack srcObj = bestBase.object;
238 		ObjectToPack resObj = res.object;
239 		if (srcObj.isEdge()) {
240 			// The source (the delta base) is an edge object outside of the
241 			// pack. Its part of the common base set that the peer already
242 			// has on hand, so we don't want to send it. We have to store
243 			// an ObjectId and *NOT* an ObjectToPack for the base to ensure
244 			// the base isn't included in the outgoing pack file.
245 			resObj.setDeltaBase(srcObj.copy());
246 		} else {
247 			// The base is part of the pack we are sending, so it should be
248 			// a direct pointer to the base.
249 			resObj.setDeltaBase(srcObj);
250 		}
251 
252 		int depth = srcObj.getDeltaDepth() + 1;
253 		resObj.setDeltaDepth(depth);
254 		resObj.clearReuseAsIs();
255 		cacheDelta(srcObj, resObj);
256 
257 		if (depth < maxDepth) {
258 			// Reorder the window so that the best base will be tested
259 			// first for the next object, and the current object will
260 			// be the second candidate to consider before any others.
261 			res.makeNext(bestBase);
262 			res = bestBase.next;
263 		}
264 
265 		bestBase = null;
266 		deltaBuf = null;
267 	}
268 
269 	private boolean delta(DeltaWindowEntry src)
270 			throws IOException {
271 		// If the sizes are radically different, this is a bad pairing.
272 		if (res.size() < src.size() >>> 4)
273 			return NEXT_SRC;
274 
275 		int msz = deltaSizeLimit(src);
276 		if (msz <= 8) // Nearly impossible to fit useful delta.
277 			return NEXT_SRC;
278 
279 		// If we have to insert a lot to make this work, find another.
280 		if (res.size() - src.size() > msz)
281 			return NEXT_SRC;
282 
283 		DeltaIndex srcIndex;
284 		try {
285 			srcIndex = index(src);
286 		} catch (LargeObjectException tooBig) {
287 			// If the source is too big to work on, skip it.
288 			return NEXT_SRC;
289 		} catch (IOException notAvailable) {
290 			if (src.object.isEdge()) // Missing edges are OK.
291 				return NEXT_SRC;
292 			throw notAvailable;
293 		}
294 
295 		byte[] resBuf;
296 		try {
297 			resBuf = buffer(res);
298 		} catch (LargeObjectException tooBig) {
299 			// If its too big, move on to another item.
300 			return NEXT_RES;
301 		}
302 
303 		try {
304 			OutputStream delta = msz <= (8 << 10)
305 				? new ArrayStream(msz)
306 				: new TemporaryBuffer.Heap(msz);
307 			if (srcIndex.encode(delta, resBuf, msz))
308 				selectDeltaBase(src, delta);
309 		} catch (IOException deltaTooBig) {
310 			// Unlikely, encoder should see limit and return false.
311 		}
312 		return NEXT_SRC;
313 	}
314 
315 	private void selectDeltaBase(DeltaWindowEntry src, OutputStream delta) {
316 		bestBase = src;
317 
318 		if (delta instanceof ArrayStream) {
319 			ArrayStream a = (ArrayStream) delta;
320 			deltaBuf = a.buf;
321 			deltaLen = a.cnt;
322 		} else {
323 			TemporaryBuffer.Heap b = (TemporaryBuffer.Heap) delta;
324 			deltaBuf = b;
325 			deltaLen = (int) b.length();
326 		}
327 	}
328 
329 	private int deltaSizeLimit(DeltaWindowEntry src) {
330 		if (bestBase == null) {
331 			// Any delta should be no more than 50% of the original size
332 			// (for text files deflate of whole form should shrink 50%).
333 			int n = res.size() >>> 1;
334 
335 			// Evenly distribute delta size limits over allowed depth.
336 			// If src is non-delta (depth = 0), delta <= 50% of original.
337 			// If src is almost at limit (9/10), delta <= 10% of original.
338 			return n * (maxDepth - src.depth()) / maxDepth;
339 		}
340 
341 		// With a delta base chosen any new delta must be "better".
342 		// Retain the distribution described above.
343 		int d = bestBase.depth();
344 		int n = deltaLen;
345 
346 		// If src is whole (depth=0) and base is near limit (depth=9/10)
347 		// any delta using src can be 10x larger and still be better.
348 		//
349 		// If src is near limit (depth=9/10) and base is whole (depth=0)
350 		// a new delta dependent on src must be 1/10th the size.
351 		return n * (maxDepth - src.depth()) / (maxDepth - d);
352 	}
353 
354 	private void cacheDelta(ObjectToPack srcObj, ObjectToPack resObj) {
355 		if (deltaCache.canCache(deltaLen, srcObj, resObj)) {
356 			try {
357 				byte[] zbuf = new byte[deflateBound(deltaLen)];
358 				ZipStream zs = new ZipStream(deflater(), zbuf);
359 				if (deltaBuf instanceof byte[])
360 					zs.write((byte[]) deltaBuf, 0, deltaLen);
361 				else
362 					((TemporaryBuffer.Heap) deltaBuf).writeTo(zs, null);
363 				deltaBuf = null;
364 				int len = zs.finish();
365 
366 				resObj.setCachedDelta(deltaCache.cache(zbuf, len, deltaLen));
367 				resObj.setCachedSize(deltaLen);
368 			} catch (IOException err) {
369 				deltaCache.credit(deltaLen);
370 			} catch (OutOfMemoryError err) {
371 				deltaCache.credit(deltaLen);
372 			}
373 		}
374 	}
375 
376 	private static int deflateBound(int insz) {
377 		return insz + ((insz + 7) >> 3) + ((insz + 63) >> 6) + 11;
378 	}
379 
380 	private void keepInWindow() {
381 		res = res.next;
382 	}
383 
384 	private DeltaIndex index(DeltaWindowEntry ent)
385 			throws MissingObjectException, IncorrectObjectTypeException,
386 			IOException, LargeObjectException {
387 		DeltaIndex idx = ent.index;
388 		if (idx == null) {
389 			checkLoadable(ent, estimateIndexSize(ent));
390 
391 			try {
392 				idx = new DeltaIndex(buffer(ent));
393 			} catch (OutOfMemoryError noMemory) {
394 				LargeObjectException.OutOfMemory e;
395 				e = new LargeObjectException.OutOfMemory(noMemory);
396 				e.setObjectId(ent.object);
397 				throw e;
398 			}
399 			if (maxMemory != 0)
400 				loaded += idx.getIndexSize() - idx.getSourceSize();
401 			ent.index = idx;
402 		}
403 		return idx;
404 	}
405 
406 	private byte[] buffer(DeltaWindowEntry ent) throws MissingObjectException,
407 			IncorrectObjectTypeException, IOException, LargeObjectException {
408 		byte[] buf = ent.buffer;
409 		if (buf == null) {
410 			checkLoadable(ent, ent.size());
411 
412 			buf = PackWriter.buffer(config, reader, ent.object);
413 			if (maxMemory != 0)
414 				loaded += buf.length;
415 			ent.buffer = buf;
416 		}
417 		return buf;
418 	}
419 
420 	private void checkLoadable(DeltaWindowEntry ent, long need) {
421 		if (maxMemory == 0)
422 			return;
423 
424 		DeltaWindowEntry n = res.next;
425 		for (; maxMemory < loaded + need; n = n.next) {
426 			clear(n);
427 			if (n == ent)
428 				throw new LargeObjectException.ExceedsLimit(
429 						maxMemory, loaded + need);
430 		}
431 	}
432 
433 	private Deflater deflater() {
434 		if (deflater == null)
435 			deflater = new Deflater(config.getCompressionLevel());
436 		else
437 			deflater.reset();
438 		return deflater;
439 	}
440 
441 	static final class ZipStream extends OutputStream {
442 		private final Deflater deflater;
443 
444 		private final byte[] zbuf;
445 
446 		private int outPtr;
447 
448 		ZipStream(Deflater deflater, byte[] zbuf) {
449 			this.deflater = deflater;
450 			this.zbuf = zbuf;
451 		}
452 
453 		int finish() throws IOException {
454 			deflater.finish();
455 			for (;;) {
456 				if (outPtr == zbuf.length)
457 					throw new EOFException();
458 
459 				int n = deflater.deflate(zbuf, outPtr, zbuf.length - outPtr);
460 				if (n == 0) {
461 					if (deflater.finished())
462 						return outPtr;
463 					throw new IOException();
464 				}
465 				outPtr += n;
466 			}
467 		}
468 
469 		@Override
470 		public void write(byte[] b, int off, int len) throws IOException {
471 			deflater.setInput(b, off, len);
472 			for (;;) {
473 				if (outPtr == zbuf.length)
474 					throw new EOFException();
475 
476 				int n = deflater.deflate(zbuf, outPtr, zbuf.length - outPtr);
477 				if (n == 0) {
478 					if (deflater.needsInput())
479 						break;
480 					throw new IOException();
481 				}
482 				outPtr += n;
483 			}
484 		}
485 
486 		@Override
487 		public void write(int b) throws IOException {
488 			throw new UnsupportedOperationException();
489 		}
490 	}
491 
492 	static final class ArrayStream extends OutputStream {
493 		final byte[] buf;
494 		int cnt;
495 
496 		ArrayStream(int max) {
497 			buf = new byte[max];
498 		}
499 
500 		@Override
501 		public void write(int b) throws IOException {
502 			if (cnt == buf.length)
503 				throw new IOException();
504 			buf[cnt++] = (byte) b;
505 		}
506 
507 		@Override
508 		public void write(byte[] b, int off, int len) throws IOException {
509 			if (len > buf.length - cnt)
510 				throw new IOException();
511 			System.arraycopy(b, off, buf, cnt, len);
512 			cnt += len;
513 		}
514 	}
515 }