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.

RepositoryCache.java 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. /*
  2. * Copyright (C) 2009, Google Inc.
  3. * and other copyright owners as documented in the project's IP log.
  4. *
  5. * This program and the accompanying materials are made available
  6. * under the terms of the Eclipse Distribution License v1.0 which
  7. * accompanies this distribution, is reproduced below, and is
  8. * available at http://www.eclipse.org/org/documents/edl-v10.php
  9. *
  10. * All rights reserved.
  11. *
  12. * Redistribution and use in source and binary forms, with or
  13. * without modification, are permitted provided that the following
  14. * conditions are met:
  15. *
  16. * - Redistributions of source code must retain the above copyright
  17. * notice, this list of conditions and the following disclaimer.
  18. *
  19. * - Redistributions in binary form must reproduce the above
  20. * copyright notice, this list of conditions and the following
  21. * disclaimer in the documentation and/or other materials provided
  22. * with the distribution.
  23. *
  24. * - Neither the name of the Eclipse Foundation, Inc. nor the
  25. * names of its contributors may be used to endorse or promote
  26. * products derived from this software without specific prior
  27. * written permission.
  28. *
  29. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  30. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  31. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  32. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  33. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  34. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  35. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  36. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  37. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  38. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  39. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  40. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  41. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  42. */
  43. package org.eclipse.jgit.lib;
  44. import java.io.File;
  45. import java.io.IOException;
  46. import java.lang.ref.Reference;
  47. import java.lang.ref.SoftReference;
  48. import java.util.ArrayList;
  49. import java.util.Collection;
  50. import java.util.Iterator;
  51. import java.util.Map;
  52. import java.util.concurrent.ConcurrentHashMap;
  53. import org.eclipse.jgit.errors.RepositoryNotFoundException;
  54. import org.eclipse.jgit.internal.storage.file.FileRepository;
  55. import org.eclipse.jgit.util.FS;
  56. import org.eclipse.jgit.util.IO;
  57. import org.eclipse.jgit.util.RawParseUtils;
  58. /** Cache of active {@link Repository} instances. */
  59. public class RepositoryCache {
  60. private static final RepositoryCache cache = new RepositoryCache();
  61. /**
  62. * Open an existing repository, reusing a cached instance if possible.
  63. * <p>
  64. * When done with the repository, the caller must call
  65. * {@link Repository#close()} to decrement the repository's usage counter.
  66. *
  67. * @param location
  68. * where the local repository is. Typically a {@link FileKey}.
  69. * @return the repository instance requested; caller must close when done.
  70. * @throws IOException
  71. * the repository could not be read (likely its core.version
  72. * property is not supported).
  73. * @throws RepositoryNotFoundException
  74. * there is no repository at the given location.
  75. */
  76. public static Repository open(final Key location) throws IOException,
  77. RepositoryNotFoundException {
  78. return open(location, true);
  79. }
  80. /**
  81. * Open a repository, reusing a cached instance if possible.
  82. * <p>
  83. * When done with the repository, the caller must call
  84. * {@link Repository#close()} to decrement the repository's usage counter.
  85. *
  86. * @param location
  87. * where the local repository is. Typically a {@link FileKey}.
  88. * @param mustExist
  89. * If true, and the repository is not found, throws {@code
  90. * RepositoryNotFoundException}. If false, a repository instance
  91. * is created and registered anyway.
  92. * @return the repository instance requested; caller must close when done.
  93. * @throws IOException
  94. * the repository could not be read (likely its core.version
  95. * property is not supported).
  96. * @throws RepositoryNotFoundException
  97. * There is no repository at the given location, only thrown if
  98. * {@code mustExist} is true.
  99. */
  100. public static Repository open(final Key location, final boolean mustExist)
  101. throws IOException {
  102. return cache.openRepository(location, mustExist);
  103. }
  104. /**
  105. * Register one repository into the cache.
  106. * <p>
  107. * During registration the cache automatically increments the usage counter,
  108. * permitting it to retain the reference. A {@link FileKey} for the
  109. * repository's {@link Repository#getDirectory()} is used to index the
  110. * repository in the cache.
  111. * <p>
  112. * If another repository already is registered in the cache at this
  113. * location, the other instance is closed.
  114. *
  115. * @param db
  116. * repository to register.
  117. */
  118. public static void register(final Repository db) {
  119. if (db.getDirectory() != null) {
  120. FileKey key = FileKey.exact(db.getDirectory(), db.getFS());
  121. cache.registerRepository(key, db);
  122. }
  123. }
  124. /**
  125. * Remove a repository from the cache.
  126. * <p>
  127. * Removes a repository from the cache, if it is still registered here,
  128. * permitting it to close.
  129. *
  130. * @param db
  131. * repository to unregister.
  132. */
  133. public static void close(final Repository db) {
  134. if (db.getDirectory() != null) {
  135. FileKey key = FileKey.exact(db.getDirectory(), db.getFS());
  136. cache.unregisterRepository(key);
  137. }
  138. }
  139. /**
  140. * Remove a repository from the cache.
  141. * <p>
  142. * Removes a repository from the cache, if it is still registered here,
  143. * permitting it to close.
  144. *
  145. * @param location
  146. * location of the repository to remove.
  147. * @since 4.1
  148. */
  149. public static void unregister(Key location) {
  150. cache.unregisterRepository(location);
  151. }
  152. /**
  153. * @return the locations of all repositories registered in the cache.
  154. * @since 4.1
  155. */
  156. public static Collection<Key> getRegisteredKeys() {
  157. return cache.getKeys();
  158. }
  159. /** Unregister all repositories from the cache. */
  160. public static void clear() {
  161. cache.clearAll();
  162. }
  163. private final ConcurrentHashMap<Key, Reference<Repository>> cacheMap;
  164. private final Lock[] openLocks;
  165. private RepositoryCache() {
  166. cacheMap = new ConcurrentHashMap<Key, Reference<Repository>>();
  167. openLocks = new Lock[4];
  168. for (int i = 0; i < openLocks.length; i++)
  169. openLocks[i] = new Lock();
  170. }
  171. @SuppressWarnings("resource")
  172. private Repository openRepository(final Key location,
  173. final boolean mustExist) throws IOException {
  174. Reference<Repository> ref = cacheMap.get(location);
  175. Repository db = ref != null ? ref.get() : null;
  176. if (db == null) {
  177. synchronized (lockFor(location)) {
  178. ref = cacheMap.get(location);
  179. db = ref != null ? ref.get() : null;
  180. if (db == null) {
  181. db = location.open(mustExist);
  182. ref = new SoftReference<Repository>(db);
  183. cacheMap.put(location, ref);
  184. }
  185. }
  186. }
  187. db.incrementOpen();
  188. return db;
  189. }
  190. private void registerRepository(final Key location, final Repository db) {
  191. db.incrementOpen();
  192. SoftReference<Repository> newRef = new SoftReference<Repository>(db);
  193. Reference<Repository> oldRef = cacheMap.put(location, newRef);
  194. Repository oldDb = oldRef != null ? oldRef.get() : null;
  195. if (oldDb != null)
  196. oldDb.close();
  197. }
  198. private void unregisterRepository(final Key location) {
  199. Reference<Repository> oldRef = cacheMap.remove(location);
  200. Repository oldDb = oldRef != null ? oldRef.get() : null;
  201. if (oldDb != null)
  202. oldDb.close();
  203. }
  204. private Collection<Key> getKeys() {
  205. return new ArrayList<Key>(cacheMap.keySet());
  206. }
  207. private void clearAll() {
  208. for (int stage = 0; stage < 2; stage++) {
  209. for (Iterator<Map.Entry<Key, Reference<Repository>>> i = cacheMap
  210. .entrySet().iterator(); i.hasNext();) {
  211. final Map.Entry<Key, Reference<Repository>> e = i.next();
  212. final Repository db = e.getValue().get();
  213. if (db != null)
  214. db.close();
  215. i.remove();
  216. }
  217. }
  218. }
  219. private Lock lockFor(final Key location) {
  220. return openLocks[(location.hashCode() >>> 1) % openLocks.length];
  221. }
  222. private static class Lock {
  223. // Used only for its monitor.
  224. }
  225. /**
  226. * Abstract hash key for {@link RepositoryCache} entries.
  227. * <p>
  228. * A Key instance should be lightweight, and implement hashCode() and
  229. * equals() such that two Key instances are equal if they represent the same
  230. * Repository location.
  231. */
  232. public static interface Key {
  233. /**
  234. * Called by {@link RepositoryCache#open(Key)} if it doesn't exist yet.
  235. * <p>
  236. * If a repository does not exist yet in the cache, the cache will call
  237. * this method to acquire a handle to it.
  238. *
  239. * @param mustExist
  240. * true if the repository must exist in order to be opened;
  241. * false if a new non-existent repository is permitted to be
  242. * created (the caller is responsible for calling create).
  243. * @return the new repository instance.
  244. * @throws IOException
  245. * the repository could not be read (likely its core.version
  246. * property is not supported).
  247. * @throws RepositoryNotFoundException
  248. * There is no repository at the given location, only thrown
  249. * if {@code mustExist} is true.
  250. */
  251. Repository open(boolean mustExist) throws IOException,
  252. RepositoryNotFoundException;
  253. }
  254. /** Location of a Repository, using the standard java.io.File API. */
  255. public static class FileKey implements Key {
  256. /**
  257. * Obtain a pointer to an exact location on disk.
  258. * <p>
  259. * No guessing is performed, the given location is exactly the GIT_DIR
  260. * directory of the repository.
  261. *
  262. * @param directory
  263. * location where the repository database is.
  264. * @param fs
  265. * the file system abstraction which will be necessary to
  266. * perform certain file system operations.
  267. * @return a key for the given directory.
  268. * @see #lenient(File, FS)
  269. */
  270. public static FileKey exact(final File directory, FS fs) {
  271. return new FileKey(directory, fs);
  272. }
  273. /**
  274. * Obtain a pointer to a location on disk.
  275. * <p>
  276. * The method performs some basic guessing to locate the repository.
  277. * Searched paths are:
  278. * <ol>
  279. * <li>{@code directory} // assume exact match</li>
  280. * <li>{@code directory} + "/.git" // assume working directory</li>
  281. * <li>{@code directory} + ".git" // assume bare</li>
  282. * </ol>
  283. *
  284. * @param directory
  285. * location where the repository database might be.
  286. * @param fs
  287. * the file system abstraction which will be necessary to
  288. * perform certain file system operations.
  289. * @return a key for the given directory.
  290. * @see #exact(File, FS)
  291. */
  292. public static FileKey lenient(final File directory, FS fs) {
  293. final File gitdir = resolve(directory, fs);
  294. return new FileKey(gitdir != null ? gitdir : directory, fs);
  295. }
  296. private final File path;
  297. private final FS fs;
  298. /**
  299. * @param directory
  300. * exact location of the repository.
  301. * @param fs
  302. * the file system abstraction which will be necessary to
  303. * perform certain file system operations.
  304. */
  305. protected FileKey(final File directory, FS fs) {
  306. path = canonical(directory);
  307. this.fs = fs;
  308. }
  309. private static File canonical(final File path) {
  310. try {
  311. return path.getCanonicalFile();
  312. } catch (IOException e) {
  313. return path.getAbsoluteFile();
  314. }
  315. }
  316. /** @return location supplied to the constructor. */
  317. public final File getFile() {
  318. return path;
  319. }
  320. public Repository open(final boolean mustExist) throws IOException {
  321. if (mustExist && !isGitRepository(path, fs))
  322. throw new RepositoryNotFoundException(path);
  323. return new FileRepository(path);
  324. }
  325. @Override
  326. public int hashCode() {
  327. return path.hashCode();
  328. }
  329. @Override
  330. public boolean equals(final Object o) {
  331. return o instanceof FileKey && path.equals(((FileKey) o).path);
  332. }
  333. @Override
  334. public String toString() {
  335. return path.toString();
  336. }
  337. /**
  338. * Guess if a directory contains a Git repository.
  339. * <p>
  340. * This method guesses by looking for the existence of some key files
  341. * and directories.
  342. *
  343. * @param dir
  344. * the location of the directory to examine.
  345. * @param fs
  346. * the file system abstraction which will be necessary to
  347. * perform certain file system operations.
  348. * @return true if the directory "looks like" a Git repository; false if
  349. * it doesn't look enough like a Git directory to really be a
  350. * Git directory.
  351. */
  352. public static boolean isGitRepository(final File dir, FS fs) {
  353. return fs.resolve(dir, "objects").exists() //$NON-NLS-1$
  354. && fs.resolve(dir, "refs").exists() //$NON-NLS-1$
  355. && isValidHead(new File(dir, Constants.HEAD));
  356. }
  357. private static boolean isValidHead(final File head) {
  358. final String ref = readFirstLine(head);
  359. return ref != null
  360. && (ref.startsWith("ref: refs/") || ObjectId.isId(ref)); //$NON-NLS-1$
  361. }
  362. private static String readFirstLine(final File head) {
  363. try {
  364. final byte[] buf = IO.readFully(head, 4096);
  365. int n = buf.length;
  366. if (n == 0)
  367. return null;
  368. if (buf[n - 1] == '\n')
  369. n--;
  370. return RawParseUtils.decode(buf, 0, n);
  371. } catch (IOException e) {
  372. return null;
  373. }
  374. }
  375. /**
  376. * Guess the proper path for a Git repository.
  377. * <p>
  378. * The method performs some basic guessing to locate the repository.
  379. * Searched paths are:
  380. * <ol>
  381. * <li>{@code directory} // assume exact match</li>
  382. * <li>{@code directory} + "/.git" // assume working directory</li>
  383. * <li>{@code directory} + ".git" // assume bare</li>
  384. * </ol>
  385. *
  386. * @param directory
  387. * location to guess from. Several permutations are tried.
  388. * @param fs
  389. * the file system abstraction which will be necessary to
  390. * perform certain file system operations.
  391. * @return the actual directory location if a better match is found;
  392. * null if there is no suitable match.
  393. */
  394. public static File resolve(final File directory, FS fs) {
  395. if (isGitRepository(directory, fs))
  396. return directory;
  397. if (isGitRepository(new File(directory, Constants.DOT_GIT), fs))
  398. return new File(directory, Constants.DOT_GIT);
  399. final String name = directory.getName();
  400. final File parent = directory.getParentFile();
  401. if (isGitRepository(new File(parent, name + Constants.DOT_GIT_EXT), fs))
  402. return new File(parent, name + Constants.DOT_GIT_EXT);
  403. return null;
  404. }
  405. }
  406. }