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 	 *
125 	 * @return the snapshot.
126 	 */
127 	public static FileSnapshot save(long modified) {
128 		final long read = System.currentTimeMillis();
129 		return new FileSnapshot(read, modified);
130 	}
131 
132 	/** Last observed modification time of the path. */
133 	private final long lastModified;
134 
135 	/** Last wall-clock time the path was read. */
136 	private volatile long lastRead;
137 
138 	/** True once {@link #lastRead} is far later than {@link #lastModified}. */
139 	private boolean cannotBeRacilyClean;
140 
141 	private FileSnapshot(long read, long modified) {
142 		this.lastRead = read;
143 		this.lastModified = modified;
144 		this.cannotBeRacilyClean = notRacyClean(read);
145 	}
146 
147 	/**
148 	 * @return time of last snapshot update
149 	 */
150 	public long lastModified() {
151 		return lastModified;
152 	}
153 
154 	/**
155 	 * Check if the path may have been modified since the snapshot was saved.
156 	 *
157 	 * @param path
158 	 *            the path the snapshot describes.
159 	 * @return true if the path needs to be read again.
160 	 */
161 	public boolean isModified(File path) {
162 		long currLastModified;
163 		try {
164 			currLastModified = FS.DETECTED.lastModified(path);
165 		} catch (IOException e) {
166 			currLastModified = path.lastModified();
167 		}
168 		return isModified(currLastModified);
169 	}
170 
171 	/**
172 	 * Update this snapshot when the content hasn't changed.
173 	 * <p>
174 	 * If the caller gets true from {@link #isModified(File)}, re-reads the
175 	 * content, discovers the content is identical, and
176 	 * {@link #equals(FileSnapshot)} is true, it can use
177 	 * {@link #setClean(FileSnapshot)} to make a future
178 	 * {@link #isModified(File)} return false. The logic goes something like
179 	 * this:
180 	 *
181 	 * <pre>
182 	 * if (snapshot.isModified(path)) {
183 	 *  FileSnapshot other = FileSnapshot.save(path);
184 	 *  Content newContent = ...;
185 	 *  if (oldContent.equals(newContent) &amp;&amp; snapshot.equals(other))
186 	 *      snapshot.setClean(other);
187 	 * }
188 	 * </pre>
189 	 *
190 	 * @param other
191 	 *            the other snapshot.
192 	 */
193 	public void setClean(FileSnapshot other) {
194 		final long now = other.lastRead;
195 		if (notRacyClean(now))
196 			cannotBeRacilyClean = true;
197 		lastRead = now;
198 	}
199 
200 	/**
201 	 * Compare two snapshots to see if they cache the same information.
202 	 *
203 	 * @param other
204 	 *            the other snapshot.
205 	 * @return true if the two snapshots share the same information.
206 	 */
207 	public boolean equals(FileSnapshot other) {
208 		return lastModified == other.lastModified;
209 	}
210 
211 	@Override
212 	public boolean equals(Object other) {
213 		if (other instanceof FileSnapshot)
214 			return equals((FileSnapshot) other);
215 		return false;
216 	}
217 
218 	@Override
219 	public int hashCode() {
220 		// This is pretty pointless, but override hashCode to ensure that
221 		// x.hashCode() == y.hashCode() when x.equals(y) is true.
222 		//
223 		return (int) lastModified;
224 	}
225 
226 	@Override
227 	public String toString() {
228 		if (this == DIRTY)
229 			return "DIRTY"; //$NON-NLS-1$
230 		if (this == MISSING_FILE)
231 			return "MISSING_FILE"; //$NON-NLS-1$
232 		DateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", //$NON-NLS-1$
233 				Locale.US);
234 		return "FileSnapshot[modified: " + f.format(new Date(lastModified)) //$NON-NLS-1$
235 				+ ", read: " + f.format(new Date(lastRead)) + "]"; //$NON-NLS-1$ //$NON-NLS-2$
236 	}
237 
238 	private boolean notRacyClean(final long read) {
239 		// The last modified time granularity of FAT filesystems is 2 seconds.
240 		// Using 2.5 seconds here provides a reasonably high assurance that
241 		// a modification was not missed.
242 		//
243 		return read - lastModified > 2500;
244 	}
245 
246 	private boolean isModified(final long currLastModified) {
247 		// Any difference indicates the path was modified.
248 		//
249 		if (lastModified != currLastModified)
250 			return true;
251 
252 		// We have already determined the last read was far enough
253 		// after the last modification that any new modifications
254 		// are certain to change the last modified time.
255 		//
256 		if (cannotBeRacilyClean)
257 			return false;
258 
259 		if (notRacyClean(lastRead)) {
260 			// Our last read should have marked cannotBeRacilyClean,
261 			// but this thread may not have seen the change. The read
262 			// of the volatile field lastRead should have fixed that.
263 			//
264 			return false;
265 		}
266 
267 		// We last read this path too close to its last observed
268 		// modification time. We may have missed a modification.
269 		// Scan again, to ensure we still see the same state.
270 		//
271 		return true;
272 	}
273 }