選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

ObjectDirectoryPackParser.java 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  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.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.security.MessageDigest;
  52. import java.text.MessageFormat;
  53. import java.util.Arrays;
  54. import java.util.List;
  55. import java.util.zip.CRC32;
  56. import java.util.zip.Deflater;
  57. import org.eclipse.jgit.JGitText;
  58. import org.eclipse.jgit.lib.AnyObjectId;
  59. import org.eclipse.jgit.lib.Constants;
  60. import org.eclipse.jgit.lib.CoreConfig;
  61. import org.eclipse.jgit.lib.ObjectId;
  62. import org.eclipse.jgit.lib.ObjectInserter;
  63. import org.eclipse.jgit.lib.ProgressMonitor;
  64. import org.eclipse.jgit.transport.PackParser;
  65. import org.eclipse.jgit.transport.PackedObjectInfo;
  66. import org.eclipse.jgit.util.FileUtils;
  67. import org.eclipse.jgit.util.NB;
  68. /**
  69. * Consumes a pack stream and stores as a pack file in {@link ObjectDirectory}.
  70. * <p>
  71. * To obtain an instance of a parser, applications should use
  72. * {@link ObjectInserter#newPackParser(InputStream)}.
  73. */
  74. public class ObjectDirectoryPackParser extends PackParser {
  75. private final FileObjectDatabase db;
  76. /** CRC-32 computation for objects that are appended onto the pack. */
  77. private final CRC32 crc;
  78. /** Running SHA-1 of any base objects appended after {@link #origEnd}. */
  79. private final MessageDigest tailDigest;
  80. /** Preferred format version of the pack-*.idx file to generate. */
  81. private int indexVersion;
  82. /** If true, pack with 0 objects will be stored. Usually these are deleted. */
  83. private boolean keepEmpty;
  84. /** Path of the temporary file holding the pack data. */
  85. private File tmpPack;
  86. /**
  87. * Path of the index created for the pack, to find objects quickly at read
  88. * time.
  89. */
  90. private File tmpIdx;
  91. /** Read/write handle to {@link #tmpPack} while it is being parsed. */
  92. private RandomAccessFile out;
  93. /** Length of the original pack stream, before missing bases were appended. */
  94. private long origEnd;
  95. /** The original checksum of data up to {@link #origEnd}. */
  96. private byte[] origHash;
  97. /** Current end of the pack file. */
  98. private long packEnd;
  99. /** Checksum of the entire pack file. */
  100. private byte[] packHash;
  101. /** Compresses delta bases when completing a thin pack. */
  102. private Deflater def;
  103. /** The pack that was created, if parsing was successful. */
  104. private PackFile newPack;
  105. ObjectDirectoryPackParser(FileObjectDatabase odb, InputStream src) {
  106. super(odb, src);
  107. this.db = odb;
  108. this.crc = new CRC32();
  109. this.tailDigest = Constants.newMessageDigest();
  110. indexVersion = db.getConfig().get(CoreConfig.KEY).getPackIndexVersion();
  111. }
  112. /**
  113. * Set the pack index file format version this instance will create.
  114. *
  115. * @param version
  116. * the version to write. The special version 0 designates the
  117. * oldest (most compatible) format available for the objects.
  118. * @see PackIndexWriter
  119. */
  120. public void setIndexVersion(int version) {
  121. indexVersion = version;
  122. }
  123. /**
  124. * Configure this index pack instance to keep an empty pack.
  125. * <p>
  126. * By default an empty pack (a pack with no objects) is not kept, as doi so
  127. * is completely pointless. With no objects in the pack there is no d stored
  128. * by it, so the pack is unnecessary.
  129. *
  130. * @param empty
  131. * true to enable keeping an empty pack.
  132. */
  133. public void setKeepEmpty(final boolean empty) {
  134. keepEmpty = empty;
  135. }
  136. /**
  137. * Get the imported {@link PackFile}.
  138. * <p>
  139. * This method is supplied only to support testing; applications shouldn't
  140. * be using it directly to access the imported data.
  141. *
  142. * @return the imported PackFile, if parsing was successful.
  143. */
  144. public PackFile getPackFile() {
  145. return newPack;
  146. }
  147. @Override
  148. public PackLock parse(ProgressMonitor progress) throws IOException {
  149. tmpPack = File.createTempFile("incoming_", ".pack", db.getDirectory());
  150. tmpIdx = new File(db.getDirectory(), baseName(tmpPack) + ".idx");
  151. try {
  152. out = new RandomAccessFile(tmpPack, "rw");
  153. super.parse(progress);
  154. out.seek(packEnd);
  155. out.write(packHash);
  156. out.getChannel().force(true);
  157. out.close();
  158. writeIdx();
  159. tmpPack.setReadOnly();
  160. tmpIdx.setReadOnly();
  161. return renameAndOpenPack(getLockMessage());
  162. } finally {
  163. if (def != null)
  164. def.end();
  165. try {
  166. if (out != null && out.getChannel().isOpen())
  167. out.close();
  168. } catch (IOException closeError) {
  169. // Ignored. We want to delete the file.
  170. }
  171. cleanupTemporaryFiles();
  172. }
  173. }
  174. @Override
  175. protected void onBeginWholeObject(long streamPosition, int type,
  176. long inflatedSize) throws IOException {
  177. crc.reset();
  178. }
  179. @Override
  180. protected void onEndWholeObject(PackedObjectInfo info) throws IOException {
  181. info.setCRC((int) crc.getValue());
  182. }
  183. @Override
  184. protected void onBeginOfsDelta(long streamPosition,
  185. long baseStreamPosition, long inflatedSize) throws IOException {
  186. crc.reset();
  187. }
  188. @Override
  189. protected void onBeginRefDelta(long streamPosition, AnyObjectId baseId,
  190. long inflatedSize) throws IOException {
  191. crc.reset();
  192. }
  193. @Override
  194. protected UnresolvedDelta onEndDelta() throws IOException {
  195. UnresolvedDelta delta = new UnresolvedDelta();
  196. delta.setCRC((int) crc.getValue());
  197. return delta;
  198. }
  199. @Override
  200. protected void onObjectHeader(Source src, byte[] raw, int pos, int len)
  201. throws IOException {
  202. crc.update(raw, pos, len);
  203. }
  204. @Override
  205. protected void onObjectData(Source src, byte[] raw, int pos, int len)
  206. throws IOException {
  207. crc.update(raw, pos, len);
  208. }
  209. @Override
  210. protected void onStoreStream(byte[] raw, int pos, int len)
  211. throws IOException {
  212. out.write(raw, pos, len);
  213. }
  214. @Override
  215. protected void onPackFooter(byte[] hash) throws IOException {
  216. packEnd = out.getFilePointer();
  217. origEnd = packEnd;
  218. origHash = hash;
  219. packHash = hash;
  220. }
  221. @Override
  222. protected ObjectTypeAndSize seekDatabase(UnresolvedDelta delta,
  223. ObjectTypeAndSize info) throws IOException {
  224. out.seek(delta.getOffset());
  225. crc.reset();
  226. return readObjectHeader(info);
  227. }
  228. @Override
  229. protected ObjectTypeAndSize seekDatabase(PackedObjectInfo obj,
  230. ObjectTypeAndSize info) throws IOException {
  231. out.seek(obj.getOffset());
  232. crc.reset();
  233. return readObjectHeader(info);
  234. }
  235. @Override
  236. protected int readDatabase(byte[] dst, int pos, int cnt) throws IOException {
  237. return out.read(dst, pos, cnt);
  238. }
  239. @Override
  240. protected boolean checkCRC(int oldCRC) {
  241. return oldCRC == (int) crc.getValue();
  242. }
  243. private static String baseName(File tmpPack) {
  244. String name = tmpPack.getName();
  245. return name.substring(0, name.lastIndexOf('.'));
  246. }
  247. private void cleanupTemporaryFiles() {
  248. if (tmpIdx != null && !tmpIdx.delete() && tmpIdx.exists())
  249. tmpIdx.deleteOnExit();
  250. if (tmpPack != null && !tmpPack.delete() && tmpPack.exists())
  251. tmpPack.deleteOnExit();
  252. }
  253. @Override
  254. protected boolean onAppendBase(final int typeCode, final byte[] data,
  255. final PackedObjectInfo info) throws IOException {
  256. info.setOffset(packEnd);
  257. final byte[] buf = buffer();
  258. int sz = data.length;
  259. int len = 0;
  260. buf[len++] = (byte) ((typeCode << 4) | sz & 15);
  261. sz >>>= 4;
  262. while (sz > 0) {
  263. buf[len - 1] |= 0x80;
  264. buf[len++] = (byte) (sz & 0x7f);
  265. sz >>>= 7;
  266. }
  267. tailDigest.update(buf, 0, len);
  268. crc.reset();
  269. crc.update(buf, 0, len);
  270. out.seek(packEnd);
  271. out.write(buf, 0, len);
  272. packEnd += len;
  273. if (def == null)
  274. def = new Deflater(Deflater.DEFAULT_COMPRESSION, false);
  275. else
  276. def.reset();
  277. def.setInput(data);
  278. def.finish();
  279. while (!def.finished()) {
  280. len = def.deflate(buf);
  281. tailDigest.update(buf, 0, len);
  282. crc.update(buf, 0, len);
  283. out.write(buf, 0, len);
  284. packEnd += len;
  285. }
  286. info.setCRC((int) crc.getValue());
  287. return true;
  288. }
  289. @Override
  290. protected void onEndThinPack() throws IOException {
  291. final byte[] tailHash = this.tailDigest.digest();
  292. final byte[] buf = buffer();
  293. final MessageDigest origDigest = Constants.newMessageDigest();
  294. final MessageDigest tailDigest = Constants.newMessageDigest();
  295. final MessageDigest packDigest = Constants.newMessageDigest();
  296. long origRemaining = origEnd;
  297. out.seek(0);
  298. out.readFully(buf, 0, 12);
  299. origDigest.update(buf, 0, 12);
  300. origRemaining -= 12;
  301. NB.encodeInt32(buf, 8, getObjectCount());
  302. out.seek(0);
  303. out.write(buf, 0, 12);
  304. packDigest.update(buf, 0, 12);
  305. for (;;) {
  306. final int n = out.read(buf);
  307. if (n < 0)
  308. break;
  309. if (origRemaining != 0) {
  310. final int origCnt = (int) Math.min(n, origRemaining);
  311. origDigest.update(buf, 0, origCnt);
  312. origRemaining -= origCnt;
  313. if (origRemaining == 0)
  314. tailDigest.update(buf, origCnt, n - origCnt);
  315. } else
  316. tailDigest.update(buf, 0, n);
  317. packDigest.update(buf, 0, n);
  318. }
  319. if (!Arrays.equals(origDigest.digest(), origHash)
  320. || !Arrays.equals(tailDigest.digest(), tailHash))
  321. throw new IOException(
  322. JGitText.get().packCorruptedWhileWritingToFilesystem);
  323. packHash = packDigest.digest();
  324. }
  325. private void writeIdx() throws IOException {
  326. List<PackedObjectInfo> list = getSortedObjectList(null /* by ObjectId */);
  327. final FileOutputStream os = new FileOutputStream(tmpIdx);
  328. try {
  329. final PackIndexWriter iw;
  330. if (indexVersion <= 0)
  331. iw = PackIndexWriter.createOldestPossible(os, list);
  332. else
  333. iw = PackIndexWriter.createVersion(os, indexVersion);
  334. iw.write(list, packHash);
  335. os.getChannel().force(true);
  336. } finally {
  337. os.close();
  338. }
  339. }
  340. private PackLock renameAndOpenPack(final String lockMessage)
  341. throws IOException {
  342. if (!keepEmpty && getObjectCount() == 0) {
  343. cleanupTemporaryFiles();
  344. return null;
  345. }
  346. final MessageDigest d = Constants.newMessageDigest();
  347. final byte[] oeBytes = new byte[Constants.OBJECT_ID_LENGTH];
  348. for (int i = 0; i < getObjectCount(); i++) {
  349. final PackedObjectInfo oe = getObject(i);
  350. oe.copyRawTo(oeBytes, 0);
  351. d.update(oeBytes);
  352. }
  353. final String name = ObjectId.fromRaw(d.digest()).name();
  354. final File packDir = new File(db.getDirectory(), "pack");
  355. final File finalPack = new File(packDir, "pack-" + name + ".pack");
  356. final File finalIdx = new File(packDir, "pack-" + name + ".idx");
  357. final PackLock keep = new PackLock(finalPack, db.getFS());
  358. if (!packDir.exists() && !packDir.mkdir() && !packDir.exists()) {
  359. // The objects/pack directory isn't present, and we are unable
  360. // to create it. There is no way to move this pack in.
  361. //
  362. cleanupTemporaryFiles();
  363. throw new IOException(MessageFormat.format(
  364. JGitText.get().cannotCreateDirectory, packDir
  365. .getAbsolutePath()));
  366. }
  367. if (finalPack.exists()) {
  368. // If the pack is already present we should never replace it.
  369. //
  370. cleanupTemporaryFiles();
  371. return null;
  372. }
  373. if (lockMessage != null) {
  374. // If we have a reason to create a keep file for this pack, do
  375. // so, or fail fast and don't put the pack in place.
  376. //
  377. try {
  378. if (!keep.lock(lockMessage))
  379. throw new IOException(MessageFormat.format(
  380. JGitText.get().cannotLockPackIn, finalPack));
  381. } catch (IOException e) {
  382. cleanupTemporaryFiles();
  383. throw e;
  384. }
  385. }
  386. if (!tmpPack.renameTo(finalPack)) {
  387. cleanupTemporaryFiles();
  388. keep.unlock();
  389. throw new IOException(MessageFormat.format(
  390. JGitText.get().cannotMovePackTo, finalPack));
  391. }
  392. if (!tmpIdx.renameTo(finalIdx)) {
  393. cleanupTemporaryFiles();
  394. keep.unlock();
  395. if (!finalPack.delete())
  396. finalPack.deleteOnExit();
  397. throw new IOException(MessageFormat.format(
  398. JGitText.get().cannotMoveIndexTo, finalIdx));
  399. }
  400. try {
  401. newPack = db.openPack(finalPack, finalIdx);
  402. } catch (IOException err) {
  403. keep.unlock();
  404. if (finalPack.exists())
  405. FileUtils.delete(finalPack);
  406. if (finalIdx.exists())
  407. FileUtils.delete(finalIdx);
  408. throw err;
  409. }
  410. return lockMessage != null ? keep : null;
  411. }
  412. }