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

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