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

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