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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  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.lib;
  45. import java.io.BufferedOutputStream;
  46. import java.io.File;
  47. import java.io.FileInputStream;
  48. import java.io.FileNotFoundException;
  49. import java.io.FileOutputStream;
  50. import java.io.FilenameFilter;
  51. import java.io.IOException;
  52. import java.io.OutputStream;
  53. import java.nio.channels.FileLock;
  54. import java.nio.channels.OverlappingFileLockException;
  55. /**
  56. * Git style file locking and replacement.
  57. * <p>
  58. * To modify a ref file Git tries to use an atomic update approach: we write the
  59. * new data into a brand new file, then rename it in place over the old name.
  60. * This way we can just delete the temporary file if anything goes wrong, and
  61. * nothing has been damaged. To coordinate access from multiple processes at
  62. * once Git tries to atomically create the new temporary file under a well-known
  63. * name.
  64. */
  65. public class LockFile {
  66. static final String SUFFIX = ".lock"; //$NON-NLS-1$
  67. /** Filter to skip over active lock files when listing a directory. */
  68. static final FilenameFilter FILTER = new FilenameFilter() {
  69. public boolean accept(File dir, String name) {
  70. return !name.endsWith(SUFFIX);
  71. }
  72. };
  73. private final File ref;
  74. private final File lck;
  75. private FileLock fLck;
  76. private boolean haveLck;
  77. private FileOutputStream os;
  78. private boolean needStatInformation;
  79. private long commitLastModified;
  80. /**
  81. * Create a new lock for any file.
  82. *
  83. * @param f
  84. * the file that will be locked.
  85. */
  86. public LockFile(final File f) {
  87. ref = f;
  88. lck = new File(ref.getParentFile(), ref.getName() + SUFFIX);
  89. }
  90. /**
  91. * Try to establish the lock.
  92. *
  93. * @return true if the lock is now held by the caller; false if it is held
  94. * by someone else.
  95. * @throws IOException
  96. * the temporary output file could not be created. The caller
  97. * does not hold the lock.
  98. */
  99. public boolean lock() throws IOException {
  100. lck.getParentFile().mkdirs();
  101. if (lck.createNewFile()) {
  102. haveLck = true;
  103. try {
  104. os = new FileOutputStream(lck);
  105. try {
  106. fLck = os.getChannel().tryLock();
  107. if (fLck == null)
  108. throw new OverlappingFileLockException();
  109. } catch (OverlappingFileLockException ofle) {
  110. // We cannot use unlock() here as this file is not
  111. // held by us, but we thought we created it. We must
  112. // not delete it, as it belongs to some other process.
  113. //
  114. haveLck = false;
  115. try {
  116. os.close();
  117. } catch (IOException ioe) {
  118. // Fail by returning haveLck = false.
  119. }
  120. os = null;
  121. }
  122. } catch (IOException ioe) {
  123. unlock();
  124. throw ioe;
  125. }
  126. }
  127. return haveLck;
  128. }
  129. /**
  130. * Try to establish the lock for appending.
  131. *
  132. * @return true if the lock is now held by the caller; false if it is held
  133. * by someone else.
  134. * @throws IOException
  135. * the temporary output file could not be created. The caller
  136. * does not hold the lock.
  137. */
  138. public boolean lockForAppend() throws IOException {
  139. if (!lock())
  140. return false;
  141. copyCurrentContent();
  142. return true;
  143. }
  144. /**
  145. * Copy the current file content into the temporary file.
  146. * <p>
  147. * This method saves the current file content by inserting it into the
  148. * temporary file, so that the caller can safely append rather than replace
  149. * the primary file.
  150. * <p>
  151. * This method does nothing if the current file does not exist, or exists
  152. * but is empty.
  153. *
  154. * @throws IOException
  155. * the temporary file could not be written, or a read error
  156. * occurred while reading from the current file. The lock is
  157. * released before throwing the underlying IO exception to the
  158. * caller.
  159. * @throws RuntimeException
  160. * the temporary file could not be written. The lock is released
  161. * before throwing the underlying exception to the caller.
  162. */
  163. public void copyCurrentContent() throws IOException {
  164. requireLock();
  165. try {
  166. final FileInputStream fis = new FileInputStream(ref);
  167. try {
  168. final byte[] buf = new byte[2048];
  169. int r;
  170. while ((r = fis.read(buf)) >= 0)
  171. os.write(buf, 0, r);
  172. } finally {
  173. fis.close();
  174. }
  175. } catch (FileNotFoundException fnfe) {
  176. // Don't worry about a file that doesn't exist yet, it
  177. // conceptually has no current content to copy.
  178. //
  179. } catch (IOException ioe) {
  180. unlock();
  181. throw ioe;
  182. } catch (RuntimeException ioe) {
  183. unlock();
  184. throw ioe;
  185. } catch (Error ioe) {
  186. unlock();
  187. throw ioe;
  188. }
  189. }
  190. /**
  191. * Write an ObjectId and LF to the temporary file.
  192. *
  193. * @param id
  194. * the id to store in the file. The id will be written in hex,
  195. * followed by a sole LF.
  196. * @throws IOException
  197. * the temporary file could not be written. The lock is released
  198. * before throwing the underlying IO exception to the caller.
  199. * @throws RuntimeException
  200. * the temporary file could not be written. The lock is released
  201. * before throwing the underlying exception to the caller.
  202. */
  203. public void write(final ObjectId id) throws IOException {
  204. requireLock();
  205. try {
  206. final BufferedOutputStream b;
  207. b = new BufferedOutputStream(os, Constants.OBJECT_ID_STRING_LENGTH + 1);
  208. id.copyTo(b);
  209. b.write('\n');
  210. b.flush();
  211. fLck.release();
  212. b.close();
  213. os = null;
  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 arbitrary data to the temporary file.
  227. *
  228. * @param content
  229. * the bytes to store in the temporary file. No additional bytes
  230. * are added, so if the file must end with an LF it must appear
  231. * at the end of the byte array.
  232. * @throws IOException
  233. * the temporary file could not be written. The lock is released
  234. * before throwing the underlying IO exception to the caller.
  235. * @throws RuntimeException
  236. * the temporary file could not be written. The lock is released
  237. * before throwing the underlying exception to the caller.
  238. */
  239. public void write(final byte[] content) throws IOException {
  240. requireLock();
  241. try {
  242. os.write(content);
  243. os.flush();
  244. fLck.release();
  245. os.close();
  246. os = null;
  247. } catch (IOException ioe) {
  248. unlock();
  249. throw ioe;
  250. } catch (RuntimeException ioe) {
  251. unlock();
  252. throw ioe;
  253. } catch (Error ioe) {
  254. unlock();
  255. throw ioe;
  256. }
  257. }
  258. /**
  259. * Obtain the direct output stream for this lock.
  260. * <p>
  261. * The stream may only be accessed once, and only after {@link #lock()} has
  262. * been successfully invoked and returned true. Callers must close the
  263. * stream prior to calling {@link #commit()} to commit the change.
  264. *
  265. * @return a stream to write to the new file. The stream is unbuffered.
  266. */
  267. public OutputStream getOutputStream() {
  268. requireLock();
  269. return new OutputStream() {
  270. @Override
  271. public void write(final byte[] b, final int o, final int n)
  272. throws IOException {
  273. os.write(b, o, n);
  274. }
  275. @Override
  276. public void write(final byte[] b) throws IOException {
  277. os.write(b);
  278. }
  279. @Override
  280. public void write(final int b) throws IOException {
  281. os.write(b);
  282. }
  283. @Override
  284. public void flush() throws IOException {
  285. os.flush();
  286. }
  287. @Override
  288. public void close() throws IOException {
  289. try {
  290. os.flush();
  291. fLck.release();
  292. os.close();
  293. os = null;
  294. } catch (IOException ioe) {
  295. unlock();
  296. throw ioe;
  297. } catch (RuntimeException ioe) {
  298. unlock();
  299. throw ioe;
  300. } catch (Error ioe) {
  301. unlock();
  302. throw ioe;
  303. }
  304. }
  305. };
  306. }
  307. private void requireLock() {
  308. if (os == null) {
  309. unlock();
  310. throw new IllegalStateException("Lock on " + ref + " not held.");
  311. }
  312. }
  313. /**
  314. * Request that {@link #commit()} remember modification time.
  315. *
  316. * @param on
  317. * true if the commit method must remember the modification time.
  318. */
  319. public void setNeedStatInformation(final boolean on) {
  320. needStatInformation = on;
  321. }
  322. /**
  323. * Wait until the lock file information differs from the old file.
  324. * <p>
  325. * This method tests both the length and the last modification date. If both
  326. * are the same, this method sleeps until it can force the new lock file's
  327. * modification date to be later than the target file.
  328. *
  329. * @throws InterruptedException
  330. * the thread was interrupted before the last modified date of
  331. * the lock file was different from the last modified date of
  332. * the target file.
  333. */
  334. public void waitForStatChange() throws InterruptedException {
  335. if (ref.length() == lck.length()) {
  336. long otime = ref.lastModified();
  337. long ntime = lck.lastModified();
  338. while (otime == ntime) {
  339. Thread.sleep(25 /* milliseconds */);
  340. lck.setLastModified(System.currentTimeMillis());
  341. ntime = lck.lastModified();
  342. }
  343. }
  344. }
  345. /**
  346. * Commit this change and release the lock.
  347. * <p>
  348. * If this method fails (returns false) the lock is still released.
  349. *
  350. * @return true if the commit was successful and the file contains the new
  351. * data; false if the commit failed and the file remains with the
  352. * old data.
  353. * @throws IllegalStateException
  354. * the lock is not held.
  355. */
  356. public boolean commit() {
  357. if (os != null) {
  358. unlock();
  359. throw new IllegalStateException("Lock on " + ref + " not closed.");
  360. }
  361. saveStatInformation();
  362. if (lck.renameTo(ref))
  363. return true;
  364. if (!ref.exists() || ref.delete())
  365. if (lck.renameTo(ref))
  366. return true;
  367. unlock();
  368. return false;
  369. }
  370. private void saveStatInformation() {
  371. if (needStatInformation)
  372. commitLastModified = lck.lastModified();
  373. }
  374. /**
  375. * Get the modification time of the output file when it was committed.
  376. *
  377. * @return modification time of the lock file right before we committed it.
  378. */
  379. public long getCommitLastModified() {
  380. return commitLastModified;
  381. }
  382. /**
  383. * Unlock this file and abort this change.
  384. * <p>
  385. * The temporary file (if created) is deleted before returning.
  386. */
  387. public void unlock() {
  388. if (os != null) {
  389. if (fLck != null) {
  390. try {
  391. fLck.release();
  392. } catch (IOException ioe) {
  393. // Huh?
  394. }
  395. fLck = null;
  396. }
  397. try {
  398. os.close();
  399. } catch (IOException ioe) {
  400. // Ignore this
  401. }
  402. os = null;
  403. }
  404. if (haveLck) {
  405. haveLck = false;
  406. lck.delete();
  407. }
  408. }
  409. @Override
  410. public String toString() {
  411. return "LockFile[" + lck + ", haveLck=" + haveLck + "]";
  412. }
  413. }