You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ObjectDirectoryPackParser.java 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  1. /*
  2. * Copyright (C) 2008-2011, Google Inc.
  3. * Copyright (C) 2007-2008, Robin Rosenberg <robin.rosenberg@dewire.com>
  4. * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org>
  5. * and other copyright owners as documented in the project's IP log.
  6. *
  7. * This program and the accompanying materials are made available
  8. * under the terms of the Eclipse Distribution License v1.0 which
  9. * accompanies this distribution, is reproduced below, and is
  10. * available at http://www.eclipse.org/org/documents/edl-v10.php
  11. *
  12. * All rights reserved.
  13. *
  14. * Redistribution and use in source and binary forms, with or
  15. * without modification, are permitted provided that the following
  16. * conditions are met:
  17. *
  18. * - Redistributions of source code must retain the above copyright
  19. * notice, this list of conditions and the following disclaimer.
  20. *
  21. * - Redistributions in binary form must reproduce the above
  22. * copyright notice, this list of conditions and the following
  23. * disclaimer in the documentation and/or other materials provided
  24. * with the distribution.
  25. *
  26. * - Neither the name of the Eclipse Foundation, Inc. nor the
  27. * names of its contributors may be used to endorse or promote
  28. * products derived from this software without specific prior
  29. * written permission.
  30. *
  31. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  32. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  33. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  34. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  35. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  36. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  37. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  38. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  39. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  40. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  41. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  42. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  43. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  44. */
  45. package org.eclipse.jgit.internal.storage.file;
  46. import java.io.File;
  47. import java.io.FileOutputStream;
  48. import java.io.IOException;
  49. import java.io.InputStream;
  50. import java.io.RandomAccessFile;
  51. import java.nio.file.StandardCopyOption;
  52. import java.security.MessageDigest;
  53. import java.text.MessageFormat;
  54. import java.util.Arrays;
  55. import java.util.List;
  56. import java.util.zip.CRC32;
  57. import java.util.zip.Deflater;
  58. import org.eclipse.jgit.errors.LockFailedException;
  59. import org.eclipse.jgit.internal.JGitText;
  60. import org.eclipse.jgit.lib.AnyObjectId;
  61. import org.eclipse.jgit.lib.Constants;
  62. import org.eclipse.jgit.lib.CoreConfig;
  63. import org.eclipse.jgit.lib.ObjectId;
  64. import org.eclipse.jgit.lib.ProgressMonitor;
  65. import org.eclipse.jgit.transport.PackParser;
  66. import org.eclipse.jgit.transport.PackedObjectInfo;
  67. import org.eclipse.jgit.util.FileUtils;
  68. import org.eclipse.jgit.util.NB;
  69. /**
  70. * Consumes a pack stream and stores as a pack file in
  71. * {@link org.eclipse.jgit.internal.storage.file.ObjectDirectory}.
  72. * <p>
  73. * To obtain an instance of a parser, applications should use
  74. * {@link org.eclipse.jgit.lib.ObjectInserter#newPackParser(InputStream)}.
  75. */
  76. public class ObjectDirectoryPackParser extends PackParser {
  77. private final FileObjectDatabase db;
  78. /** CRC-32 computation for objects that are appended onto the pack. */
  79. private final CRC32 crc;
  80. /** Running SHA-1 of any base objects appended after {@link #origEnd}. */
  81. private final MessageDigest tailDigest;
  82. /** Preferred format version of the pack-*.idx file to generate. */
  83. private int indexVersion;
  84. /** If true, pack with 0 objects will be stored. Usually these are deleted. */
  85. private boolean keepEmpty;
  86. /** Path of the temporary file holding the pack data. */
  87. private File tmpPack;
  88. /**
  89. * Path of the index created for the pack, to find objects quickly at read
  90. * time.
  91. */
  92. private File tmpIdx;
  93. /** Read/write handle to {@link #tmpPack} while it is being parsed. */
  94. private RandomAccessFile out;
  95. /** Length of the original pack stream, before missing bases were appended. */
  96. private long origEnd;
  97. /** The original checksum of data up to {@link #origEnd}. */
  98. private byte[] origHash;
  99. /** Current end of the pack file. */
  100. private long packEnd;
  101. /** Checksum of the entire pack file. */
  102. private byte[] packHash;
  103. /** Compresses delta bases when completing a thin pack. */
  104. private Deflater def;
  105. /** The pack that was created, if parsing was successful. */
  106. private PackFile newPack;
  107. ObjectDirectoryPackParser(FileObjectDatabase odb, InputStream src) {
  108. super(odb, src);
  109. this.db = odb;
  110. this.crc = new CRC32();
  111. this.tailDigest = Constants.newMessageDigest();
  112. indexVersion = db.getConfig().get(CoreConfig.KEY).getPackIndexVersion();
  113. }
  114. /**
  115. * Set the pack index file format version this instance will create.
  116. *
  117. * @param version
  118. * the version to write. The special version 0 designates the
  119. * oldest (most compatible) format available for the objects.
  120. * @see PackIndexWriter
  121. */
  122. public void setIndexVersion(int version) {
  123. indexVersion = version;
  124. }
  125. /**
  126. * Configure this index pack instance to keep an empty pack.
  127. * <p>
  128. * By default an empty pack (a pack with no objects) is not kept, as doi so
  129. * is completely pointless. With no objects in the pack there is no d stored
  130. * by it, so the pack is unnecessary.
  131. *
  132. * @param empty
  133. * true to enable keeping an empty pack.
  134. */
  135. public void setKeepEmpty(final boolean empty) {
  136. keepEmpty = empty;
  137. }
  138. /**
  139. * Get the imported {@link org.eclipse.jgit.internal.storage.file.PackFile}.
  140. * <p>
  141. * This method is supplied only to support testing; applications shouldn't
  142. * be using it directly to access the imported data.
  143. *
  144. * @return the imported PackFile, if parsing was successful.
  145. */
  146. public PackFile getPackFile() {
  147. return newPack;
  148. }
  149. /** {@inheritDoc} */
  150. @Override
  151. public long getPackSize() {
  152. if (newPack == null)
  153. return super.getPackSize();
  154. File pack = newPack.getPackFile();
  155. long size = pack.length();
  156. String p = pack.getAbsolutePath();
  157. String i = p.substring(0, p.length() - ".pack".length()) + ".idx"; //$NON-NLS-1$ //$NON-NLS-2$
  158. File idx = new File(i);
  159. if (idx.exists() && idx.isFile())
  160. size += idx.length();
  161. return size;
  162. }
  163. /** {@inheritDoc} */
  164. @Override
  165. public PackLock parse(ProgressMonitor receiving, ProgressMonitor resolving)
  166. throws IOException {
  167. tmpPack = File.createTempFile("incoming_", ".pack", db.getDirectory()); //$NON-NLS-1$ //$NON-NLS-2$
  168. tmpIdx = new File(db.getDirectory(), baseName(tmpPack) + ".idx"); //$NON-NLS-1$
  169. try {
  170. out = new RandomAccessFile(tmpPack, "rw"); //$NON-NLS-1$
  171. super.parse(receiving, resolving);
  172. out.seek(packEnd);
  173. out.write(packHash);
  174. out.getChannel().force(true);
  175. out.close();
  176. writeIdx();
  177. tmpPack.setReadOnly();
  178. tmpIdx.setReadOnly();
  179. return renameAndOpenPack(getLockMessage());
  180. } finally {
  181. if (def != null)
  182. def.end();
  183. try {
  184. if (out != null && out.getChannel().isOpen())
  185. out.close();
  186. } catch (IOException closeError) {
  187. // Ignored. We want to delete the file.
  188. }
  189. cleanupTemporaryFiles();
  190. }
  191. }
  192. /** {@inheritDoc} */
  193. @Override
  194. protected void onPackHeader(long objectCount) throws IOException {
  195. // Ignored, the count is not required.
  196. }
  197. /** {@inheritDoc} */
  198. @Override
  199. protected void onBeginWholeObject(long streamPosition, int type,
  200. long inflatedSize) throws IOException {
  201. crc.reset();
  202. }
  203. /** {@inheritDoc} */
  204. @Override
  205. protected void onEndWholeObject(PackedObjectInfo info) throws IOException {
  206. info.setCRC((int) crc.getValue());
  207. }
  208. /** {@inheritDoc} */
  209. @Override
  210. protected void onBeginOfsDelta(long streamPosition,
  211. long baseStreamPosition, long inflatedSize) throws IOException {
  212. crc.reset();
  213. }
  214. /** {@inheritDoc} */
  215. @Override
  216. protected void onBeginRefDelta(long streamPosition, AnyObjectId baseId,
  217. long inflatedSize) throws IOException {
  218. crc.reset();
  219. }
  220. /** {@inheritDoc} */
  221. @Override
  222. protected UnresolvedDelta onEndDelta() throws IOException {
  223. UnresolvedDelta delta = new UnresolvedDelta();
  224. delta.setCRC((int) crc.getValue());
  225. return delta;
  226. }
  227. /** {@inheritDoc} */
  228. @Override
  229. protected void onInflatedObjectData(PackedObjectInfo obj, int typeCode,
  230. byte[] data) throws IOException {
  231. // ObjectDirectory ignores this event.
  232. }
  233. /** {@inheritDoc} */
  234. @Override
  235. protected void onObjectHeader(Source src, byte[] raw, int pos, int len)
  236. throws IOException {
  237. crc.update(raw, pos, len);
  238. }
  239. /** {@inheritDoc} */
  240. @Override
  241. protected void onObjectData(Source src, byte[] raw, int pos, int len)
  242. throws IOException {
  243. crc.update(raw, pos, len);
  244. }
  245. /** {@inheritDoc} */
  246. @Override
  247. protected void onStoreStream(byte[] raw, int pos, int len)
  248. throws IOException {
  249. out.write(raw, pos, len);
  250. }
  251. /** {@inheritDoc} */
  252. @Override
  253. protected void onPackFooter(byte[] hash) throws IOException {
  254. packEnd = out.getFilePointer();
  255. origEnd = packEnd;
  256. origHash = hash;
  257. packHash = hash;
  258. }
  259. /** {@inheritDoc} */
  260. @Override
  261. protected ObjectTypeAndSize seekDatabase(UnresolvedDelta delta,
  262. ObjectTypeAndSize info) throws IOException {
  263. out.seek(delta.getOffset());
  264. crc.reset();
  265. return readObjectHeader(info);
  266. }
  267. /** {@inheritDoc} */
  268. @Override
  269. protected ObjectTypeAndSize seekDatabase(PackedObjectInfo obj,
  270. ObjectTypeAndSize info) throws IOException {
  271. out.seek(obj.getOffset());
  272. crc.reset();
  273. return readObjectHeader(info);
  274. }
  275. /** {@inheritDoc} */
  276. @Override
  277. protected int readDatabase(byte[] dst, int pos, int cnt) throws IOException {
  278. return out.read(dst, pos, cnt);
  279. }
  280. /** {@inheritDoc} */
  281. @Override
  282. protected boolean checkCRC(int oldCRC) {
  283. return oldCRC == (int) crc.getValue();
  284. }
  285. private static String baseName(File tmpPack) {
  286. String name = tmpPack.getName();
  287. return name.substring(0, name.lastIndexOf('.'));
  288. }
  289. private void cleanupTemporaryFiles() {
  290. if (tmpIdx != null && !tmpIdx.delete() && tmpIdx.exists())
  291. tmpIdx.deleteOnExit();
  292. if (tmpPack != null && !tmpPack.delete() && tmpPack.exists())
  293. tmpPack.deleteOnExit();
  294. }
  295. /** {@inheritDoc} */
  296. @Override
  297. protected boolean onAppendBase(final int typeCode, final byte[] data,
  298. final PackedObjectInfo info) throws IOException {
  299. info.setOffset(packEnd);
  300. final byte[] buf = buffer();
  301. int sz = data.length;
  302. int len = 0;
  303. buf[len++] = (byte) ((typeCode << 4) | sz & 15);
  304. sz >>>= 4;
  305. while (sz > 0) {
  306. buf[len - 1] |= 0x80;
  307. buf[len++] = (byte) (sz & 0x7f);
  308. sz >>>= 7;
  309. }
  310. tailDigest.update(buf, 0, len);
  311. crc.reset();
  312. crc.update(buf, 0, len);
  313. out.seek(packEnd);
  314. out.write(buf, 0, len);
  315. packEnd += len;
  316. if (def == null)
  317. def = new Deflater(Deflater.DEFAULT_COMPRESSION, false);
  318. else
  319. def.reset();
  320. def.setInput(data);
  321. def.finish();
  322. while (!def.finished()) {
  323. len = def.deflate(buf);
  324. tailDigest.update(buf, 0, len);
  325. crc.update(buf, 0, len);
  326. out.write(buf, 0, len);
  327. packEnd += len;
  328. }
  329. info.setCRC((int) crc.getValue());
  330. return true;
  331. }
  332. /** {@inheritDoc} */
  333. @Override
  334. protected void onEndThinPack() throws IOException {
  335. final byte[] buf = buffer();
  336. final MessageDigest origDigest = Constants.newMessageDigest();
  337. final MessageDigest tailDigest2 = Constants.newMessageDigest();
  338. final MessageDigest packDigest = Constants.newMessageDigest();
  339. long origRemaining = origEnd;
  340. out.seek(0);
  341. out.readFully(buf, 0, 12);
  342. origDigest.update(buf, 0, 12);
  343. origRemaining -= 12;
  344. NB.encodeInt32(buf, 8, getObjectCount());
  345. out.seek(0);
  346. out.write(buf, 0, 12);
  347. packDigest.update(buf, 0, 12);
  348. for (;;) {
  349. final int n = out.read(buf);
  350. if (n < 0)
  351. break;
  352. if (origRemaining != 0) {
  353. final int origCnt = (int) Math.min(n, origRemaining);
  354. origDigest.update(buf, 0, origCnt);
  355. origRemaining -= origCnt;
  356. if (origRemaining == 0)
  357. tailDigest2.update(buf, origCnt, n - origCnt);
  358. } else
  359. tailDigest2.update(buf, 0, n);
  360. packDigest.update(buf, 0, n);
  361. }
  362. if (!Arrays.equals(origDigest.digest(), origHash) || !Arrays
  363. .equals(tailDigest2.digest(), this.tailDigest.digest()))
  364. throw new IOException(
  365. JGitText.get().packCorruptedWhileWritingToFilesystem);
  366. packHash = packDigest.digest();
  367. }
  368. private void writeIdx() throws IOException {
  369. List<PackedObjectInfo> list = getSortedObjectList(null /* by ObjectId */);
  370. final FileOutputStream os = new FileOutputStream(tmpIdx);
  371. try {
  372. final PackIndexWriter iw;
  373. if (indexVersion <= 0)
  374. iw = PackIndexWriter.createOldestPossible(os, list);
  375. else
  376. iw = PackIndexWriter.createVersion(os, indexVersion);
  377. iw.write(list, packHash);
  378. os.getChannel().force(true);
  379. } finally {
  380. os.close();
  381. }
  382. }
  383. private PackLock renameAndOpenPack(final String lockMessage)
  384. throws IOException {
  385. if (!keepEmpty && getObjectCount() == 0) {
  386. cleanupTemporaryFiles();
  387. return null;
  388. }
  389. final MessageDigest d = Constants.newMessageDigest();
  390. final byte[] oeBytes = new byte[Constants.OBJECT_ID_LENGTH];
  391. for (int i = 0; i < getObjectCount(); i++) {
  392. final PackedObjectInfo oe = getObject(i);
  393. oe.copyRawTo(oeBytes, 0);
  394. d.update(oeBytes);
  395. }
  396. final String name = ObjectId.fromRaw(d.digest()).name();
  397. final File packDir = new File(db.getDirectory(), "pack"); //$NON-NLS-1$
  398. final File finalPack = new File(packDir, "pack-" + name + ".pack"); //$NON-NLS-1$ //$NON-NLS-2$
  399. final File finalIdx = new File(packDir, "pack-" + name + ".idx"); //$NON-NLS-1$ //$NON-NLS-2$
  400. final PackLock keep = new PackLock(finalPack, db.getFS());
  401. if (!packDir.exists() && !packDir.mkdir() && !packDir.exists()) {
  402. // The objects/pack directory isn't present, and we are unable
  403. // to create it. There is no way to move this pack in.
  404. //
  405. cleanupTemporaryFiles();
  406. throw new IOException(MessageFormat.format(
  407. JGitText.get().cannotCreateDirectory, packDir
  408. .getAbsolutePath()));
  409. }
  410. if (finalPack.exists()) {
  411. // If the pack is already present we should never replace it.
  412. //
  413. cleanupTemporaryFiles();
  414. return null;
  415. }
  416. if (lockMessage != null) {
  417. // If we have a reason to create a keep file for this pack, do
  418. // so, or fail fast and don't put the pack in place.
  419. //
  420. try {
  421. if (!keep.lock(lockMessage))
  422. throw new LockFailedException(finalPack,
  423. MessageFormat.format(
  424. JGitText.get().cannotLockPackIn, finalPack));
  425. } catch (IOException e) {
  426. cleanupTemporaryFiles();
  427. throw e;
  428. }
  429. }
  430. try {
  431. FileUtils.rename(tmpPack, finalPack,
  432. StandardCopyOption.ATOMIC_MOVE);
  433. } catch (IOException e) {
  434. cleanupTemporaryFiles();
  435. keep.unlock();
  436. throw new IOException(MessageFormat.format(
  437. JGitText.get().cannotMovePackTo, finalPack), e);
  438. }
  439. try {
  440. FileUtils.rename(tmpIdx, finalIdx, StandardCopyOption.ATOMIC_MOVE);
  441. } catch (IOException e) {
  442. cleanupTemporaryFiles();
  443. keep.unlock();
  444. if (!finalPack.delete())
  445. finalPack.deleteOnExit();
  446. throw new IOException(MessageFormat.format(
  447. JGitText.get().cannotMoveIndexTo, finalIdx), e);
  448. }
  449. try {
  450. newPack = db.openPack(finalPack);
  451. } catch (IOException err) {
  452. keep.unlock();
  453. if (finalPack.exists())
  454. FileUtils.delete(finalPack);
  455. if (finalIdx.exists())
  456. FileUtils.delete(finalIdx);
  457. throw err;
  458. }
  459. return lockMessage != null ? keep : null;
  460. }
  461. }