View Javadoc
1   /*
2    * Copyright (C) 2007, Robin Rosenberg <robin.rosenberg@dewire.com>
3    * Copyright (C) 2006-2008, Shawn O. Pearce <spearce@spearce.org>
4    * and other copyright owners as documented in the project's IP log.
5    *
6    * This program and the accompanying materials are made available
7    * under the terms of the Eclipse Distribution License v1.0 which
8    * accompanies this distribution, is reproduced below, and is
9    * available at http://www.eclipse.org/org/documents/edl-v10.php
10   *
11   * All rights reserved.
12   *
13   * Redistribution and use in source and binary forms, with or
14   * without modification, are permitted provided that the following
15   * conditions are met:
16   *
17   * - Redistributions of source code must retain the above copyright
18   *   notice, this list of conditions and the following disclaimer.
19   *
20   * - Redistributions in binary form must reproduce the above
21   *   copyright notice, this list of conditions and the following
22   *   disclaimer in the documentation and/or other materials provided
23   *   with the distribution.
24   *
25   * - Neither the name of the Eclipse Foundation, Inc. nor the
26   *   names of its contributors may be used to endorse or promote
27   *   products derived from this software without specific prior
28   *   written permission.
29   *
30   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
31   * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
32   * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
33   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
34   * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
35   * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
36   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
37   * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
38   * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
39   * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
40   * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
41   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
42   * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
43   */
44  
45  package org.eclipse.jgit.internal.storage.file;
46  
47  import static org.eclipse.jgit.lib.Constants.LOCK_SUFFIX;
48  
49  import java.io.File;
50  import java.io.FileInputStream;
51  import java.io.FileNotFoundException;
52  import java.io.FileOutputStream;
53  import java.io.FilenameFilter;
54  import java.io.IOException;
55  import java.io.OutputStream;
56  import java.nio.ByteBuffer;
57  import java.nio.channels.Channels;
58  import java.nio.channels.FileChannel;
59  import java.nio.file.Files;
60  import java.nio.file.StandardCopyOption;
61  import java.nio.file.attribute.FileTime;
62  import java.text.MessageFormat;
63  import java.time.Instant;
64  import java.util.concurrent.TimeUnit;
65  
66  import org.eclipse.jgit.internal.JGitText;
67  import org.eclipse.jgit.lib.Constants;
68  import org.eclipse.jgit.lib.ObjectId;
69  import org.eclipse.jgit.util.FS;
70  import org.eclipse.jgit.util.FS.LockToken;
71  import org.eclipse.jgit.util.FileUtils;
72  import org.slf4j.Logger;
73  import org.slf4j.LoggerFactory;
74  
75  /**
76   * Git style file locking and replacement.
77   * <p>
78   * To modify a ref file Git tries to use an atomic update approach: we write the
79   * new data into a brand new file, then rename it in place over the old name.
80   * This way we can just delete the temporary file if anything goes wrong, and
81   * nothing has been damaged. To coordinate access from multiple processes at
82   * once Git tries to atomically create the new temporary file under a well-known
83   * name.
84   */
85  public class LockFile {
86  	private final static Logger LOG = LoggerFactory.getLogger(LockFile.class);
87  
88  	/**
89  	 * Unlock the given file.
90  	 * <p>
91  	 * This method can be used for recovering from a thrown
92  	 * {@link org.eclipse.jgit.errors.LockFailedException} . This method does
93  	 * not validate that the lock is or is not currently held before attempting
94  	 * to unlock it.
95  	 *
96  	 * @param file
97  	 *            a {@link java.io.File} object.
98  	 * @return true if unlocked, false if unlocking failed
99  	 */
100 	public static boolean unlock(File file) {
101 		final File lockFile = getLockFile(file);
102 		final int flags = FileUtils.RETRY | FileUtils.SKIP_MISSING;
103 		try {
104 			FileUtils.delete(lockFile, flags);
105 		} catch (IOException ignored) {
106 			// Ignore and return whether lock file still exists
107 		}
108 		return !lockFile.exists();
109 	}
110 
111 	/**
112 	 * Get the lock file corresponding to the given file.
113 	 *
114 	 * @param file
115 	 * @return lock file
116 	 */
117 	static File getLockFile(File file) {
118 		return new File(file.getParentFile(),
119 				file.getName() + LOCK_SUFFIX);
120 	}
121 
122 	/** Filter to skip over active lock files when listing a directory. */
123 	static final FilenameFilter FILTER = (File dir,
124 			String name) -> !name.endsWith(LOCK_SUFFIX);
125 
126 	private final File ref;
127 
128 	private final File lck;
129 
130 	private boolean haveLck;
131 
132 	FileOutputStream os;
133 
134 	private boolean needSnapshot;
135 
136 	boolean fsync;
137 
138 	private FileSnapshot commitSnapshot;
139 
140 	private LockToken token;
141 
142 	/**
143 	 * Create a new lock for any file.
144 	 *
145 	 * @param f
146 	 *            the file that will be locked.
147 	 */
148 	public LockFile(File f) {
149 		ref = f;
150 		lck = getLockFile(ref);
151 	}
152 
153 	/**
154 	 * Try to establish the lock.
155 	 *
156 	 * @return true if the lock is now held by the caller; false if it is held
157 	 *         by someone else.
158 	 * @throws java.io.IOException
159 	 *             the temporary output file could not be created. The caller
160 	 *             does not hold the lock.
161 	 */
162 	public boolean lock() throws IOException {
163 		FileUtils.mkdirs(lck.getParentFile(), true);
164 		try {
165 			token = FS.DETECTED.createNewFileAtomic(lck);
166 		} catch (IOException e) {
167 			LOG.error(JGitText.get().failedCreateLockFile, lck, e);
168 			throw e;
169 		}
170 		if (token.isCreated()) {
171 			haveLck = true;
172 			try {
173 				os = new FileOutputStream(lck);
174 			} catch (IOException ioe) {
175 				unlock();
176 				throw ioe;
177 			}
178 		} else {
179 			closeToken();
180 		}
181 		return haveLck;
182 	}
183 
184 	/**
185 	 * Try to establish the lock for appending.
186 	 *
187 	 * @return true if the lock is now held by the caller; false if it is held
188 	 *         by someone else.
189 	 * @throws java.io.IOException
190 	 *             the temporary output file could not be created. The caller
191 	 *             does not hold the lock.
192 	 */
193 	public boolean lockForAppend() throws IOException {
194 		if (!lock())
195 			return false;
196 		copyCurrentContent();
197 		return true;
198 	}
199 
200 	/**
201 	 * Copy the current file content into the temporary file.
202 	 * <p>
203 	 * This method saves the current file content by inserting it into the
204 	 * temporary file, so that the caller can safely append rather than replace
205 	 * the primary file.
206 	 * <p>
207 	 * This method does nothing if the current file does not exist, or exists
208 	 * but is empty.
209 	 *
210 	 * @throws java.io.IOException
211 	 *             the temporary file could not be written, or a read error
212 	 *             occurred while reading from the current file. The lock is
213 	 *             released before throwing the underlying IO exception to the
214 	 *             caller.
215 	 * @throws java.lang.RuntimeException
216 	 *             the temporary file could not be written. The lock is released
217 	 *             before throwing the underlying exception to the caller.
218 	 */
219 	public void copyCurrentContent() throws IOException {
220 		requireLock();
221 		try {
222 			try (FileInputStream fis = new FileInputStream(ref)) {
223 				if (fsync) {
224 					FileChannel in = fis.getChannel();
225 					long pos = 0;
226 					long cnt = in.size();
227 					while (0 < cnt) {
228 						long r = os.getChannel().transferFrom(in, pos, cnt);
229 						pos += r;
230 						cnt -= r;
231 					}
232 				} else {
233 					final byte[] buf = new byte[2048];
234 					int r;
235 					while ((r = fis.read(buf)) >= 0)
236 						os.write(buf, 0, r);
237 				}
238 			}
239 		} catch (FileNotFoundException fnfe) {
240 			if (ref.exists()) {
241 				unlock();
242 				throw fnfe;
243 			}
244 			// Don't worry about a file that doesn't exist yet, it
245 			// conceptually has no current content to copy.
246 			//
247 		} catch (IOException | RuntimeException | Error ioe) {
248 			unlock();
249 			throw ioe;
250 		}
251 	}
252 
253 	/**
254 	 * Write an ObjectId and LF to the temporary file.
255 	 *
256 	 * @param id
257 	 *            the id to store in the file. The id will be written in hex,
258 	 *            followed by a sole LF.
259 	 * @throws java.io.IOException
260 	 *             the temporary file could not be written. The lock is released
261 	 *             before throwing the underlying IO exception to the caller.
262 	 * @throws java.lang.RuntimeException
263 	 *             the temporary file could not be written. The lock is released
264 	 *             before throwing the underlying exception to the caller.
265 	 */
266 	public void write(ObjectId id) throws IOException {
267 		byte[] buf = new byte[Constants.OBJECT_ID_STRING_LENGTH + 1];
268 		id.copyTo(buf, 0);
269 		buf[Constants.OBJECT_ID_STRING_LENGTH] = '\n';
270 		write(buf);
271 	}
272 
273 	/**
274 	 * Write arbitrary data to the temporary file.
275 	 *
276 	 * @param content
277 	 *            the bytes to store in the temporary file. No additional bytes
278 	 *            are added, so if the file must end with an LF it must appear
279 	 *            at the end of the byte array.
280 	 * @throws java.io.IOException
281 	 *             the temporary file could not be written. The lock is released
282 	 *             before throwing the underlying IO exception to the caller.
283 	 * @throws java.lang.RuntimeException
284 	 *             the temporary file could not be written. The lock is released
285 	 *             before throwing the underlying exception to the caller.
286 	 */
287 	public void write(byte[] content) throws IOException {
288 		requireLock();
289 		try {
290 			if (fsync) {
291 				FileChannel fc = os.getChannel();
292 				ByteBuffer buf = ByteBuffer.wrap(content);
293 				while (0 < buf.remaining())
294 					fc.write(buf);
295 				fc.force(true);
296 			} else {
297 				os.write(content);
298 			}
299 			os.close();
300 			os = null;
301 		} catch (IOException | RuntimeException | Error ioe) {
302 			unlock();
303 			throw ioe;
304 		}
305 	}
306 
307 	/**
308 	 * Obtain the direct output stream for this lock.
309 	 * <p>
310 	 * The stream may only be accessed once, and only after {@link #lock()} has
311 	 * been successfully invoked and returned true. Callers must close the
312 	 * stream prior to calling {@link #commit()} to commit the change.
313 	 *
314 	 * @return a stream to write to the new file. The stream is unbuffered.
315 	 */
316 	public OutputStream getOutputStream() {
317 		requireLock();
318 
319 		final OutputStream out;
320 		if (fsync)
321 			out = Channels.newOutputStream(os.getChannel());
322 		else
323 			out = os;
324 
325 		return new OutputStream() {
326 			@Override
327 			public void write(byte[] b, int o, int n)
328 					throws IOException {
329 				out.write(b, o, n);
330 			}
331 
332 			@Override
333 			public void write(byte[] b) throws IOException {
334 				out.write(b);
335 			}
336 
337 			@Override
338 			public void write(int b) throws IOException {
339 				out.write(b);
340 			}
341 
342 			@Override
343 			public void close() throws IOException {
344 				try {
345 					if (fsync)
346 						os.getChannel().force(true);
347 					out.close();
348 					os = null;
349 				} catch (IOException | RuntimeException | Error ioe) {
350 					unlock();
351 					throw ioe;
352 				}
353 			}
354 		};
355 	}
356 
357 	void requireLock() {
358 		if (os == null) {
359 			unlock();
360 			throw new IllegalStateException(MessageFormat.format(JGitText.get().lockOnNotHeld, ref));
361 		}
362 	}
363 
364 	/**
365 	 * Request that {@link #commit()} remember modification time.
366 	 * <p>
367 	 * This is an alias for {@code setNeedSnapshot(true)}.
368 	 *
369 	 * @param on
370 	 *            true if the commit method must remember the modification time.
371 	 */
372 	public void setNeedStatInformation(boolean on) {
373 		setNeedSnapshot(on);
374 	}
375 
376 	/**
377 	 * Request that {@link #commit()} remember the
378 	 * {@link org.eclipse.jgit.internal.storage.file.FileSnapshot}.
379 	 *
380 	 * @param on
381 	 *            true if the commit method must remember the FileSnapshot.
382 	 */
383 	public void setNeedSnapshot(boolean on) {
384 		needSnapshot = on;
385 	}
386 
387 	/**
388 	 * Request that {@link #commit()} force dirty data to the drive.
389 	 *
390 	 * @param on
391 	 *            true if dirty data should be forced to the drive.
392 	 */
393 	public void setFSync(boolean on) {
394 		fsync = on;
395 	}
396 
397 	/**
398 	 * Wait until the lock file information differs from the old file.
399 	 * <p>
400 	 * This method tests the last modification date. If both are the same, this
401 	 * method sleeps until it can force the new lock file's modification date to
402 	 * be later than the target file.
403 	 *
404 	 * @throws java.lang.InterruptedException
405 	 *             the thread was interrupted before the last modified date of
406 	 *             the lock file was different from the last modified date of
407 	 *             the target file.
408 	 */
409 	public void waitForStatChange() throws InterruptedException {
410 		FileSnapshot o = FileSnapshot.save(ref);
411 		FileSnapshot n = FileSnapshot.save(lck);
412 		long fsTimeResolution = FS.getFileStoreAttributes(lck.toPath())
413 				.getFsTimestampResolution().toNanos();
414 		while (o.equals(n)) {
415 			TimeUnit.NANOSECONDS.sleep(fsTimeResolution);
416 			try {
417 				Files.setLastModifiedTime(lck.toPath(),
418 						FileTime.from(Instant.now()));
419 			} catch (IOException e) {
420 				n.waitUntilNotRacy();
421 			}
422 			n = FileSnapshot.save(lck);
423 		}
424 	}
425 
426 	/**
427 	 * Commit this change and release the lock.
428 	 * <p>
429 	 * If this method fails (returns false) the lock is still released.
430 	 *
431 	 * @return true if the commit was successful and the file contains the new
432 	 *         data; false if the commit failed and the file remains with the
433 	 *         old data.
434 	 * @throws java.lang.IllegalStateException
435 	 *             the lock is not held.
436 	 */
437 	public boolean commit() {
438 		if (os != null) {
439 			unlock();
440 			throw new IllegalStateException(MessageFormat.format(JGitText.get().lockOnNotClosed, ref));
441 		}
442 
443 		saveStatInformation();
444 		try {
445 			FileUtils.rename(lck, ref, StandardCopyOption.ATOMIC_MOVE);
446 			haveLck = false;
447 			closeToken();
448 			return true;
449 		} catch (IOException e) {
450 			unlock();
451 			return false;
452 		}
453 	}
454 
455 	private void closeToken() {
456 		if (token != null) {
457 			token.close();
458 			token = null;
459 		}
460 	}
461 
462 	private void saveStatInformation() {
463 		if (needSnapshot)
464 			commitSnapshot = FileSnapshot.save(lck);
465 	}
466 
467 	/**
468 	 * Get the modification time of the output file when it was committed.
469 	 *
470 	 * @return modification time of the lock file right before we committed it.
471 	 * @deprecated use {@link #getCommitLastModifiedInstant()} instead
472 	 */
473 	@Deprecated
474 	public long getCommitLastModified() {
475 		return commitSnapshot.lastModified();
476 	}
477 
478 	/**
479 	 * Get the modification time of the output file when it was committed.
480 	 *
481 	 * @return modification time of the lock file right before we committed it.
482 	 */
483 	public Instant getCommitLastModifiedInstant() {
484 		return commitSnapshot.lastModifiedInstant();
485 	}
486 
487 	/**
488 	 * Get the {@link FileSnapshot} just before commit.
489 	 *
490 	 * @return get the {@link FileSnapshot} just before commit.
491 	 */
492 	public FileSnapshot getCommitSnapshot() {
493 		return commitSnapshot;
494 	}
495 
496 	/**
497 	 * Update the commit snapshot {@link #getCommitSnapshot()} before commit.
498 	 * <p>
499 	 * This may be necessary if you need time stamp before commit occurs, e.g
500 	 * while writing the index.
501 	 */
502 	public void createCommitSnapshot() {
503 		saveStatInformation();
504 	}
505 
506 	/**
507 	 * Unlock this file and abort this change.
508 	 * <p>
509 	 * The temporary file (if created) is deleted before returning.
510 	 */
511 	public void unlock() {
512 		if (os != null) {
513 			try {
514 				os.close();
515 			} catch (IOException e) {
516 				LOG.error(MessageFormat
517 						.format(JGitText.get().unlockLockFileFailed, lck), e);
518 			}
519 			os = null;
520 		}
521 
522 		if (haveLck) {
523 			haveLck = false;
524 			try {
525 				FileUtils.delete(lck, FileUtils.RETRY);
526 			} catch (IOException e) {
527 				LOG.error(MessageFormat
528 						.format(JGitText.get().unlockLockFileFailed, lck), e);
529 			} finally {
530 				closeToken();
531 			}
532 		}
533 	}
534 
535 	/** {@inheritDoc} */
536 	@SuppressWarnings("nls")
537 	@Override
538 	public String toString() {
539 		return "LockFile[" + lck + ", haveLck=" + haveLck + "]";
540 	}
541 }