Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

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