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 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  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 java.util.concurrent.ScheduledFuture;
  54. import java.util.concurrent.ScheduledThreadPoolExecutor;
  55. import java.util.concurrent.TimeUnit;
  56. import org.eclipse.jgit.annotations.NonNull;
  57. import org.eclipse.jgit.errors.RepositoryNotFoundException;
  58. import org.eclipse.jgit.internal.storage.file.FileRepository;
  59. import org.eclipse.jgit.util.FS;
  60. import org.eclipse.jgit.util.IO;
  61. import org.eclipse.jgit.util.RawParseUtils;
  62. import org.slf4j.Logger;
  63. import org.slf4j.LoggerFactory;
  64. /** Cache of active {@link Repository} instances. */
  65. public class RepositoryCache {
  66. private static final RepositoryCache cache = new RepositoryCache();
  67. private final static Logger LOG = LoggerFactory
  68. .getLogger(RepositoryCache.class);
  69. /**
  70. * Open an existing repository, reusing a cached instance if possible.
  71. * <p>
  72. * When done with the repository, the caller must call
  73. * {@link Repository#close()} to decrement the repository's usage counter.
  74. *
  75. * @param location
  76. * where the local repository is. Typically a {@link FileKey}.
  77. * @return the repository instance requested; caller must close when done.
  78. * @throws IOException
  79. * the repository could not be read (likely its core.version
  80. * property is not supported).
  81. * @throws RepositoryNotFoundException
  82. * there is no repository at the given location.
  83. */
  84. public static Repository open(final Key location) throws IOException,
  85. RepositoryNotFoundException {
  86. return open(location, true);
  87. }
  88. /**
  89. * Open a repository, reusing a cached instance if possible.
  90. * <p>
  91. * When done with the repository, the caller must call
  92. * {@link Repository#close()} to decrement the repository's usage counter.
  93. *
  94. * @param location
  95. * where the local repository is. Typically a {@link FileKey}.
  96. * @param mustExist
  97. * If true, and the repository is not found, throws {@code
  98. * RepositoryNotFoundException}. If false, a repository instance
  99. * is created and registered anyway.
  100. * @return the repository instance requested; caller must close when done.
  101. * @throws IOException
  102. * the repository could not be read (likely its core.version
  103. * property is not supported).
  104. * @throws RepositoryNotFoundException
  105. * There is no repository at the given location, only thrown if
  106. * {@code mustExist} is true.
  107. */
  108. public static Repository open(final Key location, final boolean mustExist)
  109. throws IOException {
  110. return cache.openRepository(location, mustExist);
  111. }
  112. /**
  113. * Register one repository into the cache.
  114. * <p>
  115. * During registration the cache automatically increments the usage counter,
  116. * permitting it to retain the reference. A {@link FileKey} for the
  117. * repository's {@link Repository#getDirectory()} is used to index the
  118. * repository in the cache.
  119. * <p>
  120. * If another repository already is registered in the cache at this
  121. * location, the other instance is closed.
  122. *
  123. * @param db
  124. * repository to register.
  125. */
  126. public static void register(final Repository db) {
  127. if (db.getDirectory() != null) {
  128. FileKey key = FileKey.exact(db.getDirectory(), db.getFS());
  129. cache.registerRepository(key, db);
  130. }
  131. }
  132. /**
  133. * Close and remove a repository from the cache.
  134. * <p>
  135. * Removes a repository from the cache, if it is still registered here, and
  136. * close it.
  137. *
  138. * @param db
  139. * repository to unregister.
  140. */
  141. public static void close(@NonNull final Repository db) {
  142. if (db.getDirectory() != null) {
  143. FileKey key = FileKey.exact(db.getDirectory(), db.getFS());
  144. cache.unregisterAndCloseRepository(key, db);
  145. }
  146. }
  147. /**
  148. * Remove a repository from the cache.
  149. * <p>
  150. * Removes a repository from the cache, if it is still registered here. This
  151. * method will not close the repository, only remove it from the cache. See
  152. * {@link RepositoryCache#close(Repository)} to remove and close the
  153. * repository.
  154. *
  155. * @param db
  156. * repository to unregister.
  157. * @since 4.3
  158. */
  159. public static void unregister(final Repository db) {
  160. if (db.getDirectory() != null) {
  161. unregister(FileKey.exact(db.getDirectory(), db.getFS()));
  162. }
  163. }
  164. /**
  165. * Remove a repository from the cache.
  166. * <p>
  167. * Removes a repository from the cache, if it is still registered here. This
  168. * method will not close the repository, only remove it from the cache. See
  169. * {@link RepositoryCache#close(Repository)} to remove and close the
  170. * repository.
  171. *
  172. * @param location
  173. * location of the repository to remove.
  174. * @since 4.1
  175. */
  176. public static void unregister(Key location) {
  177. cache.unregisterRepository(location);
  178. }
  179. /**
  180. * @return the locations of all repositories registered in the cache.
  181. * @since 4.1
  182. */
  183. public static Collection<Key> getRegisteredKeys() {
  184. return cache.getKeys();
  185. }
  186. static boolean isCached(@NonNull Repository repo) {
  187. File gitDir = repo.getDirectory();
  188. if (gitDir == null) {
  189. return false;
  190. }
  191. FileKey key = new FileKey(gitDir, repo.getFS());
  192. Reference<Repository> repoRef = cache.cacheMap.get(key);
  193. return repoRef != null && repoRef.get() == repo;
  194. }
  195. /** Unregister all repositories from the cache. */
  196. public static void clear() {
  197. cache.clearAll();
  198. }
  199. static void clearExpired() {
  200. cache.clearAllExpired();
  201. }
  202. static void reconfigure(RepositoryCacheConfig repositoryCacheConfig) {
  203. cache.configureEviction(repositoryCacheConfig);
  204. }
  205. private final ConcurrentHashMap<Key, Reference<Repository>> cacheMap;
  206. private final Lock[] openLocks;
  207. private ScheduledFuture<?> cleanupTask;
  208. private volatile long expireAfter;
  209. private RepositoryCache() {
  210. cacheMap = new ConcurrentHashMap<Key, Reference<Repository>>();
  211. openLocks = new Lock[4];
  212. for (int i = 0; i < openLocks.length; i++) {
  213. openLocks[i] = new Lock();
  214. }
  215. configureEviction(new RepositoryCacheConfig());
  216. }
  217. private void configureEviction(
  218. RepositoryCacheConfig repositoryCacheConfig) {
  219. expireAfter = repositoryCacheConfig.getExpireAfter();
  220. ScheduledThreadPoolExecutor scheduler = WorkQueue.getExecutor();
  221. synchronized (scheduler) {
  222. if (cleanupTask != null) {
  223. cleanupTask.cancel(false);
  224. }
  225. long delay = repositoryCacheConfig.getCleanupDelay();
  226. if (delay == RepositoryCacheConfig.NO_CLEANUP) {
  227. return;
  228. }
  229. cleanupTask = scheduler.scheduleWithFixedDelay(new Runnable() {
  230. @Override
  231. public void run() {
  232. try {
  233. cache.clearAllExpired();
  234. } catch (Throwable e) {
  235. LOG.error(e.getMessage(), e);
  236. }
  237. }
  238. }, delay, delay, TimeUnit.MILLISECONDS);
  239. }
  240. }
  241. @SuppressWarnings("resource")
  242. private Repository openRepository(final Key location,
  243. final boolean mustExist) throws IOException {
  244. Reference<Repository> ref = cacheMap.get(location);
  245. Repository db = ref != null ? ref.get() : null;
  246. if (db == null) {
  247. synchronized (lockFor(location)) {
  248. ref = cacheMap.get(location);
  249. db = ref != null ? ref.get() : null;
  250. if (db == null) {
  251. db = location.open(mustExist);
  252. ref = new SoftReference<Repository>(db);
  253. cacheMap.put(location, ref);
  254. } else {
  255. db.incrementOpen();
  256. }
  257. }
  258. } else {
  259. db.incrementOpen();
  260. }
  261. return db;
  262. }
  263. private void registerRepository(final Key location, final Repository db) {
  264. SoftReference<Repository> newRef = new SoftReference<Repository>(db);
  265. Reference<Repository> oldRef = cacheMap.put(location, newRef);
  266. Repository oldDb = oldRef != null ? oldRef.get() : null;
  267. if (oldDb != null)
  268. oldDb.close();
  269. }
  270. private Repository unregisterRepository(final Key location) {
  271. Reference<Repository> oldRef = cacheMap.remove(location);
  272. return oldRef != null ? oldRef.get() : null;
  273. }
  274. private boolean isExpired(Repository db) {
  275. return db != null && db.useCnt.get() == 0
  276. && (System.currentTimeMillis() - db.closedAt.get() > expireAfter);
  277. }
  278. private void unregisterAndCloseRepository(final Key location,
  279. Repository db) {
  280. synchronized (lockFor(location)) {
  281. if (isExpired(db)) {
  282. Repository oldDb = unregisterRepository(location);
  283. if (oldDb != null) {
  284. oldDb.close();
  285. }
  286. }
  287. }
  288. }
  289. private Collection<Key> getKeys() {
  290. return new ArrayList<Key>(cacheMap.keySet());
  291. }
  292. private void clearAllExpired() {
  293. for (Reference<Repository> ref : cacheMap.values()) {
  294. Repository db = ref.get();
  295. if (isExpired(db)) {
  296. RepositoryCache.close(db);
  297. }
  298. }
  299. }
  300. private void clearAll() {
  301. for (int stage = 0; stage < 2; stage++) {
  302. for (Iterator<Map.Entry<Key, Reference<Repository>>> i = cacheMap
  303. .entrySet().iterator(); i.hasNext();) {
  304. final Map.Entry<Key, Reference<Repository>> e = i.next();
  305. final Repository db = e.getValue().get();
  306. if (db != null)
  307. db.close();
  308. i.remove();
  309. }
  310. }
  311. }
  312. private Lock lockFor(final Key location) {
  313. return openLocks[(location.hashCode() >>> 1) % openLocks.length];
  314. }
  315. private static class Lock {
  316. // Used only for its monitor.
  317. }
  318. /**
  319. * Abstract hash key for {@link RepositoryCache} entries.
  320. * <p>
  321. * A Key instance should be lightweight, and implement hashCode() and
  322. * equals() such that two Key instances are equal if they represent the same
  323. * Repository location.
  324. */
  325. public static interface Key {
  326. /**
  327. * Called by {@link RepositoryCache#open(Key)} if it doesn't exist yet.
  328. * <p>
  329. * If a repository does not exist yet in the cache, the cache will call
  330. * this method to acquire a handle to it.
  331. *
  332. * @param mustExist
  333. * true if the repository must exist in order to be opened;
  334. * false if a new non-existent repository is permitted to be
  335. * created (the caller is responsible for calling create).
  336. * @return the new repository instance.
  337. * @throws IOException
  338. * the repository could not be read (likely its core.version
  339. * property is not supported).
  340. * @throws RepositoryNotFoundException
  341. * There is no repository at the given location, only thrown
  342. * if {@code mustExist} is true.
  343. */
  344. Repository open(boolean mustExist) throws IOException,
  345. RepositoryNotFoundException;
  346. }
  347. /** Location of a Repository, using the standard java.io.File API. */
  348. public static class FileKey implements Key {
  349. /**
  350. * Obtain a pointer to an exact location on disk.
  351. * <p>
  352. * No guessing is performed, the given location is exactly the GIT_DIR
  353. * directory of the repository.
  354. *
  355. * @param directory
  356. * location where the repository database is.
  357. * @param fs
  358. * the file system abstraction which will be necessary to
  359. * perform certain file system operations.
  360. * @return a key for the given directory.
  361. * @see #lenient(File, FS)
  362. */
  363. public static FileKey exact(final File directory, FS fs) {
  364. return new FileKey(directory, fs);
  365. }
  366. /**
  367. * Obtain a pointer to a location on disk.
  368. * <p>
  369. * The method performs some basic guessing to locate the repository.
  370. * Searched paths are:
  371. * <ol>
  372. * <li>{@code directory} // assume exact match</li>
  373. * <li>{@code directory} + "/.git" // assume working directory</li>
  374. * <li>{@code directory} + ".git" // assume bare</li>
  375. * </ol>
  376. *
  377. * @param directory
  378. * location where the repository database might be.
  379. * @param fs
  380. * the file system abstraction which will be necessary to
  381. * perform certain file system operations.
  382. * @return a key for the given directory.
  383. * @see #exact(File, FS)
  384. */
  385. public static FileKey lenient(final File directory, FS fs) {
  386. final File gitdir = resolve(directory, fs);
  387. return new FileKey(gitdir != null ? gitdir : directory, fs);
  388. }
  389. private final File path;
  390. private final FS fs;
  391. /**
  392. * @param directory
  393. * exact location of the repository.
  394. * @param fs
  395. * the file system abstraction which will be necessary to
  396. * perform certain file system operations.
  397. */
  398. protected FileKey(final File directory, FS fs) {
  399. path = canonical(directory);
  400. this.fs = fs;
  401. }
  402. private static File canonical(final File path) {
  403. try {
  404. return path.getCanonicalFile();
  405. } catch (IOException e) {
  406. return path.getAbsoluteFile();
  407. }
  408. }
  409. /** @return location supplied to the constructor. */
  410. public final File getFile() {
  411. return path;
  412. }
  413. public Repository open(final boolean mustExist) throws IOException {
  414. if (mustExist && !isGitRepository(path, fs))
  415. throw new RepositoryNotFoundException(path);
  416. return new FileRepository(path);
  417. }
  418. @Override
  419. public int hashCode() {
  420. return path.hashCode();
  421. }
  422. @Override
  423. public boolean equals(final Object o) {
  424. return o instanceof FileKey && path.equals(((FileKey) o).path);
  425. }
  426. @Override
  427. public String toString() {
  428. return path.toString();
  429. }
  430. /**
  431. * Guess if a directory contains a Git repository.
  432. * <p>
  433. * This method guesses by looking for the existence of some key files
  434. * and directories.
  435. *
  436. * @param dir
  437. * the location of the directory to examine.
  438. * @param fs
  439. * the file system abstraction which will be necessary to
  440. * perform certain file system operations.
  441. * @return true if the directory "looks like" a Git repository; false if
  442. * it doesn't look enough like a Git directory to really be a
  443. * Git directory.
  444. */
  445. public static boolean isGitRepository(final File dir, FS fs) {
  446. return fs.resolve(dir, "objects").exists() //$NON-NLS-1$
  447. && fs.resolve(dir, "refs").exists() //$NON-NLS-1$
  448. && isValidHead(new File(dir, Constants.HEAD));
  449. }
  450. private static boolean isValidHead(final File head) {
  451. final String ref = readFirstLine(head);
  452. return ref != null
  453. && (ref.startsWith("ref: refs/") || ObjectId.isId(ref)); //$NON-NLS-1$
  454. }
  455. private static String readFirstLine(final File head) {
  456. try {
  457. final byte[] buf = IO.readFully(head, 4096);
  458. int n = buf.length;
  459. if (n == 0)
  460. return null;
  461. if (buf[n - 1] == '\n')
  462. n--;
  463. return RawParseUtils.decode(buf, 0, n);
  464. } catch (IOException e) {
  465. return null;
  466. }
  467. }
  468. /**
  469. * Guess the proper path for a Git repository.
  470. * <p>
  471. * The method performs some basic guessing to locate the repository.
  472. * Searched paths are:
  473. * <ol>
  474. * <li>{@code directory} // assume exact match</li>
  475. * <li>{@code directory} + "/.git" // assume working directory</li>
  476. * <li>{@code directory} + ".git" // assume bare</li>
  477. * </ol>
  478. *
  479. * @param directory
  480. * location to guess from. Several permutations are tried.
  481. * @param fs
  482. * the file system abstraction which will be necessary to
  483. * perform certain file system operations.
  484. * @return the actual directory location if a better match is found;
  485. * null if there is no suitable match.
  486. */
  487. public static File resolve(final File directory, FS fs) {
  488. if (isGitRepository(directory, fs))
  489. return directory;
  490. if (isGitRepository(new File(directory, Constants.DOT_GIT), fs))
  491. return new File(directory, Constants.DOT_GIT);
  492. final String name = directory.getName();
  493. final File parent = directory.getParentFile();
  494. if (isGitRepository(new File(parent, name + Constants.DOT_GIT_EXT), fs))
  495. return new File(parent, name + Constants.DOT_GIT_EXT);
  496. return null;
  497. }
  498. }
  499. }