View Javadoc
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  
43  package org.eclipse.jgit.internal.storage.file;
44  
45  import static java.nio.charset.StandardCharsets.UTF_8;
46  import static org.junit.Assert.assertFalse;
47  import static org.junit.Assert.assertNull;
48  import static org.junit.Assert.assertThrows;
49  import static org.junit.Assert.assertTrue;
50  import static org.mockito.ArgumentMatchers.any;
51  import static org.mockito.Mockito.mock;
52  import static org.mockito.Mockito.verify;
53  
54  import java.io.File;
55  import java.io.IOException;
56  import java.io.PrintWriter;
57  import java.text.MessageFormat;
58  import java.util.Collection;
59  import java.util.Collections;
60  import java.util.Set;
61  import java.util.concurrent.Callable;
62  import java.util.concurrent.ExecutorService;
63  import java.util.concurrent.Executors;
64  import java.util.concurrent.Future;
65  
66  import org.eclipse.jgit.internal.JGitText;
67  import org.eclipse.jgit.junit.RepositoryTestCase;
68  import org.eclipse.jgit.lib.ConfigConstants;
69  import org.eclipse.jgit.lib.Constants;
70  import org.eclipse.jgit.lib.ObjectId;
71  import org.eclipse.jgit.revwalk.RevCommit;
72  import org.eclipse.jgit.storage.file.FileBasedConfig;
73  import org.eclipse.jgit.util.FS;
74  import org.junit.Assume;
75  import org.junit.Test;
76  import org.mockito.Mockito;
77  
78  public class ObjectDirectoryTest extends RepositoryTestCase {
79  
80  	@Test
81  	public void testConcurrentInsertionOfBlobsToTheSameNewFanOutDirectory()
82  			throws Exception {
83  		ExecutorService e = Executors.newCachedThreadPool();
84  		for (int i=0; i < 100; ++i) {
85  			ObjectDirectory dir = createBareRepository().getObjectDatabase();
86  			for (Future f : e.invokeAll(blobInsertersForTheSameFanOutDir(dir))) {
87  				f.get();
88  			}
89  		}
90  	}
91  
92  	/**
93  	 * Test packfile scanning while a gc is done from the outside (different
94  	 * process or different Repository instance). This situation occurs e.g. if
95  	 * a gerrit server is serving fetch requests while native git is doing a
96  	 * garbage collection. The test shows that when core.trustfolderstat==true
97  	 * jgit may miss to detect that a new packfile was created. This situation
98  	 * is persistent until a new full rescan of the pack directory is triggered.
99  	 *
100 	 * The test works with two Repository instances working on the same disk
101 	 * location. One (db) for all write operations (creating commits, doing gc)
102 	 * and another one (receivingDB) which just reads and which in the end shows
103 	 * the bug
104 	 *
105 	 * @throws Exception
106 	 */
107 	@Test
108 	public void testScanningForPackfiles() throws Exception {
109 		ObjectId unknownID = ObjectId
110 				.fromString("c0ffee09d0b63d694bf49bc1e6847473f42d4a8c");
111 		GC gc = new GC(db);
112 		gc.setExpireAgeMillis(0);
113 		gc.setPackExpireAgeMillis(0);
114 
115 		// the default repo db is used to create the objects. The receivingDB
116 		// repo is used to trigger gc's
117 		try (FileRepository receivingDB = new FileRepository(
118 				db.getDirectory())) {
119 			// set trustfolderstat to true. If set to false the test always
120 			// succeeds.
121 			FileBasedConfig cfg = receivingDB.getConfig();
122 			cfg.setBoolean(ConfigConstants.CONFIG_CORE_SECTION, null,
123 					ConfigConstants.CONFIG_KEY_TRUSTFOLDERSTAT, true);
124 			cfg.save();
125 
126 			// setup a repo which has at least one pack file and trigger
127 			// scanning of the packs directory
128 			ObjectId id = commitFile("file.txt", "test", "master").getId();
129 			gc.gc().get();
130 			assertFalse(receivingDB.getObjectDatabase().has(unknownID));
131 			assertTrue(receivingDB.getObjectDatabase().hasPackedObject(id));
132 
133 			// preparations
134 			File packsFolder = receivingDB.getObjectDatabase()
135 					.getPackDirectory();
136 			// prepare creation of a temporary file in the pack folder. This
137 			// simulates that a native git gc is happening starting to write
138 			// temporary files but has not yet finished
139 			File tmpFile = new File(packsFolder, "1.tmp");
140 			RevCommit id2 = commitFile("file.txt", "test2", "master");
141 			// wait until filesystem timer ticks. This raises probability that
142 			// the next statements are executed in the same tick as the
143 			// filesystem timer
144 			fsTick(null);
145 
146 			// create a Temp file in the packs folder and trigger a rescan of
147 			// the packs folder. This lets receivingDB think it has scanned the
148 			// packs folder at the current fs timestamp t1. The following gc
149 			// will create new files which have the same timestamp t1 but this
150 			// will not update the mtime of the packs folder. Because of that
151 			// JGit will not rescan the packs folder later on and fails to see
152 			// the pack file created during gc.
153 			assertTrue(tmpFile.createNewFile());
154 			assertFalse(receivingDB.getObjectDatabase().has(unknownID));
155 
156 			// trigger a gc. This will create packfiles which have likely the
157 			// same mtime than the packfolder
158 			gc.gc().get();
159 
160 			// To deal with racy-git situations JGit's Filesnapshot class will
161 			// report a file/folder potentially dirty if
162 			// cachedLastReadTime-cachedLastModificationTime < filesystem
163 			// timestamp resolution. This causes JGit to always rescan a file
164 			// after modification. But: this was true only if the difference
165 			// between current system time and cachedLastModification time was
166 			// less than 2500ms. If the modification is more than 2500ms ago we
167 			// may have reported a file/folder to be clean although it has not
168 			// been rescanned. A bug. To show the bug we sleep for more than
169 			// 2500ms
170 			Thread.sleep(2600);
171 
172 			File[] ret = packsFolder.listFiles(
173 					(File dir, String name) -> name.endsWith(".pack"));
174 			assertTrue(ret != null && ret.length == 1);
175 			FS fs = db.getFS();
176 			Assume.assumeTrue(fs.lastModifiedInstant(tmpFile)
177 					.equals(fs.lastModifiedInstant(ret[0])));
178 
179 			// all objects are in a new packfile but we will not detect it
180 			assertFalse(receivingDB.getObjectDatabase().has(unknownID));
181 			assertTrue(receivingDB.getObjectDatabase().has(id2));
182 		}
183 	}
184 
185 	@Test
186 	public void testShallowFile()
187 			throws Exception {
188 		FileRepository repository = createBareRepository();
189 		ObjectDirectory dir = repository.getObjectDatabase();
190 
191 		String commit = "d3148f9410b071edd4a4c85d2a43d1fa2574b0d2";
192 		try (PrintWriter writer = new PrintWriter(
193 				new File(repository.getDirectory(), Constants.SHALLOW),
194 				UTF_8.name())) {
195 			writer.println(commit);
196 		}
197 		Set<ObjectId> shallowCommits = dir.getShallowCommits();
198 		assertTrue(shallowCommits.remove(ObjectId.fromString(commit)));
199 		assertTrue(shallowCommits.isEmpty());
200 	}
201 
202 	@Test
203 	public void testOpenLooseObjectSuppressStaleFileHandleException()
204 			throws Exception {
205 		ObjectId id = ObjectId
206 				.fromString("873fb8d667d05436d728c52b1d7a09528e6eb59b");
207 		WindowCursor curs = new WindowCursor(db.getObjectDatabase());
208 
209 		LooseObjects mock = mock(LooseObjects.class);
210 		UnpackedObjectCache unpackedObjectCacheMock = mock(
211 				UnpackedObjectCache.class);
212 
213 		Mockito.when(mock.getObjectLoader(any(), any(), any()))
214 				.thenThrow(new IOException("Stale File Handle"));
215 		Mockito.when(mock.open(curs, id)).thenCallRealMethod();
216 		Mockito.when(mock.unpackedObjectCache())
217 				.thenReturn(unpackedObjectCacheMock);
218 
219 		assertNull(mock.open(curs, id));
220 		verify(unpackedObjectCacheMock).remove(id);
221 	}
222 
223 	@Test
224 	public void testOpenLooseObjectPropagatesIOExceptions() throws Exception {
225 		ObjectId id = ObjectId
226 				.fromString("873fb8d667d05436d728c52b1d7a09528e6eb59b");
227 		WindowCursor curs = new WindowCursor(db.getObjectDatabase());
228 
229 		LooseObjects mock = mock(LooseObjects.class);
230 
231 		Mockito.when(mock.getObjectLoader(any(), any(), any()))
232 				.thenThrow(new IOException("some IO failure"));
233 		Mockito.when(mock.open(curs, id)).thenCallRealMethod();
234 
235 		assertThrows(IOException.class, () -> mock.open(curs, id));
236 	}
237 
238 	@Test
239 	public void testShallowFileCorrupt() throws Exception {
240 		FileRepository repository = createBareRepository();
241 		ObjectDirectory dir = repository.getObjectDatabase();
242 
243 		String commit = "X3148f9410b071edd4a4c85d2a43d1fa2574b0d2";
244 		try (PrintWriter writer = new PrintWriter(
245 				new File(repository.getDirectory(), Constants.SHALLOW),
246 				UTF_8.name())) {
247 			writer.println(commit);
248 		}
249 		assertThrows(
250 				MessageFormat.format(JGitText.get().badShallowLine, commit),
251 				IOException.class, () -> dir.getShallowCommits());
252 	}
253 
254 	private Collection<Callable<ObjectId>> blobInsertersForTheSameFanOutDir(
255 			final ObjectDirectory dir) {
256 		Callable<ObjectId> callable = () -> dir.newInserter()
257 				.insert(Constants.OBJ_BLOB, new byte[0]);
258 		return Collections.nCopies(4, callable);
259 	}
260 
261 }