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 8.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. /*
  2. * Copyright (C) 2010, Robin Rosenberg and others
  3. *
  4. * This program and the accompanying materials are made available under the
  5. * terms of the Eclipse Distribution License v. 1.0 which is available at
  6. * https://www.eclipse.org/org/documents/edl-v10.php.
  7. *
  8. * SPDX-License-Identifier: BSD-3-Clause
  9. */
  10. package org.eclipse.jgit.internal.storage.file;
  11. import static org.eclipse.jgit.junit.JGitTestUtil.read;
  12. import static org.eclipse.jgit.junit.JGitTestUtil.write;
  13. import static org.junit.Assert.assertEquals;
  14. import static org.junit.Assert.assertFalse;
  15. import static org.junit.Assert.assertTrue;
  16. import static org.junit.Assert.fail;
  17. import java.io.File;
  18. import java.io.IOException;
  19. import java.io.OutputStream;
  20. import java.nio.file.Files;
  21. import java.nio.file.Path;
  22. import java.nio.file.StandardCopyOption;
  23. import java.nio.file.StandardOpenOption;
  24. import java.nio.file.attribute.FileTime;
  25. import java.time.Duration;
  26. import java.time.Instant;
  27. import java.util.ArrayList;
  28. import java.util.concurrent.TimeUnit;
  29. import org.eclipse.jgit.junit.MockSystemReader;
  30. import org.eclipse.jgit.util.FS;
  31. import org.eclipse.jgit.util.FS.FileStoreAttributes;
  32. import org.eclipse.jgit.util.FileUtils;
  33. import org.eclipse.jgit.util.Stats;
  34. import org.eclipse.jgit.util.SystemReader;
  35. import org.junit.After;
  36. import org.junit.Assume;
  37. import org.junit.Before;
  38. import org.junit.Test;
  39. import org.slf4j.Logger;
  40. import org.slf4j.LoggerFactory;
  41. public class FileSnapshotTest {
  42. private static final Logger LOG = LoggerFactory
  43. .getLogger(FileSnapshotTest.class);
  44. private Path trash;
  45. private FileStoreAttributes fsAttrCache;
  46. @Before
  47. public void setUp() throws Exception {
  48. SystemReader.setInstance(new MockSystemReader());
  49. trash = Files.createTempDirectory("tmp_");
  50. // measure timer resolution before the test to avoid time critical tests
  51. // are affected by time needed for measurement
  52. fsAttrCache = FS
  53. .getFileStoreAttributes(trash.getParent());
  54. }
  55. @Before
  56. @After
  57. public void tearDown() throws Exception {
  58. FileUtils.delete(trash.toFile(),
  59. FileUtils.RECURSIVE | FileUtils.SKIP_MISSING);
  60. }
  61. private static void waitNextTick(Path f) throws IOException {
  62. Instant initialLastModified = FS.DETECTED.lastModifiedInstant(f);
  63. do {
  64. FS.DETECTED.setLastModified(f, Instant.now());
  65. } while (FS.DETECTED.lastModifiedInstant(f)
  66. .equals(initialLastModified));
  67. }
  68. /**
  69. * Change data and time stamp.
  70. *
  71. * @throws Exception
  72. */
  73. @Test
  74. public void testActuallyIsModifiedTrivial() throws Exception {
  75. Path f1 = createFile("simple");
  76. waitNextTick(f1);
  77. FileSnapshot save = FileSnapshot.save(f1.toFile());
  78. append(f1, (byte) 'x');
  79. waitNextTick(f1);
  80. assertTrue(save.isModified(f1.toFile()));
  81. }
  82. /**
  83. * Create a file, but don't wait long enough for the difference between file
  84. * system clock and system clock to be significant. Assume the file may have
  85. * been modified. It may have been, but the clock alone cannot determine
  86. * this
  87. *
  88. * @throws Exception
  89. */
  90. @Test
  91. public void testNewFileWithWait() throws Exception {
  92. // if filesystem timestamp resolution is high the snapshot won't be
  93. // racily clean
  94. Assume.assumeTrue(
  95. fsAttrCache.getFsTimestampResolution()
  96. .compareTo(Duration.ofMillis(10)) > 0);
  97. Path f1 = createFile("newfile");
  98. waitNextTick(f1);
  99. FileSnapshot save = FileSnapshot.save(f1.toFile());
  100. TimeUnit.NANOSECONDS.sleep(
  101. fsAttrCache.getFsTimestampResolution().dividedBy(2).toNanos());
  102. assertTrue(save.isModified(f1.toFile()));
  103. }
  104. /**
  105. * Same as {@link #testNewFileWithWait()} but do not wait at all
  106. *
  107. * @throws Exception
  108. */
  109. @Test
  110. public void testNewFileNoWait() throws Exception {
  111. // if filesystem timestamp resolution is smaller than time needed to
  112. // create a file and FileSnapshot the snapshot won't be racily clean
  113. Assume.assumeTrue(fsAttrCache.getFsTimestampResolution()
  114. .compareTo(Duration.ofMillis(10)) > 0);
  115. for (int i = 0; i < 50; i++) {
  116. Instant start = Instant.now();
  117. Path f1 = createFile("newfile");
  118. FileSnapshot save = FileSnapshot.save(f1.toFile());
  119. Duration res = FS.getFileStoreAttributes(f1)
  120. .getFsTimestampResolution();
  121. Instant end = Instant.now();
  122. if (Duration.between(start, end)
  123. .compareTo(res.multipliedBy(2)) > 0) {
  124. // This test is racy: under load, there may be a delay between createFile() and
  125. // FileSnapshot.save(). This can stretch the time between the read TS and FS
  126. // creation TS to the point that it exceeds the FS granularity, and we
  127. // conclude it cannot be racily clean, and therefore must be really clean.
  128. //
  129. // This should be relatively uncommon.
  130. continue;
  131. }
  132. // The file wasn't really modified, but it looks just like a "maybe racily clean"
  133. // file.
  134. assertTrue(save.isModified(f1.toFile()));
  135. return;
  136. }
  137. fail("too much load for this test");
  138. }
  139. /**
  140. * Simulate packfile replacement in same file which may occur if set of
  141. * objects in the pack is the same but pack config was different. On Posix
  142. * filesystems this should change the inode (filekey in java.nio
  143. * terminology).
  144. *
  145. * @throws Exception
  146. */
  147. @Test
  148. public void testSimulatePackfileReplacement() throws Exception {
  149. Assume.assumeFalse(SystemReader.getInstance().isWindows());
  150. Path f1 = createFile("file"); // inode y
  151. Path f2 = createFile("fool"); // Guarantees new inode x
  152. // wait on f2 since this method resets lastModified of the file
  153. // and leaves lastModified of f1 untouched
  154. waitNextTick(f2);
  155. waitNextTick(f2);
  156. FileTime timestamp = Files.getLastModifiedTime(f1);
  157. FileSnapshot save = FileSnapshot.save(f1.toFile());
  158. Files.move(f2, f1, // Now "file" is inode x
  159. StandardCopyOption.REPLACE_EXISTING,
  160. StandardCopyOption.ATOMIC_MOVE);
  161. Files.setLastModifiedTime(f1, timestamp);
  162. assertTrue(save.isModified(f1.toFile()));
  163. assertTrue("unexpected change of fileKey", save.wasFileKeyChanged());
  164. assertFalse("unexpected size change", save.wasSizeChanged());
  165. assertFalse("unexpected lastModified change",
  166. save.wasLastModifiedChanged());
  167. assertFalse("lastModified was unexpectedly racily clean",
  168. save.wasLastModifiedRacilyClean());
  169. }
  170. /**
  171. * Append a character to a file to change its size and set original
  172. * lastModified
  173. *
  174. * @throws Exception
  175. */
  176. @Test
  177. public void testFileSizeChanged() throws Exception {
  178. Path f = createFile("file");
  179. FileTime timestamp = Files.getLastModifiedTime(f);
  180. FileSnapshot save = FileSnapshot.save(f.toFile());
  181. append(f, (byte) 'x');
  182. Files.setLastModifiedTime(f, timestamp);
  183. assertTrue(save.isModified(f.toFile()));
  184. assertTrue(save.wasSizeChanged());
  185. }
  186. @Test
  187. public void fileSnapshotEquals() throws Exception {
  188. // 0 sized FileSnapshot.
  189. FileSnapshot fs1 = FileSnapshot.MISSING_FILE;
  190. // UNKNOWN_SIZE FileSnapshot.
  191. FileSnapshot fs2 = FileSnapshot.save(fs1.lastModifiedInstant());
  192. assertTrue(fs1.equals(fs2));
  193. assertTrue(fs2.equals(fs1));
  194. }
  195. @SuppressWarnings("boxing")
  196. @Test
  197. public void detectFileModified() throws IOException {
  198. int failures = 0;
  199. long racyNanos = 0;
  200. final int COUNT = 10000;
  201. ArrayList<Long> deltas = new ArrayList<>();
  202. File f = createFile("test").toFile();
  203. for (int i = 0; i < COUNT; i++) {
  204. write(f, "a");
  205. FileSnapshot snapshot = FileSnapshot.save(f);
  206. assertEquals("file should contain 'a'", "a", read(f));
  207. write(f, "b");
  208. if (!snapshot.isModified(f)) {
  209. deltas.add(snapshot.lastDelta());
  210. racyNanos = snapshot.lastRacyThreshold();
  211. failures++;
  212. }
  213. assertEquals("file should contain 'b'", "b", read(f));
  214. }
  215. if (failures > 0) {
  216. Stats stats = new Stats();
  217. LOG.debug(
  218. "delta [ns] since modification FileSnapshot failed to detect");
  219. for (Long d : deltas) {
  220. stats.add(d);
  221. LOG.debug(String.format("%,d", d));
  222. }
  223. LOG.error(
  224. "count, failures, eff. racy threshold [ns], delta min [ns],"
  225. + " delta max [ns], delta avg [ns],"
  226. + " delta stddev [ns]");
  227. LOG.error(String.format(
  228. "%,d, %,d, %,d, %,.0f, %,.0f, %,.0f, %,.0f", COUNT,
  229. failures, racyNanos, stats.min(), stats.max(),
  230. stats.avg(), stats.stddev()));
  231. }
  232. assertTrue(
  233. String.format(
  234. "FileSnapshot: failures to detect file modifications"
  235. + " %d out of %d\n"
  236. + "timestamp resolution %d µs"
  237. + " min racy threshold %d µs"
  238. , failures, COUNT,
  239. fsAttrCache.getFsTimestampResolution().toNanos() / 1000,
  240. fsAttrCache.getMinimalRacyInterval().toNanos() / 1000),
  241. failures == 0);
  242. }
  243. private Path createFile(String string) throws IOException {
  244. Files.createDirectories(trash);
  245. return Files.createTempFile(trash, string, "tdat");
  246. }
  247. private static void append(Path f, byte b) throws IOException {
  248. try (OutputStream os = Files.newOutputStream(f,
  249. StandardOpenOption.APPEND)) {
  250. os.write(b);
  251. }
  252. }
  253. }