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.

FileSnapshotTest.java 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. /*
  2. * Copyright (C) 2010, Robin Rosenberg
  3. * and other copyright owners as documented in the project's IP log.
  4. *
  5. * This program and the accompanying materials are made available
  6. * under the terms of the Eclipse Distribution License v1.0 which
  7. * accompanies this distribution, is reproduced below, and is
  8. * available at http://www.eclipse.org/org/documents/edl-v10.php
  9. *
  10. * All rights reserved.
  11. *
  12. * Redistribution and use in source and binary forms, with or
  13. * without modification, are permitted provided that the following
  14. * conditions are met:
  15. *
  16. * - Redistributions of source code must retain the above copyright
  17. * notice, this list of conditions and the following disclaimer.
  18. *
  19. * - Redistributions in binary form must reproduce the above
  20. * copyright notice, this list of conditions and the following
  21. * disclaimer in the documentation and/or other materials provided
  22. * with the distribution.
  23. *
  24. * - Neither the name of the Eclipse Foundation, Inc. nor the
  25. * names of its contributors may be used to endorse or promote
  26. * products derived from this software without specific prior
  27. * written permission.
  28. *
  29. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  30. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  31. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  32. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  33. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  34. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  35. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  36. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  37. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  38. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  39. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  40. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  41. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  42. */
  43. package org.eclipse.jgit.internal.storage.file;
  44. import static org.eclipse.jgit.junit.JGitTestUtil.read;
  45. import static org.eclipse.jgit.junit.JGitTestUtil.write;
  46. import static org.junit.Assert.assertEquals;
  47. import static org.junit.Assert.assertFalse;
  48. import static org.junit.Assert.assertTrue;
  49. import static org.junit.Assert.fail;
  50. import java.io.File;
  51. import java.io.IOException;
  52. import java.io.OutputStream;
  53. import java.nio.file.Files;
  54. import java.nio.file.Path;
  55. import java.nio.file.StandardCopyOption;
  56. import java.nio.file.StandardOpenOption;
  57. import java.nio.file.attribute.FileTime;
  58. import java.time.Duration;
  59. import java.time.Instant;
  60. import java.util.ArrayList;
  61. import java.util.concurrent.TimeUnit;
  62. import org.eclipse.jgit.junit.MockSystemReader;
  63. import org.eclipse.jgit.util.FS;
  64. import org.eclipse.jgit.util.FS.FileStoreAttributes;
  65. import org.eclipse.jgit.util.FileUtils;
  66. import org.eclipse.jgit.util.Stats;
  67. import org.eclipse.jgit.util.SystemReader;
  68. import org.junit.After;
  69. import org.junit.Assume;
  70. import org.junit.Before;
  71. import org.junit.Test;
  72. import org.slf4j.Logger;
  73. import org.slf4j.LoggerFactory;
  74. public class FileSnapshotTest {
  75. private static final Logger LOG = LoggerFactory
  76. .getLogger(FileSnapshotTest.class);
  77. private Path trash;
  78. private FileStoreAttributes fsAttrCache;
  79. @Before
  80. public void setUp() throws Exception {
  81. SystemReader.setInstance(new MockSystemReader());
  82. trash = Files.createTempDirectory("tmp_");
  83. // measure timer resolution before the test to avoid time critical tests
  84. // are affected by time needed for measurement
  85. fsAttrCache = FS
  86. .getFileStoreAttributes(trash.getParent());
  87. }
  88. @Before
  89. @After
  90. public void tearDown() throws Exception {
  91. FileUtils.delete(trash.toFile(),
  92. FileUtils.RECURSIVE | FileUtils.SKIP_MISSING);
  93. }
  94. private static void waitNextTick(Path f) throws IOException {
  95. Instant initialLastModified = FS.DETECTED.lastModifiedInstant(f);
  96. do {
  97. FS.DETECTED.setLastModified(f, Instant.now());
  98. } while (FS.DETECTED.lastModifiedInstant(f)
  99. .equals(initialLastModified));
  100. }
  101. /**
  102. * Change data and time stamp.
  103. *
  104. * @throws Exception
  105. */
  106. @Test
  107. public void testActuallyIsModifiedTrivial() throws Exception {
  108. Path f1 = createFile("simple");
  109. waitNextTick(f1);
  110. FileSnapshot save = FileSnapshot.save(f1.toFile());
  111. append(f1, (byte) 'x');
  112. waitNextTick(f1);
  113. assertTrue(save.isModified(f1.toFile()));
  114. }
  115. /**
  116. * Create a file, but don't wait long enough for the difference between file
  117. * system clock and system clock to be significant. Assume the file may have
  118. * been modified. It may have been, but the clock alone cannot determine
  119. * this
  120. *
  121. * @throws Exception
  122. */
  123. @Test
  124. public void testNewFileWithWait() throws Exception {
  125. // if filesystem timestamp resolution is high the snapshot won't be
  126. // racily clean
  127. Assume.assumeTrue(
  128. fsAttrCache.getFsTimestampResolution()
  129. .compareTo(Duration.ofMillis(10)) > 0);
  130. Path f1 = createFile("newfile");
  131. waitNextTick(f1);
  132. FileSnapshot save = FileSnapshot.save(f1.toFile());
  133. TimeUnit.NANOSECONDS.sleep(
  134. fsAttrCache.getFsTimestampResolution().dividedBy(2).toNanos());
  135. assertTrue(save.isModified(f1.toFile()));
  136. }
  137. /**
  138. * Same as {@link #testNewFileWithWait()} but do not wait at all
  139. *
  140. * @throws Exception
  141. */
  142. @Test
  143. public void testNewFileNoWait() throws Exception {
  144. // if filesystem timestamp resolution is smaller than time needed to
  145. // create a file and FileSnapshot the snapshot won't be racily clean
  146. Assume.assumeTrue(fsAttrCache.getFsTimestampResolution()
  147. .compareTo(Duration.ofMillis(10)) > 0);
  148. for (int i = 0; i < 50; i++) {
  149. Instant start = Instant.now();
  150. Path f1 = createFile("newfile");
  151. FileSnapshot save = FileSnapshot.save(f1.toFile());
  152. Duration res = FS.getFileStoreAttributes(f1)
  153. .getFsTimestampResolution();
  154. Instant end = Instant.now();
  155. if (Duration.between(start, end)
  156. .compareTo(res.multipliedBy(2)) > 0) {
  157. // This test is racy: under load, there may be a delay between createFile() and
  158. // FileSnapshot.save(). This can stretch the time between the read TS and FS
  159. // creation TS to the point that it exceeds the FS granularity, and we
  160. // conclude it cannot be racily clean, and therefore must be really clean.
  161. //
  162. // This should be relatively uncommon.
  163. continue;
  164. }
  165. // The file wasn't really modified, but it looks just like a "maybe racily clean"
  166. // file.
  167. assertTrue(save.isModified(f1.toFile()));
  168. return;
  169. }
  170. fail("too much load for this test");
  171. }
  172. /**
  173. * Simulate packfile replacement in same file which may occur if set of
  174. * objects in the pack is the same but pack config was different. On Posix
  175. * filesystems this should change the inode (filekey in java.nio
  176. * terminology).
  177. *
  178. * @throws Exception
  179. */
  180. @Test
  181. public void testSimulatePackfileReplacement() throws Exception {
  182. Assume.assumeFalse(SystemReader.getInstance().isWindows());
  183. Path f1 = createFile("file"); // inode y
  184. Path f2 = createFile("fool"); // Guarantees new inode x
  185. // wait on f2 since this method resets lastModified of the file
  186. // and leaves lastModified of f1 untouched
  187. waitNextTick(f2);
  188. waitNextTick(f2);
  189. FileTime timestamp = Files.getLastModifiedTime(f1);
  190. FileSnapshot save = FileSnapshot.save(f1.toFile());
  191. Files.move(f2, f1, // Now "file" is inode x
  192. StandardCopyOption.REPLACE_EXISTING,
  193. StandardCopyOption.ATOMIC_MOVE);
  194. Files.setLastModifiedTime(f1, timestamp);
  195. assertTrue(save.isModified(f1.toFile()));
  196. assertTrue("unexpected change of fileKey", save.wasFileKeyChanged());
  197. assertFalse("unexpected size change", save.wasSizeChanged());
  198. assertFalse("unexpected lastModified change",
  199. save.wasLastModifiedChanged());
  200. assertFalse("lastModified was unexpectedly racily clean",
  201. save.wasLastModifiedRacilyClean());
  202. }
  203. /**
  204. * Append a character to a file to change its size and set original
  205. * lastModified
  206. *
  207. * @throws Exception
  208. */
  209. @Test
  210. public void testFileSizeChanged() throws Exception {
  211. Path f = createFile("file");
  212. FileTime timestamp = Files.getLastModifiedTime(f);
  213. FileSnapshot save = FileSnapshot.save(f.toFile());
  214. append(f, (byte) 'x');
  215. Files.setLastModifiedTime(f, timestamp);
  216. assertTrue(save.isModified(f.toFile()));
  217. assertTrue(save.wasSizeChanged());
  218. }
  219. @Test
  220. public void fileSnapshotEquals() throws Exception {
  221. // 0 sized FileSnapshot.
  222. FileSnapshot fs1 = FileSnapshot.MISSING_FILE;
  223. // UNKNOWN_SIZE FileSnapshot.
  224. FileSnapshot fs2 = FileSnapshot.save(fs1.lastModifiedInstant());
  225. assertTrue(fs1.equals(fs2));
  226. assertTrue(fs2.equals(fs1));
  227. }
  228. @SuppressWarnings("boxing")
  229. @Test
  230. public void detectFileModified() throws IOException {
  231. int failures = 0;
  232. long racyNanos = 0;
  233. final int COUNT = 10000;
  234. ArrayList<Long> deltas = new ArrayList<>();
  235. File f = createFile("test").toFile();
  236. for (int i = 0; i < COUNT; i++) {
  237. write(f, "a");
  238. FileSnapshot snapshot = FileSnapshot.save(f);
  239. assertEquals("file should contain 'a'", "a", read(f));
  240. write(f, "b");
  241. if (!snapshot.isModified(f)) {
  242. deltas.add(snapshot.lastDelta());
  243. racyNanos = snapshot.lastRacyThreshold();
  244. failures++;
  245. }
  246. assertEquals("file should contain 'b'", "b", read(f));
  247. }
  248. if (failures > 0) {
  249. Stats stats = new Stats();
  250. LOG.debug(
  251. "delta [ns] since modification FileSnapshot failed to detect");
  252. for (Long d : deltas) {
  253. stats.add(d);
  254. LOG.debug(String.format("%,d", d));
  255. }
  256. LOG.error(
  257. "count, failures, eff. racy threshold [ns], delta min [ns],"
  258. + " delta max [ns], delta avg [ns],"
  259. + " delta stddev [ns]");
  260. LOG.error(String.format(
  261. "%,d, %,d, %,d, %,.0f, %,.0f, %,.0f, %,.0f", COUNT,
  262. failures, racyNanos, stats.min(), stats.max(),
  263. stats.avg(), stats.stddev()));
  264. }
  265. assertTrue(
  266. String.format(
  267. "FileSnapshot: failures to detect file modifications"
  268. + " %d out of %d\n"
  269. + "timestamp resolution %d µs"
  270. + " min racy threshold %d µs"
  271. , failures, COUNT,
  272. fsAttrCache.getFsTimestampResolution().toNanos() / 1000,
  273. fsAttrCache.getMinimalRacyInterval().toNanos() / 1000),
  274. failures == 0);
  275. }
  276. private Path createFile(String string) throws IOException {
  277. Files.createDirectories(trash);
  278. return Files.createTempFile(trash, string, "tdat");
  279. }
  280. private static void append(Path f, byte b) throws IOException {
  281. try (OutputStream os = Files.newOutputStream(f,
  282. StandardOpenOption.APPEND)) {
  283. os.write(b);
  284. }
  285. }
  286. }