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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  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 = new FilenameFilter() {
  116. @Override
  117. public boolean accept(File dir, String name) {
  118. return !name.endsWith(LOCK_SUFFIX);
  119. }
  120. };
  121. private final File ref;
  122. private final File lck;
  123. private boolean haveLck;
  124. FileOutputStream os;
  125. private boolean needSnapshot;
  126. boolean fsync;
  127. private FileSnapshot commitSnapshot;
  128. private LockToken token;
  129. /**
  130. * Create a new lock for any file.
  131. *
  132. * @param f
  133. * the file that will be locked.
  134. */
  135. public LockFile(File f) {
  136. ref = f;
  137. lck = getLockFile(ref);
  138. }
  139. /**
  140. * Try to establish the lock.
  141. *
  142. * @return true if the lock is now held by the caller; false if it is held
  143. * by someone else.
  144. * @throws java.io.IOException
  145. * the temporary output file could not be created. The caller
  146. * does not hold the lock.
  147. */
  148. public boolean lock() throws IOException {
  149. FileUtils.mkdirs(lck.getParentFile(), true);
  150. try {
  151. token = FS.DETECTED.createNewFileAtomic(lck);
  152. } catch (IOException e) {
  153. LOG.error(JGitText.get().failedCreateLockFile, lck, e);
  154. throw e;
  155. }
  156. if (token.isCreated()) {
  157. haveLck = true;
  158. try {
  159. os = new FileOutputStream(lck);
  160. } catch (IOException ioe) {
  161. unlock();
  162. throw ioe;
  163. }
  164. } else {
  165. closeToken();
  166. }
  167. return haveLck;
  168. }
  169. /**
  170. * Try to establish the lock for appending.
  171. *
  172. * @return true if the lock is now held by the caller; false if it is held
  173. * by someone else.
  174. * @throws java.io.IOException
  175. * the temporary output file could not be created. The caller
  176. * does not hold the lock.
  177. */
  178. public boolean lockForAppend() throws IOException {
  179. if (!lock())
  180. return false;
  181. copyCurrentContent();
  182. return true;
  183. }
  184. /**
  185. * Copy the current file content into the temporary file.
  186. * <p>
  187. * This method saves the current file content by inserting it into the
  188. * temporary file, so that the caller can safely append rather than replace
  189. * the primary file.
  190. * <p>
  191. * This method does nothing if the current file does not exist, or exists
  192. * but is empty.
  193. *
  194. * @throws java.io.IOException
  195. * the temporary file could not be written, or a read error
  196. * occurred while reading from the current file. The lock is
  197. * released before throwing the underlying IO exception to the
  198. * caller.
  199. * @throws java.lang.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 copyCurrentContent() throws IOException {
  204. requireLock();
  205. try {
  206. try (FileInputStream fis = new FileInputStream(ref)) {
  207. if (fsync) {
  208. FileChannel in = fis.getChannel();
  209. long pos = 0;
  210. long cnt = in.size();
  211. while (0 < cnt) {
  212. long r = os.getChannel().transferFrom(in, pos, cnt);
  213. pos += r;
  214. cnt -= r;
  215. }
  216. } else {
  217. final byte[] buf = new byte[2048];
  218. int r;
  219. while ((r = fis.read(buf)) >= 0)
  220. os.write(buf, 0, r);
  221. }
  222. }
  223. } catch (FileNotFoundException fnfe) {
  224. if (ref.exists()) {
  225. unlock();
  226. throw fnfe;
  227. }
  228. // Don't worry about a file that doesn't exist yet, it
  229. // conceptually has no current content to copy.
  230. //
  231. } catch (IOException ioe) {
  232. unlock();
  233. throw ioe;
  234. } catch (RuntimeException ioe) {
  235. unlock();
  236. throw ioe;
  237. } catch (Error ioe) {
  238. unlock();
  239. throw ioe;
  240. }
  241. }
  242. /**
  243. * Write an ObjectId and LF to the temporary file.
  244. *
  245. * @param id
  246. * the id to store in the file. The id will be written in hex,
  247. * followed by a sole LF.
  248. * @throws java.io.IOException
  249. * the temporary file could not be written. The lock is released
  250. * before throwing the underlying IO exception to the caller.
  251. * @throws java.lang.RuntimeException
  252. * the temporary file could not be written. The lock is released
  253. * before throwing the underlying exception to the caller.
  254. */
  255. public void write(ObjectId id) throws IOException {
  256. byte[] buf = new byte[Constants.OBJECT_ID_STRING_LENGTH + 1];
  257. id.copyTo(buf, 0);
  258. buf[Constants.OBJECT_ID_STRING_LENGTH] = '\n';
  259. write(buf);
  260. }
  261. /**
  262. * Write arbitrary data to the temporary file.
  263. *
  264. * @param content
  265. * the bytes to store in the temporary file. No additional bytes
  266. * are added, so if the file must end with an LF it must appear
  267. * at the end of the byte array.
  268. * @throws java.io.IOException
  269. * the temporary file could not be written. The lock is released
  270. * before throwing the underlying IO exception to the caller.
  271. * @throws java.lang.RuntimeException
  272. * the temporary file could not be written. The lock is released
  273. * before throwing the underlying exception to the caller.
  274. */
  275. public void write(byte[] content) throws IOException {
  276. requireLock();
  277. try {
  278. if (fsync) {
  279. FileChannel fc = os.getChannel();
  280. ByteBuffer buf = ByteBuffer.wrap(content);
  281. while (0 < buf.remaining())
  282. fc.write(buf);
  283. fc.force(true);
  284. } else {
  285. os.write(content);
  286. }
  287. os.close();
  288. os = null;
  289. } catch (IOException ioe) {
  290. unlock();
  291. throw ioe;
  292. } catch (RuntimeException ioe) {
  293. unlock();
  294. throw ioe;
  295. } catch (Error ioe) {
  296. unlock();
  297. throw ioe;
  298. }
  299. }
  300. /**
  301. * Obtain the direct output stream for this lock.
  302. * <p>
  303. * The stream may only be accessed once, and only after {@link #lock()} has
  304. * been successfully invoked and returned true. Callers must close the
  305. * stream prior to calling {@link #commit()} to commit the change.
  306. *
  307. * @return a stream to write to the new file. The stream is unbuffered.
  308. */
  309. public OutputStream getOutputStream() {
  310. requireLock();
  311. final OutputStream out;
  312. if (fsync)
  313. out = Channels.newOutputStream(os.getChannel());
  314. else
  315. out = os;
  316. return new OutputStream() {
  317. @Override
  318. public void write(byte[] b, int o, int n)
  319. throws IOException {
  320. out.write(b, o, n);
  321. }
  322. @Override
  323. public void write(byte[] b) throws IOException {
  324. out.write(b);
  325. }
  326. @Override
  327. public void write(int b) throws IOException {
  328. out.write(b);
  329. }
  330. @Override
  331. public void close() throws IOException {
  332. try {
  333. if (fsync)
  334. os.getChannel().force(true);
  335. out.close();
  336. os = null;
  337. } catch (IOException ioe) {
  338. unlock();
  339. throw ioe;
  340. } catch (RuntimeException ioe) {
  341. unlock();
  342. throw ioe;
  343. } catch (Error ioe) {
  344. unlock();
  345. throw ioe;
  346. }
  347. }
  348. };
  349. }
  350. void requireLock() {
  351. if (os == null) {
  352. unlock();
  353. throw new IllegalStateException(MessageFormat.format(JGitText.get().lockOnNotHeld, ref));
  354. }
  355. }
  356. /**
  357. * Request that {@link #commit()} remember modification time.
  358. * <p>
  359. * This is an alias for {@code setNeedSnapshot(true)}.
  360. *
  361. * @param on
  362. * true if the commit method must remember the modification time.
  363. */
  364. public void setNeedStatInformation(boolean on) {
  365. setNeedSnapshot(on);
  366. }
  367. /**
  368. * Request that {@link #commit()} remember the
  369. * {@link org.eclipse.jgit.internal.storage.file.FileSnapshot}.
  370. *
  371. * @param on
  372. * true if the commit method must remember the FileSnapshot.
  373. */
  374. public void setNeedSnapshot(boolean on) {
  375. needSnapshot = on;
  376. }
  377. /**
  378. * Request that {@link #commit()} force dirty data to the drive.
  379. *
  380. * @param on
  381. * true if dirty data should be forced to the drive.
  382. */
  383. public void setFSync(boolean on) {
  384. fsync = on;
  385. }
  386. /**
  387. * Wait until the lock file information differs from the old file.
  388. * <p>
  389. * This method tests the last modification date. If both are the same, this
  390. * method sleeps until it can force the new lock file's modification date to
  391. * be later than the target file.
  392. *
  393. * @throws java.lang.InterruptedException
  394. * the thread was interrupted before the last modified date of
  395. * the lock file was different from the last modified date of
  396. * the target file.
  397. */
  398. public void waitForStatChange() throws InterruptedException {
  399. FileSnapshot o = FileSnapshot.save(ref);
  400. FileSnapshot n = FileSnapshot.save(lck);
  401. long fsTimeResolution = FS.getFileStoreAttributes(lck.toPath())
  402. .getFsTimestampResolution().toNanos();
  403. while (o.equals(n)) {
  404. TimeUnit.NANOSECONDS.sleep(fsTimeResolution);
  405. try {
  406. Files.setLastModifiedTime(lck.toPath(),
  407. FileTime.from(Instant.now()));
  408. } catch (IOException e) {
  409. n.waitUntilNotRacy();
  410. }
  411. n = FileSnapshot.save(lck);
  412. }
  413. }
  414. /**
  415. * Commit this change and release the lock.
  416. * <p>
  417. * If this method fails (returns false) the lock is still released.
  418. *
  419. * @return true if the commit was successful and the file contains the new
  420. * data; false if the commit failed and the file remains with the
  421. * old data.
  422. * @throws java.lang.IllegalStateException
  423. * the lock is not held.
  424. */
  425. public boolean commit() {
  426. if (os != null) {
  427. unlock();
  428. throw new IllegalStateException(MessageFormat.format(JGitText.get().lockOnNotClosed, ref));
  429. }
  430. saveStatInformation();
  431. try {
  432. FileUtils.rename(lck, ref, StandardCopyOption.ATOMIC_MOVE);
  433. haveLck = false;
  434. closeToken();
  435. return true;
  436. } catch (IOException e) {
  437. unlock();
  438. return false;
  439. }
  440. }
  441. private void closeToken() {
  442. if (token != null) {
  443. token.close();
  444. token = null;
  445. }
  446. }
  447. private void saveStatInformation() {
  448. if (needSnapshot)
  449. commitSnapshot = FileSnapshot.save(lck);
  450. }
  451. /**
  452. * Get the modification time of the output file when it was committed.
  453. *
  454. * @return modification time of the lock file right before we committed it.
  455. * @deprecated use {@link #getCommitLastModifiedInstant()} instead
  456. */
  457. @Deprecated
  458. public long getCommitLastModified() {
  459. return commitSnapshot.lastModified();
  460. }
  461. /**
  462. * Get the modification time of the output file when it was committed.
  463. *
  464. * @return modification time of the lock file right before we committed it.
  465. */
  466. public Instant getCommitLastModifiedInstant() {
  467. return commitSnapshot.lastModifiedInstant();
  468. }
  469. /**
  470. * Get the {@link FileSnapshot} just before commit.
  471. *
  472. * @return get the {@link FileSnapshot} just before commit.
  473. */
  474. public FileSnapshot getCommitSnapshot() {
  475. return commitSnapshot;
  476. }
  477. /**
  478. * Update the commit snapshot {@link #getCommitSnapshot()} before commit.
  479. * <p>
  480. * This may be necessary if you need time stamp before commit occurs, e.g
  481. * while writing the index.
  482. */
  483. public void createCommitSnapshot() {
  484. saveStatInformation();
  485. }
  486. /**
  487. * Unlock this file and abort this change.
  488. * <p>
  489. * The temporary file (if created) is deleted before returning.
  490. */
  491. public void unlock() {
  492. if (os != null) {
  493. try {
  494. os.close();
  495. } catch (IOException e) {
  496. LOG.error(MessageFormat
  497. .format(JGitText.get().unlockLockFileFailed, lck), e);
  498. }
  499. os = null;
  500. }
  501. if (haveLck) {
  502. haveLck = false;
  503. try {
  504. FileUtils.delete(lck, FileUtils.RETRY);
  505. } catch (IOException e) {
  506. LOG.error(MessageFormat
  507. .format(JGitText.get().unlockLockFileFailed, lck), e);
  508. } finally {
  509. closeToken();
  510. }
  511. }
  512. }
  513. /** {@inheritDoc} */
  514. @SuppressWarnings("nls")
  515. @Override
  516. public String toString() {
  517. return "LockFile[" + lck + ", haveLck=" + haveLck + "]";
  518. }
  519. }