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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  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.ObjectInserter;
  65. import org.eclipse.jgit.lib.ProgressMonitor;
  66. import org.eclipse.jgit.transport.PackParser;
  67. import org.eclipse.jgit.transport.PackedObjectInfo;
  68. import org.eclipse.jgit.util.FileUtils;
  69. import org.eclipse.jgit.util.NB;
  70. /**
  71. * Consumes a pack stream and stores as a pack file in {@link ObjectDirectory}.
  72. * <p>
  73. * To obtain an instance of a parser, applications should use
  74. * {@link 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 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. @Override
  150. public long getPackSize() {
  151. if (newPack == null)
  152. return super.getPackSize();
  153. File pack = newPack.getPackFile();
  154. long size = pack.length();
  155. String p = pack.getAbsolutePath();
  156. String i = p.substring(0, p.length() - ".pack".length()) + ".idx"; //$NON-NLS-1$ //$NON-NLS-2$
  157. File idx = new File(i);
  158. if (idx.exists() && idx.isFile())
  159. size += idx.length();
  160. return size;
  161. }
  162. @Override
  163. public PackLock parse(ProgressMonitor receiving, ProgressMonitor resolving)
  164. throws IOException {
  165. tmpPack = File.createTempFile("incoming_", ".pack", db.getDirectory()); //$NON-NLS-1$ //$NON-NLS-2$
  166. tmpIdx = new File(db.getDirectory(), baseName(tmpPack) + ".idx"); //$NON-NLS-1$
  167. try {
  168. out = new RandomAccessFile(tmpPack, "rw"); //$NON-NLS-1$
  169. super.parse(receiving, resolving);
  170. out.seek(packEnd);
  171. out.write(packHash);
  172. out.getChannel().force(true);
  173. out.close();
  174. writeIdx();
  175. tmpPack.setReadOnly();
  176. tmpIdx.setReadOnly();
  177. return renameAndOpenPack(getLockMessage());
  178. } finally {
  179. if (def != null)
  180. def.end();
  181. try {
  182. if (out != null && out.getChannel().isOpen())
  183. out.close();
  184. } catch (IOException closeError) {
  185. // Ignored. We want to delete the file.
  186. }
  187. cleanupTemporaryFiles();
  188. }
  189. }
  190. @Override
  191. protected void onPackHeader(long objectCount) throws IOException {
  192. // Ignored, the count is not required.
  193. }
  194. @Override
  195. protected void onBeginWholeObject(long streamPosition, int type,
  196. long inflatedSize) throws IOException {
  197. crc.reset();
  198. }
  199. @Override
  200. protected void onEndWholeObject(PackedObjectInfo info) throws IOException {
  201. info.setCRC((int) crc.getValue());
  202. }
  203. @Override
  204. protected void onBeginOfsDelta(long streamPosition,
  205. long baseStreamPosition, long inflatedSize) throws IOException {
  206. crc.reset();
  207. }
  208. @Override
  209. protected void onBeginRefDelta(long streamPosition, AnyObjectId baseId,
  210. long inflatedSize) throws IOException {
  211. crc.reset();
  212. }
  213. @Override
  214. protected UnresolvedDelta onEndDelta() throws IOException {
  215. UnresolvedDelta delta = new UnresolvedDelta();
  216. delta.setCRC((int) crc.getValue());
  217. return delta;
  218. }
  219. @Override
  220. protected void onInflatedObjectData(PackedObjectInfo obj, int typeCode,
  221. byte[] data) throws IOException {
  222. // ObjectDirectory ignores this event.
  223. }
  224. @Override
  225. protected void onObjectHeader(Source src, byte[] raw, int pos, int len)
  226. throws IOException {
  227. crc.update(raw, pos, len);
  228. }
  229. @Override
  230. protected void onObjectData(Source src, byte[] raw, int pos, int len)
  231. throws IOException {
  232. crc.update(raw, pos, len);
  233. }
  234. @Override
  235. protected void onStoreStream(byte[] raw, int pos, int len)
  236. throws IOException {
  237. out.write(raw, pos, len);
  238. }
  239. @Override
  240. protected void onPackFooter(byte[] hash) throws IOException {
  241. packEnd = out.getFilePointer();
  242. origEnd = packEnd;
  243. origHash = hash;
  244. packHash = hash;
  245. }
  246. @Override
  247. protected ObjectTypeAndSize seekDatabase(UnresolvedDelta delta,
  248. ObjectTypeAndSize info) throws IOException {
  249. out.seek(delta.getOffset());
  250. crc.reset();
  251. return readObjectHeader(info);
  252. }
  253. @Override
  254. protected ObjectTypeAndSize seekDatabase(PackedObjectInfo obj,
  255. ObjectTypeAndSize info) throws IOException {
  256. out.seek(obj.getOffset());
  257. crc.reset();
  258. return readObjectHeader(info);
  259. }
  260. @Override
  261. protected int readDatabase(byte[] dst, int pos, int cnt) throws IOException {
  262. return out.read(dst, pos, cnt);
  263. }
  264. @Override
  265. protected boolean checkCRC(int oldCRC) {
  266. return oldCRC == (int) crc.getValue();
  267. }
  268. private static String baseName(File tmpPack) {
  269. String name = tmpPack.getName();
  270. return name.substring(0, name.lastIndexOf('.'));
  271. }
  272. private void cleanupTemporaryFiles() {
  273. if (tmpIdx != null && !tmpIdx.delete() && tmpIdx.exists())
  274. tmpIdx.deleteOnExit();
  275. if (tmpPack != null && !tmpPack.delete() && tmpPack.exists())
  276. tmpPack.deleteOnExit();
  277. }
  278. @Override
  279. protected boolean onAppendBase(final int typeCode, final byte[] data,
  280. final PackedObjectInfo info) throws IOException {
  281. info.setOffset(packEnd);
  282. final byte[] buf = buffer();
  283. int sz = data.length;
  284. int len = 0;
  285. buf[len++] = (byte) ((typeCode << 4) | sz & 15);
  286. sz >>>= 4;
  287. while (sz > 0) {
  288. buf[len - 1] |= 0x80;
  289. buf[len++] = (byte) (sz & 0x7f);
  290. sz >>>= 7;
  291. }
  292. tailDigest.update(buf, 0, len);
  293. crc.reset();
  294. crc.update(buf, 0, len);
  295. out.seek(packEnd);
  296. out.write(buf, 0, len);
  297. packEnd += len;
  298. if (def == null)
  299. def = new Deflater(Deflater.DEFAULT_COMPRESSION, false);
  300. else
  301. def.reset();
  302. def.setInput(data);
  303. def.finish();
  304. while (!def.finished()) {
  305. len = def.deflate(buf);
  306. tailDigest.update(buf, 0, len);
  307. crc.update(buf, 0, len);
  308. out.write(buf, 0, len);
  309. packEnd += len;
  310. }
  311. info.setCRC((int) crc.getValue());
  312. return true;
  313. }
  314. @Override
  315. protected void onEndThinPack() throws IOException {
  316. final byte[] buf = buffer();
  317. final MessageDigest origDigest = Constants.newMessageDigest();
  318. final MessageDigest tailDigest2 = Constants.newMessageDigest();
  319. final MessageDigest packDigest = Constants.newMessageDigest();
  320. long origRemaining = origEnd;
  321. out.seek(0);
  322. out.readFully(buf, 0, 12);
  323. origDigest.update(buf, 0, 12);
  324. origRemaining -= 12;
  325. NB.encodeInt32(buf, 8, getObjectCount());
  326. out.seek(0);
  327. out.write(buf, 0, 12);
  328. packDigest.update(buf, 0, 12);
  329. for (;;) {
  330. final int n = out.read(buf);
  331. if (n < 0)
  332. break;
  333. if (origRemaining != 0) {
  334. final int origCnt = (int) Math.min(n, origRemaining);
  335. origDigest.update(buf, 0, origCnt);
  336. origRemaining -= origCnt;
  337. if (origRemaining == 0)
  338. tailDigest2.update(buf, origCnt, n - origCnt);
  339. } else
  340. tailDigest2.update(buf, 0, n);
  341. packDigest.update(buf, 0, n);
  342. }
  343. if (!Arrays.equals(origDigest.digest(), origHash) || !Arrays
  344. .equals(tailDigest2.digest(), this.tailDigest.digest()))
  345. throw new IOException(
  346. JGitText.get().packCorruptedWhileWritingToFilesystem);
  347. packHash = packDigest.digest();
  348. }
  349. private void writeIdx() throws IOException {
  350. List<PackedObjectInfo> list = getSortedObjectList(null /* by ObjectId */);
  351. final FileOutputStream os = new FileOutputStream(tmpIdx);
  352. try {
  353. final PackIndexWriter iw;
  354. if (indexVersion <= 0)
  355. iw = PackIndexWriter.createOldestPossible(os, list);
  356. else
  357. iw = PackIndexWriter.createVersion(os, indexVersion);
  358. iw.write(list, packHash);
  359. os.getChannel().force(true);
  360. } finally {
  361. os.close();
  362. }
  363. }
  364. private PackLock renameAndOpenPack(final String lockMessage)
  365. throws IOException {
  366. if (!keepEmpty && getObjectCount() == 0) {
  367. cleanupTemporaryFiles();
  368. return null;
  369. }
  370. final MessageDigest d = Constants.newMessageDigest();
  371. final byte[] oeBytes = new byte[Constants.OBJECT_ID_LENGTH];
  372. for (int i = 0; i < getObjectCount(); i++) {
  373. final PackedObjectInfo oe = getObject(i);
  374. oe.copyRawTo(oeBytes, 0);
  375. d.update(oeBytes);
  376. }
  377. final String name = ObjectId.fromRaw(d.digest()).name();
  378. final File packDir = new File(db.getDirectory(), "pack"); //$NON-NLS-1$
  379. final File finalPack = new File(packDir, "pack-" + name + ".pack"); //$NON-NLS-1$ //$NON-NLS-2$
  380. final File finalIdx = new File(packDir, "pack-" + name + ".idx"); //$NON-NLS-1$ //$NON-NLS-2$
  381. final PackLock keep = new PackLock(finalPack, db.getFS());
  382. if (!packDir.exists() && !packDir.mkdir() && !packDir.exists()) {
  383. // The objects/pack directory isn't present, and we are unable
  384. // to create it. There is no way to move this pack in.
  385. //
  386. cleanupTemporaryFiles();
  387. throw new IOException(MessageFormat.format(
  388. JGitText.get().cannotCreateDirectory, packDir
  389. .getAbsolutePath()));
  390. }
  391. if (finalPack.exists()) {
  392. // If the pack is already present we should never replace it.
  393. //
  394. cleanupTemporaryFiles();
  395. return null;
  396. }
  397. if (lockMessage != null) {
  398. // If we have a reason to create a keep file for this pack, do
  399. // so, or fail fast and don't put the pack in place.
  400. //
  401. try {
  402. if (!keep.lock(lockMessage))
  403. throw new LockFailedException(finalPack,
  404. MessageFormat.format(
  405. JGitText.get().cannotLockPackIn, finalPack));
  406. } catch (IOException e) {
  407. cleanupTemporaryFiles();
  408. throw e;
  409. }
  410. }
  411. try {
  412. FileUtils.rename(tmpPack, finalPack,
  413. StandardCopyOption.ATOMIC_MOVE);
  414. } catch (IOException e) {
  415. cleanupTemporaryFiles();
  416. keep.unlock();
  417. throw new IOException(MessageFormat.format(
  418. JGitText.get().cannotMovePackTo, finalPack), e);
  419. }
  420. try {
  421. FileUtils.rename(tmpIdx, finalIdx, StandardCopyOption.ATOMIC_MOVE);
  422. } catch (IOException e) {
  423. cleanupTemporaryFiles();
  424. keep.unlock();
  425. if (!finalPack.delete())
  426. finalPack.deleteOnExit();
  427. throw new IOException(MessageFormat.format(
  428. JGitText.get().cannotMoveIndexTo, finalIdx), e);
  429. }
  430. try {
  431. newPack = db.openPack(finalPack);
  432. } catch (IOException err) {
  433. keep.unlock();
  434. if (finalPack.exists())
  435. FileUtils.delete(finalPack);
  436. if (finalIdx.exists())
  437. FileUtils.delete(finalIdx);
  438. throw err;
  439. }
  440. return lockMessage != null ? keep : null;
  441. }
  442. }