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