選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

LockFile.java 14KB

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