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.

LooseObjects.java 7.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. /*
  2. * Copyright (C) 2009, Google Inc. and others
  3. *
  4. * This program and the accompanying materials are made available under the
  5. * terms of the Eclipse Distribution License v. 1.0 which is available at
  6. * https://www.eclipse.org/org/documents/edl-v10.php.
  7. *
  8. * SPDX-License-Identifier: BSD-3-Clause
  9. */
  10. package org.eclipse.jgit.internal.storage.file;
  11. import java.io.File;
  12. import java.io.FileInputStream;
  13. import java.io.FileNotFoundException;
  14. import java.io.IOException;
  15. import java.nio.file.Files;
  16. import java.nio.file.NoSuchFileException;
  17. import java.nio.file.StandardCopyOption;
  18. import java.text.MessageFormat;
  19. import java.util.Set;
  20. import org.eclipse.jgit.internal.JGitText;
  21. import org.eclipse.jgit.internal.storage.file.FileObjectDatabase.InsertLooseObjectResult;
  22. import org.eclipse.jgit.lib.AbbreviatedObjectId;
  23. import org.eclipse.jgit.lib.AnyObjectId;
  24. import org.eclipse.jgit.lib.Constants;
  25. import org.eclipse.jgit.lib.ObjectId;
  26. import org.eclipse.jgit.lib.ObjectLoader;
  27. import org.eclipse.jgit.util.FileUtils;
  28. import org.slf4j.Logger;
  29. import org.slf4j.LoggerFactory;
  30. /**
  31. * Traditional file system based loose objects handler.
  32. * <p>
  33. * This is the loose object representation for a Git object database, where
  34. * objects are stored loose by hashing them into directories by their
  35. * {@link org.eclipse.jgit.lib.ObjectId}.
  36. */
  37. class LooseObjects {
  38. private static final Logger LOG = LoggerFactory
  39. .getLogger(LooseObjects.class);
  40. /**
  41. * Maximum number of attempts to read a loose object for which a stale file
  42. * handle exception is thrown
  43. */
  44. private final static int MAX_LOOSE_OBJECT_STALE_READ_ATTEMPTS = 5;
  45. private final File directory;
  46. private final UnpackedObjectCache unpackedObjectCache;
  47. /**
  48. * Initialize a reference to an on-disk object directory.
  49. *
  50. * @param dir
  51. * the location of the <code>objects</code> directory.
  52. */
  53. LooseObjects(File dir) {
  54. directory = dir;
  55. unpackedObjectCache = new UnpackedObjectCache();
  56. }
  57. /**
  58. * Getter for the field <code>directory</code>.
  59. *
  60. * @return the location of the <code>objects</code> directory.
  61. */
  62. File getDirectory() {
  63. return directory;
  64. }
  65. void create() throws IOException {
  66. FileUtils.mkdirs(directory);
  67. }
  68. void close() {
  69. unpackedObjectCache().clear();
  70. }
  71. /** {@inheritDoc} */
  72. @Override
  73. public String toString() {
  74. return "LooseObjects[" + directory + "]"; //$NON-NLS-1$ //$NON-NLS-2$
  75. }
  76. boolean hasCached(AnyObjectId id) {
  77. return unpackedObjectCache().isUnpacked(id);
  78. }
  79. /**
  80. * Does the requested object exist as a loose object?
  81. *
  82. * @param objectId
  83. * identity of the object to test for existence of.
  84. * @return {@code true} if the specified object is stored as a loose object.
  85. */
  86. boolean has(AnyObjectId objectId) {
  87. return fileFor(objectId).exists();
  88. }
  89. /**
  90. * Find objects matching the prefix abbreviation.
  91. *
  92. * @param matches
  93. * set to add any located ObjectIds to. This is an output
  94. * parameter.
  95. * @param id
  96. * prefix to search for.
  97. * @param matchLimit
  98. * maximum number of results to return. At most this many
  99. * ObjectIds should be added to matches before returning.
  100. * @return {@code true} if the matches were exhausted before reaching
  101. * {@code maxLimit}.
  102. */
  103. boolean resolve(Set<ObjectId> matches, AbbreviatedObjectId id,
  104. int matchLimit) {
  105. String fanOut = id.name().substring(0, 2);
  106. String[] entries = new File(directory, fanOut).list();
  107. if (entries != null) {
  108. for (String e : entries) {
  109. if (e.length() != Constants.OBJECT_ID_STRING_LENGTH - 2) {
  110. continue;
  111. }
  112. try {
  113. ObjectId entId = ObjectId.fromString(fanOut + e);
  114. if (id.prefixCompare(entId) == 0) {
  115. matches.add(entId);
  116. }
  117. } catch (IllegalArgumentException notId) {
  118. continue;
  119. }
  120. if (matches.size() > matchLimit) {
  121. return false;
  122. }
  123. }
  124. }
  125. return true;
  126. }
  127. ObjectLoader open(WindowCursor curs, AnyObjectId id) throws IOException {
  128. int readAttempts = 0;
  129. while (readAttempts < MAX_LOOSE_OBJECT_STALE_READ_ATTEMPTS) {
  130. readAttempts++;
  131. File path = fileFor(id);
  132. try {
  133. return getObjectLoader(curs, path, id);
  134. } catch (FileNotFoundException noFile) {
  135. if (path.exists()) {
  136. throw noFile;
  137. }
  138. break;
  139. } catch (IOException e) {
  140. if (!FileUtils.isStaleFileHandleInCausalChain(e)) {
  141. throw e;
  142. }
  143. if (LOG.isDebugEnabled()) {
  144. LOG.debug(MessageFormat.format(
  145. JGitText.get().looseObjectHandleIsStale, id.name(),
  146. Integer.valueOf(readAttempts), Integer.valueOf(
  147. MAX_LOOSE_OBJECT_STALE_READ_ATTEMPTS)));
  148. }
  149. }
  150. }
  151. unpackedObjectCache().remove(id);
  152. return null;
  153. }
  154. /**
  155. * Provides a loader for an objectId
  156. *
  157. * @param curs
  158. * cursor on the database
  159. * @param path
  160. * the path of the loose object
  161. * @param id
  162. * the object id
  163. * @return a loader for the loose file object
  164. * @throws IOException
  165. * when file does not exist or it could not be opened
  166. */
  167. ObjectLoader getObjectLoader(WindowCursor curs, File path, AnyObjectId id)
  168. throws IOException {
  169. try (FileInputStream in = new FileInputStream(path)) {
  170. unpackedObjectCache().add(id);
  171. return UnpackedObject.open(in, path, id, curs);
  172. }
  173. }
  174. /**
  175. * <p>
  176. * Getter for the field <code>unpackedObjectCache</code>.
  177. * </p>
  178. * This accessor is particularly useful to allow mocking of this class for
  179. * testing purposes.
  180. *
  181. * @return the cache of the objects currently unpacked.
  182. */
  183. UnpackedObjectCache unpackedObjectCache() {
  184. return unpackedObjectCache;
  185. }
  186. long getSize(WindowCursor curs, AnyObjectId id) throws IOException {
  187. File f = fileFor(id);
  188. try (FileInputStream in = new FileInputStream(f)) {
  189. unpackedObjectCache().add(id);
  190. return UnpackedObject.getSize(in, id, curs);
  191. } catch (FileNotFoundException noFile) {
  192. if (f.exists()) {
  193. throw noFile;
  194. }
  195. unpackedObjectCache().remove(id);
  196. return -1;
  197. }
  198. }
  199. InsertLooseObjectResult insert(File tmp, ObjectId id) throws IOException {
  200. final File dst = fileFor(id);
  201. if (dst.exists()) {
  202. // We want to be extra careful and avoid replacing an object
  203. // that already exists. We can't be sure renameTo() would
  204. // fail on all platforms if dst exists, so we check first.
  205. //
  206. FileUtils.delete(tmp, FileUtils.RETRY);
  207. return InsertLooseObjectResult.EXISTS_LOOSE;
  208. }
  209. try {
  210. return tryMove(tmp, dst, id);
  211. } catch (NoSuchFileException e) {
  212. // It's possible the directory doesn't exist yet as the object
  213. // directories are always lazily created. Note that we try the
  214. // rename/move first as the directory likely does exist.
  215. //
  216. // Create the directory.
  217. //
  218. FileUtils.mkdir(dst.getParentFile(), true);
  219. } catch (IOException e) {
  220. // Any other IO error is considered a failure.
  221. //
  222. LOG.error(e.getMessage(), e);
  223. FileUtils.delete(tmp, FileUtils.RETRY);
  224. return InsertLooseObjectResult.FAILURE;
  225. }
  226. try {
  227. return tryMove(tmp, dst, id);
  228. } catch (IOException e) {
  229. // The object failed to be renamed into its proper location and
  230. // it doesn't exist in the repository either. We really don't
  231. // know what went wrong, so fail.
  232. //
  233. LOG.error(e.getMessage(), e);
  234. FileUtils.delete(tmp, FileUtils.RETRY);
  235. return InsertLooseObjectResult.FAILURE;
  236. }
  237. }
  238. private InsertLooseObjectResult tryMove(File tmp, File dst, ObjectId id)
  239. throws IOException {
  240. Files.move(FileUtils.toPath(tmp), FileUtils.toPath(dst),
  241. StandardCopyOption.ATOMIC_MOVE);
  242. dst.setReadOnly();
  243. unpackedObjectCache().add(id);
  244. return InsertLooseObjectResult.INSERTED;
  245. }
  246. /**
  247. * Compute the location of a loose object file.
  248. *
  249. * @param objectId
  250. * identity of the object to get the File location for.
  251. * @return {@link java.io.File} location of the specified loose object.
  252. */
  253. File fileFor(AnyObjectId objectId) {
  254. String n = objectId.name();
  255. String d = n.substring(0, 2);
  256. String f = n.substring(2);
  257. return new File(new File(getDirectory(), d), f);
  258. }
  259. }