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

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