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 14KB

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