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