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.

LockFile.java 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  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. package org.eclipse.jgit.storage.file;
  45. import java.io.File;
  46. import java.io.FileInputStream;
  47. import java.io.FileNotFoundException;
  48. import java.io.FileOutputStream;
  49. import java.io.FilenameFilter;
  50. import java.io.IOException;
  51. import java.io.OutputStream;
  52. import java.nio.ByteBuffer;
  53. import java.nio.channels.Channels;
  54. import java.nio.channels.FileChannel;
  55. import java.text.MessageFormat;
  56. import org.eclipse.jgit.errors.LockFailedException;
  57. import org.eclipse.jgit.internal.JGitText;
  58. import org.eclipse.jgit.lib.Constants;
  59. import org.eclipse.jgit.lib.ObjectId;
  60. import org.eclipse.jgit.util.FS;
  61. import org.eclipse.jgit.util.FileUtils;
  62. /**
  63. * Git style file locking and replacement.
  64. * <p>
  65. * To modify a ref file Git tries to use an atomic update approach: we write the
  66. * new data into a brand new file, then rename it in place over the old name.
  67. * This way we can just delete the temporary file if anything goes wrong, and
  68. * nothing has been damaged. To coordinate access from multiple processes at
  69. * once Git tries to atomically create the new temporary file under a well-known
  70. * name.
  71. */
  72. public class LockFile {
  73. static final String SUFFIX = ".lock"; //$NON-NLS-1$
  74. /**
  75. * Unlock the given file.
  76. * <p>
  77. * This method can be used for recovering from a thrown
  78. * {@link LockFailedException} . This method does not validate that the lock
  79. * is or is not currently held before attempting to unlock it.
  80. *
  81. * @param file
  82. * @return true if unlocked, false if unlocking failed
  83. */
  84. public static boolean unlock(final File file) {
  85. final File lockFile = getLockFile(file);
  86. final int flags = FileUtils.RETRY | FileUtils.SKIP_MISSING;
  87. try {
  88. FileUtils.delete(lockFile, flags);
  89. } catch (IOException ignored) {
  90. // Ignore and return whether lock file still exists
  91. }
  92. return !lockFile.exists();
  93. }
  94. /**
  95. * Get the lock file corresponding to the given file.
  96. *
  97. * @param file
  98. * @return lock file
  99. */
  100. static File getLockFile(File file) {
  101. return new File(file.getParentFile(), file.getName() + SUFFIX);
  102. }
  103. /** Filter to skip over active lock files when listing a directory. */
  104. static final FilenameFilter FILTER = new FilenameFilter() {
  105. public boolean accept(File dir, String name) {
  106. return !name.endsWith(SUFFIX);
  107. }
  108. };
  109. private final File ref;
  110. private final File lck;
  111. private boolean haveLck;
  112. private FileOutputStream os;
  113. private boolean needSnapshot;
  114. private boolean fsync;
  115. private FileSnapshot commitSnapshot;
  116. private final FS fs;
  117. /**
  118. * Create a new lock for any file.
  119. *
  120. * @param f
  121. * the file that will be locked.
  122. * @param fs
  123. * the file system abstraction which will be necessary to perform
  124. * certain file system operations.
  125. */
  126. public LockFile(final File f, final FS fs) {
  127. ref = f;
  128. lck = getLockFile(ref);
  129. this.fs = fs;
  130. }
  131. /**
  132. * Try to establish the lock.
  133. *
  134. * @return true if the lock is now held by the caller; false if it is held
  135. * by someone else.
  136. * @throws IOException
  137. * the temporary output file could not be created. The caller
  138. * does not hold the lock.
  139. */
  140. public boolean lock() throws IOException {
  141. FileUtils.mkdirs(lck.getParentFile(), true);
  142. if (lck.createNewFile()) {
  143. haveLck = true;
  144. try {
  145. os = new FileOutputStream(lck);
  146. } catch (IOException ioe) {
  147. unlock();
  148. throw ioe;
  149. }
  150. }
  151. return haveLck;
  152. }
  153. /**
  154. * Try to establish the lock for appending.
  155. *
  156. * @return true if the lock is now held by the caller; false if it is held
  157. * by someone else.
  158. * @throws IOException
  159. * the temporary output file could not be created. The caller
  160. * does not hold the lock.
  161. */
  162. public boolean lockForAppend() throws IOException {
  163. if (!lock())
  164. return false;
  165. copyCurrentContent();
  166. return true;
  167. }
  168. /**
  169. * Copy the current file content into the temporary file.
  170. * <p>
  171. * This method saves the current file content by inserting it into the
  172. * temporary file, so that the caller can safely append rather than replace
  173. * the primary file.
  174. * <p>
  175. * This method does nothing if the current file does not exist, or exists
  176. * but is empty.
  177. *
  178. * @throws IOException
  179. * the temporary file could not be written, or a read error
  180. * occurred while reading from the current file. The lock is
  181. * released before throwing the underlying IO exception to the
  182. * caller.
  183. * @throws RuntimeException
  184. * the temporary file could not be written. The lock is released
  185. * before throwing the underlying exception to the caller.
  186. */
  187. public void copyCurrentContent() throws IOException {
  188. requireLock();
  189. try {
  190. final FileInputStream fis = new FileInputStream(ref);
  191. try {
  192. if (fsync) {
  193. FileChannel in = fis.getChannel();
  194. long pos = 0;
  195. long cnt = in.size();
  196. while (0 < cnt) {
  197. long r = os.getChannel().transferFrom(in, pos, cnt);
  198. pos += r;
  199. cnt -= r;
  200. }
  201. } else {
  202. final byte[] buf = new byte[2048];
  203. int r;
  204. while ((r = fis.read(buf)) >= 0)
  205. os.write(buf, 0, r);
  206. }
  207. } finally {
  208. fis.close();
  209. }
  210. } catch (FileNotFoundException fnfe) {
  211. // Don't worry about a file that doesn't exist yet, it
  212. // conceptually has no current content to copy.
  213. //
  214. } catch (IOException ioe) {
  215. unlock();
  216. throw ioe;
  217. } catch (RuntimeException ioe) {
  218. unlock();
  219. throw ioe;
  220. } catch (Error ioe) {
  221. unlock();
  222. throw ioe;
  223. }
  224. }
  225. /**
  226. * Write an ObjectId and LF to the temporary file.
  227. *
  228. * @param id
  229. * the id to store in the file. The id will be written in hex,
  230. * followed by a sole LF.
  231. * @throws IOException
  232. * the temporary file could not be written. The lock is released
  233. * before throwing the underlying IO exception to the caller.
  234. * @throws RuntimeException
  235. * the temporary file could not be written. The lock is released
  236. * before throwing the underlying exception to the caller.
  237. */
  238. public void write(final ObjectId id) throws IOException {
  239. byte[] buf = new byte[Constants.OBJECT_ID_STRING_LENGTH + 1];
  240. id.copyTo(buf, 0);
  241. buf[Constants.OBJECT_ID_STRING_LENGTH] = '\n';
  242. write(buf);
  243. }
  244. /**
  245. * Write arbitrary data to the temporary file.
  246. *
  247. * @param content
  248. * the bytes to store in the temporary file. No additional bytes
  249. * are added, so if the file must end with an LF it must appear
  250. * at the end of the byte array.
  251. * @throws IOException
  252. * the temporary file could not be written. The lock is released
  253. * before throwing the underlying IO exception to the caller.
  254. * @throws RuntimeException
  255. * the temporary file could not be written. The lock is released
  256. * before throwing the underlying exception to the caller.
  257. */
  258. public void write(final byte[] content) throws IOException {
  259. requireLock();
  260. try {
  261. if (fsync) {
  262. FileChannel fc = os.getChannel();
  263. ByteBuffer buf = ByteBuffer.wrap(content);
  264. while (0 < buf.remaining())
  265. fc.write(buf);
  266. fc.force(true);
  267. } else {
  268. os.write(content);
  269. }
  270. os.close();
  271. os = null;
  272. } catch (IOException ioe) {
  273. unlock();
  274. throw ioe;
  275. } catch (RuntimeException ioe) {
  276. unlock();
  277. throw ioe;
  278. } catch (Error ioe) {
  279. unlock();
  280. throw ioe;
  281. }
  282. }
  283. /**
  284. * Obtain the direct output stream for this lock.
  285. * <p>
  286. * The stream may only be accessed once, and only after {@link #lock()} has
  287. * been successfully invoked and returned true. Callers must close the
  288. * stream prior to calling {@link #commit()} to commit the change.
  289. *
  290. * @return a stream to write to the new file. The stream is unbuffered.
  291. */
  292. public OutputStream getOutputStream() {
  293. requireLock();
  294. final OutputStream out;
  295. if (fsync)
  296. out = Channels.newOutputStream(os.getChannel());
  297. else
  298. out = os;
  299. return new OutputStream() {
  300. @Override
  301. public void write(final byte[] b, final int o, final int n)
  302. throws IOException {
  303. out.write(b, o, n);
  304. }
  305. @Override
  306. public void write(final byte[] b) throws IOException {
  307. out.write(b);
  308. }
  309. @Override
  310. public void write(final int b) throws IOException {
  311. out.write(b);
  312. }
  313. @Override
  314. public void close() throws IOException {
  315. try {
  316. if (fsync)
  317. os.getChannel().force(true);
  318. out.close();
  319. os = null;
  320. } catch (IOException ioe) {
  321. unlock();
  322. throw ioe;
  323. } catch (RuntimeException ioe) {
  324. unlock();
  325. throw ioe;
  326. } catch (Error ioe) {
  327. unlock();
  328. throw ioe;
  329. }
  330. }
  331. };
  332. }
  333. private void requireLock() {
  334. if (os == null) {
  335. unlock();
  336. throw new IllegalStateException(MessageFormat.format(JGitText.get().lockOnNotHeld, ref));
  337. }
  338. }
  339. /**
  340. * Request that {@link #commit()} remember modification time.
  341. * <p>
  342. * This is an alias for {@code setNeedSnapshot(true)}.
  343. *
  344. * @param on
  345. * true if the commit method must remember the modification time.
  346. */
  347. public void setNeedStatInformation(final boolean on) {
  348. setNeedSnapshot(on);
  349. }
  350. /**
  351. * Request that {@link #commit()} remember the {@link FileSnapshot}.
  352. *
  353. * @param on
  354. * true if the commit method must remember the FileSnapshot.
  355. */
  356. public void setNeedSnapshot(final boolean on) {
  357. needSnapshot = on;
  358. }
  359. /**
  360. * Request that {@link #commit()} force dirty data to the drive.
  361. *
  362. * @param on
  363. * true if dirty data should be forced to the drive.
  364. */
  365. public void setFSync(final boolean on) {
  366. fsync = on;
  367. }
  368. /**
  369. * Wait until the lock file information differs from the old file.
  370. * <p>
  371. * This method tests the last modification date. If both are the same, this
  372. * method sleeps until it can force the new lock file's modification date to
  373. * be later than the target file.
  374. *
  375. * @throws InterruptedException
  376. * the thread was interrupted before the last modified date of
  377. * the lock file was different from the last modified date of
  378. * the target file.
  379. */
  380. public void waitForStatChange() throws InterruptedException {
  381. FileSnapshot o = FileSnapshot.save(ref);
  382. FileSnapshot n = FileSnapshot.save(lck);
  383. while (o.equals(n)) {
  384. Thread.sleep(25 /* milliseconds */);
  385. lck.setLastModified(System.currentTimeMillis());
  386. n = FileSnapshot.save(lck);
  387. }
  388. }
  389. /**
  390. * Commit this change and release the lock.
  391. * <p>
  392. * If this method fails (returns false) the lock is still released.
  393. *
  394. * @return true if the commit was successful and the file contains the new
  395. * data; false if the commit failed and the file remains with the
  396. * old data.
  397. * @throws IllegalStateException
  398. * the lock is not held.
  399. */
  400. public boolean commit() {
  401. if (os != null) {
  402. unlock();
  403. throw new IllegalStateException(MessageFormat.format(JGitText.get().lockOnNotClosed, ref));
  404. }
  405. saveStatInformation();
  406. if (lck.renameTo(ref))
  407. return true;
  408. if (!ref.exists() || deleteRef())
  409. if (renameLock())
  410. return true;
  411. unlock();
  412. return false;
  413. }
  414. private boolean deleteRef() {
  415. if (!fs.retryFailedLockFileCommit())
  416. return ref.delete();
  417. // File deletion fails on windows if another thread is
  418. // concurrently reading the same file. So try a few times.
  419. //
  420. for (int attempts = 0; attempts < 10; attempts++) {
  421. if (ref.delete())
  422. return true;
  423. try {
  424. Thread.sleep(100);
  425. } catch (InterruptedException e) {
  426. return false;
  427. }
  428. }
  429. return false;
  430. }
  431. private boolean renameLock() {
  432. if (!fs.retryFailedLockFileCommit())
  433. return lck.renameTo(ref);
  434. // File renaming fails on windows if another thread is
  435. // concurrently reading the same file. So try a few times.
  436. //
  437. for (int attempts = 0; attempts < 10; attempts++) {
  438. if (lck.renameTo(ref))
  439. return true;
  440. try {
  441. Thread.sleep(100);
  442. } catch (InterruptedException e) {
  443. return false;
  444. }
  445. }
  446. return false;
  447. }
  448. private void saveStatInformation() {
  449. if (needSnapshot)
  450. commitSnapshot = FileSnapshot.save(lck);
  451. }
  452. /**
  453. * Get the modification time of the output file when it was committed.
  454. *
  455. * @return modification time of the lock file right before we committed it.
  456. */
  457. public long getCommitLastModified() {
  458. return commitSnapshot.lastModified();
  459. }
  460. /** @return get the {@link FileSnapshot} just before commit. */
  461. public FileSnapshot getCommitSnapshot() {
  462. return commitSnapshot;
  463. }
  464. /**
  465. * Update the commit snapshot {@link #getCommitSnapshot()} before commit.
  466. * <p>
  467. * This may be necessary if you need time stamp before commit occurs, e.g
  468. * while writing the index.
  469. */
  470. public void createCommitSnapshot() {
  471. saveStatInformation();
  472. }
  473. /**
  474. * Unlock this file and abort this change.
  475. * <p>
  476. * The temporary file (if created) is deleted before returning.
  477. */
  478. public void unlock() {
  479. if (os != null) {
  480. try {
  481. os.close();
  482. } catch (IOException ioe) {
  483. // Ignore this
  484. }
  485. os = null;
  486. }
  487. if (haveLck) {
  488. haveLck = false;
  489. try {
  490. FileUtils.delete(lck, FileUtils.RETRY);
  491. } catch (IOException e) {
  492. // couldn't delete the file even after retry.
  493. }
  494. }
  495. }
  496. @Override
  497. public String toString() {
  498. return "LockFile[" + lck + ", haveLck=" + haveLck + "]";
  499. }
  500. }