Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  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. package org.eclipse.jgit.internal.storage.pack;
  44. import java.io.EOFException;
  45. import java.io.IOException;
  46. import java.io.OutputStream;
  47. import java.util.zip.Deflater;
  48. import org.eclipse.jgit.errors.IncorrectObjectTypeException;
  49. import org.eclipse.jgit.errors.LargeObjectException;
  50. import org.eclipse.jgit.errors.MissingObjectException;
  51. import org.eclipse.jgit.lib.ObjectReader;
  52. import org.eclipse.jgit.lib.ProgressMonitor;
  53. import org.eclipse.jgit.storage.pack.PackConfig;
  54. import org.eclipse.jgit.util.TemporaryBuffer;
  55. final class DeltaWindow {
  56. private static final boolean NEXT_RES = false;
  57. private static final boolean NEXT_SRC = true;
  58. private final PackConfig config;
  59. private final DeltaCache deltaCache;
  60. private final ObjectReader reader;
  61. private final ProgressMonitor monitor;
  62. private final long bytesPerUnit;
  63. private long bytesProcessed;
  64. /** Maximum number of bytes to admit to the window at once. */
  65. private final long maxMemory;
  66. /** Maximum depth we should create for any delta chain. */
  67. private final int maxDepth;
  68. private final ObjectToPack[] toSearch;
  69. private int cur;
  70. private int end;
  71. /** Amount of memory we have loaded right now. */
  72. private long loaded;
  73. // The object we are currently considering needs a lot of state:
  74. /** Window entry of the object we are currently considering. */
  75. private DeltaWindowEntry res;
  76. /** If we have chosen a base, the window entry it was created from. */
  77. private DeltaWindowEntry bestBase;
  78. private int deltaLen;
  79. private Object deltaBuf;
  80. /** Used to compress cached deltas. */
  81. private Deflater deflater;
  82. DeltaWindow(PackConfig pc, DeltaCache dc, ObjectReader or,
  83. ProgressMonitor pm, long bpu,
  84. ObjectToPack[] in, int beginIndex, int endIndex) {
  85. config = pc;
  86. deltaCache = dc;
  87. reader = or;
  88. monitor = pm;
  89. bytesPerUnit = bpu;
  90. toSearch = in;
  91. cur = beginIndex;
  92. end = endIndex;
  93. maxMemory = Math.max(0, config.getDeltaSearchMemoryLimit());
  94. maxDepth = config.getMaxDeltaDepth();
  95. res = DeltaWindowEntry.createWindow(config.getDeltaSearchWindowSize());
  96. }
  97. synchronized DeltaTask.Slice remaining() {
  98. int e = end;
  99. int halfRemaining = (e - cur) >>> 1;
  100. if (0 == halfRemaining)
  101. return null;
  102. int split = e - halfRemaining;
  103. int h = toSearch[split].getPathHash();
  104. // Attempt to split on the next path after the 50% split point.
  105. for (int n = split + 1; n < e; n++) {
  106. if (h != toSearch[n].getPathHash())
  107. return new DeltaTask.Slice(n, e);
  108. }
  109. if (h != toSearch[cur].getPathHash()) {
  110. // Try to split on the path before the 50% split point.
  111. // Do not split the path currently being processed.
  112. for (int p = split - 1; cur < p; p--) {
  113. if (h != toSearch[p].getPathHash())
  114. return new DeltaTask.Slice(p + 1, e);
  115. }
  116. }
  117. return null;
  118. }
  119. synchronized boolean tryStealWork(DeltaTask.Slice s) {
  120. if (s.beginIndex <= cur || end <= s.beginIndex)
  121. return false;
  122. end = s.beginIndex;
  123. return true;
  124. }
  125. void search() throws IOException {
  126. try {
  127. for (;;) {
  128. ObjectToPack next;
  129. synchronized (this) {
  130. if (end <= cur)
  131. break;
  132. next = toSearch[cur++];
  133. }
  134. if (maxMemory != 0) {
  135. clear(res);
  136. final long need = estimateSize(next);
  137. DeltaWindowEntry n = res.next;
  138. for (; maxMemory < loaded + need && n != res; n = n.next)
  139. clear(n);
  140. }
  141. res.set(next);
  142. if (res.object.isEdge() || res.object.doNotAttemptDelta()) {
  143. // We don't actually want to make a delta for
  144. // them, just need to push them into the window
  145. // so they can be read by other objects.
  146. keepInWindow();
  147. } else {
  148. // Search for a delta for the current window slot.
  149. if (bytesPerUnit <= (bytesProcessed += next.getWeight())) {
  150. int d = (int) (bytesProcessed / bytesPerUnit);
  151. monitor.update(d);
  152. bytesProcessed -= d * bytesPerUnit;
  153. }
  154. searchInWindow();
  155. }
  156. }
  157. } finally {
  158. if (deflater != null)
  159. deflater.end();
  160. }
  161. }
  162. private static long estimateSize(ObjectToPack ent) {
  163. return DeltaIndex.estimateIndexSize(ent.getWeight());
  164. }
  165. private static long estimateIndexSize(DeltaWindowEntry ent) {
  166. if (ent.buffer == null)
  167. return estimateSize(ent.object);
  168. int len = ent.buffer.length;
  169. return DeltaIndex.estimateIndexSize(len) - len;
  170. }
  171. private void clear(DeltaWindowEntry ent) {
  172. if (ent.index != null)
  173. loaded -= ent.index.getIndexSize();
  174. else if (ent.buffer != null)
  175. loaded -= ent.buffer.length;
  176. ent.set(null);
  177. }
  178. private void searchInWindow() throws IOException {
  179. // Loop through the window backwards, considering every entry.
  180. // This lets us look at the bigger objects that came before.
  181. for (DeltaWindowEntry src = res.prev; src != res; src = src.prev) {
  182. if (src.empty())
  183. break;
  184. if (delta(src) /* == NEXT_SRC */)
  185. continue;
  186. bestBase = null;
  187. deltaBuf = null;
  188. return;
  189. }
  190. // We couldn't find a suitable delta for this object, but it may
  191. // still be able to act as a base for another one.
  192. if (bestBase == null) {
  193. keepInWindow();
  194. return;
  195. }
  196. // Select this best matching delta as the base for the object.
  197. //
  198. ObjectToPack srcObj = bestBase.object;
  199. ObjectToPack resObj = res.object;
  200. if (srcObj.isEdge()) {
  201. // The source (the delta base) is an edge object outside of the
  202. // pack. Its part of the common base set that the peer already
  203. // has on hand, so we don't want to send it. We have to store
  204. // an ObjectId and *NOT* an ObjectToPack for the base to ensure
  205. // the base isn't included in the outgoing pack file.
  206. resObj.setDeltaBase(srcObj.copy());
  207. } else {
  208. // The base is part of the pack we are sending, so it should be
  209. // a direct pointer to the base.
  210. resObj.setDeltaBase(srcObj);
  211. }
  212. int depth = srcObj.getDeltaDepth() + 1;
  213. resObj.setDeltaDepth(depth);
  214. resObj.clearReuseAsIs();
  215. cacheDelta(srcObj, resObj);
  216. if (depth < maxDepth) {
  217. // Reorder the window so that the best base will be tested
  218. // first for the next object, and the current object will
  219. // be the second candidate to consider before any others.
  220. res.makeNext(bestBase);
  221. res = bestBase.next;
  222. }
  223. bestBase = null;
  224. deltaBuf = null;
  225. }
  226. private boolean delta(final DeltaWindowEntry src)
  227. throws IOException {
  228. // Objects must use only the same type as their delta base.
  229. if (src.type() != res.type()) {
  230. keepInWindow();
  231. return NEXT_RES;
  232. }
  233. // If the sizes are radically different, this is a bad pairing.
  234. if (res.size() < src.size() >>> 4)
  235. return NEXT_SRC;
  236. int msz = deltaSizeLimit(src);
  237. if (msz <= 8) // Nearly impossible to fit useful delta.
  238. return NEXT_SRC;
  239. // If we have to insert a lot to make this work, find another.
  240. if (res.size() - src.size() > msz)
  241. return NEXT_SRC;
  242. DeltaIndex srcIndex;
  243. try {
  244. srcIndex = index(src);
  245. } catch (LargeObjectException tooBig) {
  246. // If the source is too big to work on, skip it.
  247. return NEXT_SRC;
  248. } catch (IOException notAvailable) {
  249. if (src.object.isEdge()) // Missing edges are OK.
  250. return NEXT_SRC;
  251. throw notAvailable;
  252. }
  253. byte[] resBuf;
  254. try {
  255. resBuf = buffer(res);
  256. } catch (LargeObjectException tooBig) {
  257. // If its too big, move on to another item.
  258. return NEXT_RES;
  259. }
  260. try {
  261. OutputStream delta = msz <= (8 << 10)
  262. ? new ArrayStream(msz)
  263. : new TemporaryBuffer.Heap(msz);
  264. if (srcIndex.encode(delta, resBuf, msz))
  265. selectDeltaBase(src, delta);
  266. } catch (IOException deltaTooBig) {
  267. // Unlikely, encoder should see limit and return false.
  268. }
  269. return NEXT_SRC;
  270. }
  271. private void selectDeltaBase(DeltaWindowEntry src, OutputStream delta) {
  272. bestBase = src;
  273. if (delta instanceof ArrayStream) {
  274. ArrayStream a = (ArrayStream) delta;
  275. deltaBuf = a.buf;
  276. deltaLen = a.cnt;
  277. } else {
  278. TemporaryBuffer.Heap b = (TemporaryBuffer.Heap) delta;
  279. deltaBuf = b;
  280. deltaLen = (int) b.length();
  281. }
  282. }
  283. private int deltaSizeLimit(DeltaWindowEntry src) {
  284. if (bestBase == null) {
  285. // Any delta should be no more than 50% of the original size
  286. // (for text files deflate of whole form should shrink 50%).
  287. int n = res.size() >>> 1;
  288. // Evenly distribute delta size limits over allowed depth.
  289. // If src is non-delta (depth = 0), delta <= 50% of original.
  290. // If src is almost at limit (9/10), delta <= 10% of original.
  291. return n * (maxDepth - src.depth()) / maxDepth;
  292. }
  293. // With a delta base chosen any new delta must be "better".
  294. // Retain the distribution described above.
  295. int d = bestBase.depth();
  296. int n = deltaLen;
  297. // If src is whole (depth=0) and base is near limit (depth=9/10)
  298. // any delta using src can be 10x larger and still be better.
  299. //
  300. // If src is near limit (depth=9/10) and base is whole (depth=0)
  301. // a new delta dependent on src must be 1/10th the size.
  302. return n * (maxDepth - src.depth()) / (maxDepth - d);
  303. }
  304. private void cacheDelta(ObjectToPack srcObj, ObjectToPack resObj) {
  305. if (deltaCache.canCache(deltaLen, srcObj, resObj)) {
  306. try {
  307. byte[] zbuf = new byte[deflateBound(deltaLen)];
  308. ZipStream zs = new ZipStream(deflater(), zbuf);
  309. if (deltaBuf instanceof byte[])
  310. zs.write((byte[]) deltaBuf, 0, deltaLen);
  311. else
  312. ((TemporaryBuffer.Heap) deltaBuf).writeTo(zs, null);
  313. deltaBuf = null;
  314. int len = zs.finish();
  315. resObj.setCachedDelta(deltaCache.cache(zbuf, len, deltaLen));
  316. resObj.setCachedSize(deltaLen);
  317. } catch (IOException err) {
  318. deltaCache.credit(deltaLen);
  319. } catch (OutOfMemoryError err) {
  320. deltaCache.credit(deltaLen);
  321. }
  322. }
  323. }
  324. private static int deflateBound(int insz) {
  325. return insz + ((insz + 7) >> 3) + ((insz + 63) >> 6) + 11;
  326. }
  327. private void keepInWindow() {
  328. res = res.next;
  329. }
  330. private DeltaIndex index(DeltaWindowEntry ent)
  331. throws MissingObjectException, IncorrectObjectTypeException,
  332. IOException, LargeObjectException {
  333. DeltaIndex idx = ent.index;
  334. if (idx == null) {
  335. checkLoadable(ent, estimateIndexSize(ent));
  336. try {
  337. idx = new DeltaIndex(buffer(ent));
  338. } catch (OutOfMemoryError noMemory) {
  339. LargeObjectException.OutOfMemory e;
  340. e = new LargeObjectException.OutOfMemory(noMemory);
  341. e.setObjectId(ent.object);
  342. throw e;
  343. }
  344. if (maxMemory != 0)
  345. loaded += idx.getIndexSize() - idx.getSourceSize();
  346. ent.index = idx;
  347. }
  348. return idx;
  349. }
  350. private byte[] buffer(DeltaWindowEntry ent) throws MissingObjectException,
  351. IncorrectObjectTypeException, IOException, LargeObjectException {
  352. byte[] buf = ent.buffer;
  353. if (buf == null) {
  354. checkLoadable(ent, ent.size());
  355. buf = PackWriter.buffer(config, reader, ent.object);
  356. if (maxMemory != 0)
  357. loaded += buf.length;
  358. ent.buffer = buf;
  359. }
  360. return buf;
  361. }
  362. private void checkLoadable(DeltaWindowEntry ent, long need) {
  363. if (maxMemory == 0)
  364. return;
  365. DeltaWindowEntry n = res.next;
  366. for (; maxMemory < loaded + need; n = n.next) {
  367. clear(n);
  368. if (n == ent)
  369. throw new LargeObjectException.ExceedsLimit(
  370. maxMemory, loaded + need);
  371. }
  372. }
  373. private Deflater deflater() {
  374. if (deflater == null)
  375. deflater = new Deflater(config.getCompressionLevel());
  376. else
  377. deflater.reset();
  378. return deflater;
  379. }
  380. static final class ZipStream extends OutputStream {
  381. private final Deflater deflater;
  382. private final byte[] zbuf;
  383. private int outPtr;
  384. ZipStream(Deflater deflater, byte[] zbuf) {
  385. this.deflater = deflater;
  386. this.zbuf = zbuf;
  387. }
  388. int finish() throws IOException {
  389. deflater.finish();
  390. for (;;) {
  391. if (outPtr == zbuf.length)
  392. throw new EOFException();
  393. int n = deflater.deflate(zbuf, outPtr, zbuf.length - outPtr);
  394. if (n == 0) {
  395. if (deflater.finished())
  396. return outPtr;
  397. throw new IOException();
  398. }
  399. outPtr += n;
  400. }
  401. }
  402. @Override
  403. public void write(byte[] b, int off, int len) throws IOException {
  404. deflater.setInput(b, off, len);
  405. for (;;) {
  406. if (outPtr == zbuf.length)
  407. throw new EOFException();
  408. int n = deflater.deflate(zbuf, outPtr, zbuf.length - outPtr);
  409. if (n == 0) {
  410. if (deflater.needsInput())
  411. break;
  412. throw new IOException();
  413. }
  414. outPtr += n;
  415. }
  416. }
  417. @Override
  418. public void write(int b) throws IOException {
  419. throw new UnsupportedOperationException();
  420. }
  421. }
  422. static final class ArrayStream extends OutputStream {
  423. final byte[] buf;
  424. int cnt;
  425. ArrayStream(int max) {
  426. buf = new byte[max];
  427. }
  428. @Override
  429. public void write(int b) throws IOException {
  430. if (cnt == buf.length)
  431. throw new IOException();
  432. buf[cnt++] = (byte) b;
  433. }
  434. @Override
  435. public void write(byte[] b, int off, int len) throws IOException {
  436. if (len > buf.length - cnt)
  437. throw new IOException();
  438. System.arraycopy(b, off, buf, cnt, len);
  439. cnt += len;
  440. }
  441. }
  442. }