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.

ObjectDirectoryTest.java 9.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. /*
  2. * Copyright (C) 2012, Roberto Tyley <roberto.tyley@gmail.com>
  3. *
  4. * This program and the accompanying materials are made available
  5. * under the terms of the Eclipse Distribution License v1.0 which
  6. * accompanies this distribution, is reproduced below, and is
  7. * available at http://www.eclipse.org/org/documents/edl-v10.php
  8. *
  9. * All rights reserved.
  10. *
  11. * Redistribution and use in source and binary forms, with or
  12. * without modification, are permitted provided that the following
  13. * conditions are met:
  14. *
  15. * - Redistributions of source code must retain the above copyright
  16. * notice, this list of conditions and the following disclaimer.
  17. *
  18. * - Redistributions in binary form must reproduce the above
  19. * copyright notice, this list of conditions and the following
  20. * disclaimer in the documentation and/or other materials provided
  21. * with the distribution.
  22. *
  23. * - Neither the name of the Eclipse Foundation, Inc. nor the
  24. * names of its contributors may be used to endorse or promote
  25. * products derived from this software without specific prior
  26. * written permission.
  27. *
  28. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  29. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  30. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  31. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  32. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  33. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  34. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  35. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  36. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  37. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  38. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  39. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  40. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  41. */
  42. package org.eclipse.jgit.internal.storage.file;
  43. import static java.nio.charset.StandardCharsets.UTF_8;
  44. import static org.junit.Assert.assertFalse;
  45. import static org.junit.Assert.assertNull;
  46. import static org.junit.Assert.assertThrows;
  47. import static org.junit.Assert.assertTrue;
  48. import static org.mockito.ArgumentMatchers.any;
  49. import static org.mockito.Mockito.mock;
  50. import static org.mockito.Mockito.verify;
  51. import java.io.File;
  52. import java.io.IOException;
  53. import java.io.PrintWriter;
  54. import java.text.MessageFormat;
  55. import java.util.Collection;
  56. import java.util.Collections;
  57. import java.util.Set;
  58. import java.util.concurrent.Callable;
  59. import java.util.concurrent.ExecutorService;
  60. import java.util.concurrent.Executors;
  61. import java.util.concurrent.Future;
  62. import org.eclipse.jgit.internal.JGitText;
  63. import org.eclipse.jgit.junit.RepositoryTestCase;
  64. import org.eclipse.jgit.lib.ConfigConstants;
  65. import org.eclipse.jgit.lib.Constants;
  66. import org.eclipse.jgit.lib.ObjectId;
  67. import org.eclipse.jgit.revwalk.RevCommit;
  68. import org.eclipse.jgit.storage.file.FileBasedConfig;
  69. import org.eclipse.jgit.util.FS;
  70. import org.junit.Assume;
  71. import org.junit.Test;
  72. import org.mockito.Mockito;
  73. public class ObjectDirectoryTest extends RepositoryTestCase {
  74. @Test
  75. public void testConcurrentInsertionOfBlobsToTheSameNewFanOutDirectory()
  76. throws Exception {
  77. ExecutorService e = Executors.newCachedThreadPool();
  78. for (int i=0; i < 100; ++i) {
  79. ObjectDirectory dir = createBareRepository().getObjectDatabase();
  80. for (Future f : e.invokeAll(blobInsertersForTheSameFanOutDir(dir))) {
  81. f.get();
  82. }
  83. }
  84. }
  85. /**
  86. * Test packfile scanning while a gc is done from the outside (different
  87. * process or different Repository instance). This situation occurs e.g. if
  88. * a gerrit server is serving fetch requests while native git is doing a
  89. * garbage collection. The test shows that when core.trustfolderstat==true
  90. * jgit may miss to detect that a new packfile was created. This situation
  91. * is persistent until a new full rescan of the pack directory is triggered.
  92. *
  93. * The test works with two Repository instances working on the same disk
  94. * location. One (db) for all write operations (creating commits, doing gc)
  95. * and another one (receivingDB) which just reads and which in the end shows
  96. * the bug
  97. *
  98. * @throws Exception
  99. */
  100. @Test
  101. public void testScanningForPackfiles() throws Exception {
  102. ObjectId unknownID = ObjectId
  103. .fromString("c0ffee09d0b63d694bf49bc1e6847473f42d4a8c");
  104. GC gc = new GC(db);
  105. gc.setExpireAgeMillis(0);
  106. gc.setPackExpireAgeMillis(0);
  107. // the default repo db is used to create the objects. The receivingDB
  108. // repo is used to trigger gc's
  109. try (FileRepository receivingDB = new FileRepository(
  110. db.getDirectory())) {
  111. // set trustfolderstat to true. If set to false the test always
  112. // succeeds.
  113. FileBasedConfig cfg = receivingDB.getConfig();
  114. cfg.setBoolean(ConfigConstants.CONFIG_CORE_SECTION, null,
  115. ConfigConstants.CONFIG_KEY_TRUSTFOLDERSTAT, true);
  116. cfg.save();
  117. // setup a repo which has at least one pack file and trigger
  118. // scanning of the packs directory
  119. ObjectId id = commitFile("file.txt", "test", "master").getId();
  120. gc.gc();
  121. assertFalse(receivingDB.getObjectDatabase().has(unknownID));
  122. assertTrue(receivingDB.getObjectDatabase().hasPackedObject(id));
  123. // preparations
  124. File packsFolder = receivingDB.getObjectDatabase()
  125. .getPackDirectory();
  126. // prepare creation of a temporary file in the pack folder. This
  127. // simulates that a native git gc is happening starting to write
  128. // temporary files but has not yet finished
  129. File tmpFile = new File(packsFolder, "1.tmp");
  130. RevCommit id2 = commitFile("file.txt", "test2", "master");
  131. // wait until filesystem timer ticks. This raises probability that
  132. // the next statements are executed in the same tick as the
  133. // filesystem timer
  134. fsTick(null);
  135. // create a Temp file in the packs folder and trigger a rescan of
  136. // the packs folder. This lets receivingDB think it has scanned the
  137. // packs folder at the current fs timestamp t1. The following gc
  138. // will create new files which have the same timestamp t1 but this
  139. // will not update the mtime of the packs folder. Because of that
  140. // JGit will not rescan the packs folder later on and fails to see
  141. // the pack file created during gc.
  142. assertTrue(tmpFile.createNewFile());
  143. assertFalse(receivingDB.getObjectDatabase().has(unknownID));
  144. // trigger a gc. This will create packfiles which have likely the
  145. // same mtime than the packfolder
  146. gc.gc();
  147. // To deal with racy-git situations JGit's Filesnapshot class will
  148. // report a file/folder potentially dirty if
  149. // cachedLastReadTime-cachedLastModificationTime < filesystem
  150. // timestamp resolution. This causes JGit to always rescan a file
  151. // after modification. But: this was true only if the difference
  152. // between current system time and cachedLastModification time was
  153. // less than 2500ms. If the modification is more than 2500ms ago we
  154. // may have reported a file/folder to be clean although it has not
  155. // been rescanned. A bug. To show the bug we sleep for more than
  156. // 2500ms
  157. Thread.sleep(2600);
  158. File[] ret = packsFolder.listFiles(
  159. (File dir, String name) -> name.endsWith(".pack"));
  160. assertTrue(ret != null && ret.length == 1);
  161. FS fs = db.getFS();
  162. Assume.assumeTrue(fs.lastModifiedInstant(tmpFile)
  163. .equals(fs.lastModifiedInstant(ret[0])));
  164. // all objects are in a new packfile but we will not detect it
  165. assertFalse(receivingDB.getObjectDatabase().has(unknownID));
  166. assertTrue(receivingDB.getObjectDatabase().has(id2));
  167. }
  168. }
  169. @Test
  170. public void testShallowFile()
  171. throws Exception {
  172. FileRepository repository = createBareRepository();
  173. ObjectDirectory dir = repository.getObjectDatabase();
  174. String commit = "d3148f9410b071edd4a4c85d2a43d1fa2574b0d2";
  175. try (PrintWriter writer = new PrintWriter(
  176. new File(repository.getDirectory(), Constants.SHALLOW),
  177. UTF_8.name())) {
  178. writer.println(commit);
  179. }
  180. Set<ObjectId> shallowCommits = dir.getShallowCommits();
  181. assertTrue(shallowCommits.remove(ObjectId.fromString(commit)));
  182. assertTrue(shallowCommits.isEmpty());
  183. }
  184. @Test
  185. public void testOpenLooseObjectSuppressStaleFileHandleException()
  186. throws Exception {
  187. ObjectId id = ObjectId
  188. .fromString("873fb8d667d05436d728c52b1d7a09528e6eb59b");
  189. WindowCursor curs = new WindowCursor(db.getObjectDatabase());
  190. LooseObjects mock = mock(LooseObjects.class);
  191. UnpackedObjectCache unpackedObjectCacheMock = mock(
  192. UnpackedObjectCache.class);
  193. Mockito.when(mock.getObjectLoader(any(), any(), any()))
  194. .thenThrow(new IOException("Stale File Handle"));
  195. Mockito.when(mock.open(curs, id)).thenCallRealMethod();
  196. Mockito.when(mock.unpackedObjectCache())
  197. .thenReturn(unpackedObjectCacheMock);
  198. assertNull(mock.open(curs, id));
  199. verify(unpackedObjectCacheMock).remove(id);
  200. }
  201. @Test
  202. public void testOpenLooseObjectPropagatesIOExceptions() throws Exception {
  203. ObjectId id = ObjectId
  204. .fromString("873fb8d667d05436d728c52b1d7a09528e6eb59b");
  205. WindowCursor curs = new WindowCursor(db.getObjectDatabase());
  206. LooseObjects mock = mock(LooseObjects.class);
  207. Mockito.when(mock.getObjectLoader(any(), any(), any()))
  208. .thenThrow(new IOException("some IO failure"));
  209. Mockito.when(mock.open(curs, id)).thenCallRealMethod();
  210. assertThrows(IOException.class, () -> mock.open(curs, id));
  211. }
  212. @Test
  213. public void testShallowFileCorrupt() throws Exception {
  214. FileRepository repository = createBareRepository();
  215. ObjectDirectory dir = repository.getObjectDatabase();
  216. String commit = "X3148f9410b071edd4a4c85d2a43d1fa2574b0d2";
  217. try (PrintWriter writer = new PrintWriter(
  218. new File(repository.getDirectory(), Constants.SHALLOW),
  219. UTF_8.name())) {
  220. writer.println(commit);
  221. }
  222. assertThrows(
  223. MessageFormat.format(JGitText.get().badShallowLine, commit),
  224. IOException.class, () -> dir.getShallowCommits());
  225. }
  226. private Collection<Callable<ObjectId>> blobInsertersForTheSameFanOutDir(
  227. final ObjectDirectory dir) {
  228. Callable<ObjectId> callable = () -> dir.newInserter()
  229. .insert(Constants.OBJ_BLOB, new byte[0]);
  230. return Collections.nCopies(4, callable);
  231. }
  232. }