View Javadoc
1   /*
2    * Copyright (C) 2010, Google Inc.
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  
44  package org.eclipse.jgit.internal.storage.file;
45  
46  import java.io.File;
47  import java.io.IOException;
48  import java.text.DateFormat;
49  import java.text.SimpleDateFormat;
50  import java.util.Date;
51  import java.util.Locale;
52  
53  import org.eclipse.jgit.util.FS;
54  
55  /**
56   * Caches when a file was last read, making it possible to detect future edits.
57   * <p>
58   * This object tracks the last modified time of a file. Later during an
59   * invocation of {@link #isModified(File)} the object will return true if the
60   * file may have been modified and should be re-read from disk.
61   * <p>
62   * A snapshot does not "live update" when the underlying filesystem changes.
63   * Callers must poll for updates by periodically invoking
64   * {@link #isModified(File)}.
65   * <p>
66   * To work around the "racy git" problem (where a file may be modified multiple
67   * times within the granularity of the filesystem modification clock) this class
68   * may return true from isModified(File) if the last modification time of the
69   * file is less than 3 seconds ago.
70   */
71  public class FileSnapshot {
72  	/**
73  	 * A FileSnapshot that is considered to always be modified.
74  	 * <p>
75  	 * This instance is useful for application code that wants to lazily read a
76  	 * file, but only after {@link #isModified(File)} gets invoked. The returned
77  	 * snapshot contains only invalid status information.
78  	 */
79  	public static final FileSnapshot DIRTY = new FileSnapshot(-1, -1);
80  
81  	/**
82  	 * A FileSnapshot that is clean if the file does not exist.
83  	 * <p>
84  	 * This instance is useful if the application wants to consider a missing
85  	 * file to be clean. {@link #isModified(File)} will return false if the file
86  	 * path does not exist.
87  	 */
88  	public static final FileSnapshot MISSING_FILE = new FileSnapshot(0, 0) {
89  		@Override
90  		public boolean isModified(File path) {
91  			return FS.DETECTED.exists(path);
92  		}
93  	};
94  
95  	/**
96  	 * Record a snapshot for a specific file path.
97  	 * <p>
98  	 * This method should be invoked before the file is accessed.
99  	 *
100 	 * @param path
101 	 *            the path to later remember. The path's current status
102 	 *            information is saved.
103 	 * @return the snapshot.
104 	 */
105 	public static FileSnapshot save(File path) {
106 		long read = System.currentTimeMillis();
107 		long modified;
108 		try {
109 			modified = FS.DETECTED.lastModified(path);
110 		} catch (IOException e) {
111 			modified = path.lastModified();
112 		}
113 		return new FileSnapshot(read, modified);
114 	}
115 
116 	/**
117 	 * Record a snapshot for a file for which the last modification time is
118 	 * already known.
119 	 * <p>
120 	 * This method should be invoked before the file is accessed.
121 	 *
122 	 * @param modified
123 	 *            the last modification time of the file
124 	 * @return the snapshot.
125 	 */
126 	public static FileSnapshot save(long modified) {
127 		final long read = System.currentTimeMillis();
128 		return new FileSnapshot(read, modified);
129 	}
130 
131 	/** Last observed modification time of the path. */
132 	private final long lastModified;
133 
134 	/** Last wall-clock time the path was read. */
135 	private volatile long lastRead;
136 
137 	/** True once {@link #lastRead} is far later than {@link #lastModified}. */
138 	private boolean cannotBeRacilyClean;
139 
140 	private FileSnapshot(long read, long modified) {
141 		this.lastRead = read;
142 		this.lastModified = modified;
143 		this.cannotBeRacilyClean = notRacyClean(read);
144 	}
145 
146 	/**
147 	 * Get time of last snapshot update
148 	 *
149 	 * @return time of last snapshot update
150 	 */
151 	public long lastModified() {
152 		return lastModified;
153 	}
154 
155 	/**
156 	 * Check if the path may have been modified since the snapshot was saved.
157 	 *
158 	 * @param path
159 	 *            the path the snapshot describes.
160 	 * @return true if the path needs to be read again.
161 	 */
162 	public boolean isModified(File path) {
163 		long currLastModified;
164 		try {
165 			currLastModified = FS.DETECTED.lastModified(path);
166 		} catch (IOException e) {
167 			currLastModified = path.lastModified();
168 		}
169 		return isModified(currLastModified);
170 	}
171 
172 	/**
173 	 * Update this snapshot when the content hasn't changed.
174 	 * <p>
175 	 * If the caller gets true from {@link #isModified(File)}, re-reads the
176 	 * content, discovers the content is identical, and
177 	 * {@link #equals(FileSnapshot)} is true, it can use
178 	 * {@link #setClean(FileSnapshot)} to make a future
179 	 * {@link #isModified(File)} return false. The logic goes something like
180 	 * this:
181 	 *
182 	 * <pre>
183 	 * if (snapshot.isModified(path)) {
184 	 *  FileSnapshot other = FileSnapshot.save(path);
185 	 *  Content newContent = ...;
186 	 *  if (oldContent.equals(newContent) &amp;&amp; snapshot.equals(other))
187 	 *      snapshot.setClean(other);
188 	 * }
189 	 * </pre>
190 	 *
191 	 * @param other
192 	 *            the other snapshot.
193 	 */
194 	public void setClean(FileSnapshot other) {
195 		final long now = other.lastRead;
196 		if (notRacyClean(now))
197 			cannotBeRacilyClean = true;
198 		lastRead = now;
199 	}
200 
201 	/**
202 	 * Compare two snapshots to see if they cache the same information.
203 	 *
204 	 * @param other
205 	 *            the other snapshot.
206 	 * @return true if the two snapshots share the same information.
207 	 */
208 	public boolean equals(FileSnapshot other) {
209 		return lastModified == other.lastModified;
210 	}
211 
212 	/** {@inheritDoc} */
213 	@Override
214 	public boolean equals(Object other) {
215 		if (other instanceof FileSnapshot)
216 			return equals((FileSnapshot) other);
217 		return false;
218 	}
219 
220 	/** {@inheritDoc} */
221 	@Override
222 	public int hashCode() {
223 		// This is pretty pointless, but override hashCode to ensure that
224 		// x.hashCode() == y.hashCode() when x.equals(y) is true.
225 		//
226 		return (int) lastModified;
227 	}
228 
229 	/** {@inheritDoc} */
230 	@Override
231 	public String toString() {
232 		if (this == DIRTY)
233 			return "DIRTY"; //$NON-NLS-1$
234 		if (this == MISSING_FILE)
235 			return "MISSING_FILE"; //$NON-NLS-1$
236 		DateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", //$NON-NLS-1$
237 				Locale.US);
238 		return "FileSnapshot[modified: " + f.format(new Date(lastModified)) //$NON-NLS-1$
239 				+ ", read: " + f.format(new Date(lastRead)) + "]"; //$NON-NLS-1$ //$NON-NLS-2$
240 	}
241 
242 	private boolean notRacyClean(long read) {
243 		// The last modified time granularity of FAT filesystems is 2 seconds.
244 		// Using 2.5 seconds here provides a reasonably high assurance that
245 		// a modification was not missed.
246 		//
247 		return read - lastModified > 2500;
248 	}
249 
250 	private boolean isModified(long currLastModified) {
251 		// Any difference indicates the path was modified.
252 		//
253 		if (lastModified != currLastModified)
254 			return true;
255 
256 		// We have already determined the last read was far enough
257 		// after the last modification that any new modifications
258 		// are certain to change the last modified time.
259 		//
260 		if (cannotBeRacilyClean)
261 			return false;
262 
263 		if (notRacyClean(lastRead)) {
264 			// Our last read should have marked cannotBeRacilyClean,
265 			// but this thread may not have seen the change. The read
266 			// of the volatile field lastRead should have fixed that.
267 			//
268 			return false;
269 		}
270 
271 		// We last read this path too close to its last observed
272 		// modification time. We may have missed a modification.
273 		// Scan again, to ensure we still see the same state.
274 		//
275 		return true;
276 	}
277 }