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

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