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

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