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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  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 static final 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(() -> {
  237. try {
  238. cache.clearAllExpired();
  239. } catch (Throwable e) {
  240. LOG.error(e.getMessage(), e);
  241. }
  242. }, delay, delay, TimeUnit.MILLISECONDS);
  243. }
  244. }
  245. private Repository openRepository(final Key location,
  246. final boolean mustExist) throws IOException {
  247. Repository db = cacheMap.get(location);
  248. if (db == null) {
  249. synchronized (lockFor(location)) {
  250. db = cacheMap.get(location);
  251. if (db == null) {
  252. db = location.open(mustExist);
  253. cacheMap.put(location, db);
  254. } else {
  255. db.incrementOpen();
  256. }
  257. }
  258. } else {
  259. db.incrementOpen();
  260. }
  261. return db;
  262. }
  263. private void registerRepository(Key location, Repository db) {
  264. try (Repository oldDb = cacheMap.put(location, db)) {
  265. // oldDb is auto-closed
  266. }
  267. }
  268. private Repository unregisterRepository(Key location) {
  269. return cacheMap.remove(location);
  270. }
  271. private boolean isExpired(Repository db) {
  272. return db != null && db.useCnt.get() <= 0
  273. && (System.currentTimeMillis() - db.closedAt.get() > expireAfter);
  274. }
  275. private void unregisterAndCloseRepository(Key location) {
  276. synchronized (lockFor(location)) {
  277. Repository oldDb = unregisterRepository(location);
  278. if (oldDb != null) {
  279. oldDb.doClose();
  280. }
  281. }
  282. }
  283. private Collection<Key> getKeys() {
  284. return new ArrayList<>(cacheMap.keySet());
  285. }
  286. private void clearAllExpired() {
  287. for (Repository db : cacheMap.values()) {
  288. if (isExpired(db)) {
  289. RepositoryCache.close(db);
  290. }
  291. }
  292. }
  293. private void clearAll() {
  294. for (Key k : cacheMap.keySet()) {
  295. unregisterAndCloseRepository(k);
  296. }
  297. }
  298. private Lock lockFor(Key location) {
  299. return openLocks[(location.hashCode() >>> 1) % openLocks.length];
  300. }
  301. private static class Lock {
  302. // Used only for its monitor.
  303. }
  304. /**
  305. * Abstract hash key for {@link RepositoryCache} entries.
  306. * <p>
  307. * A Key instance should be lightweight, and implement hashCode() and
  308. * equals() such that two Key instances are equal if they represent the same
  309. * Repository location.
  310. */
  311. public static interface Key {
  312. /**
  313. * Called by {@link RepositoryCache#open(Key)} if it doesn't exist yet.
  314. * <p>
  315. * If a repository does not exist yet in the cache, the cache will call
  316. * this method to acquire a handle to it.
  317. *
  318. * @param mustExist
  319. * true if the repository must exist in order to be opened;
  320. * false if a new non-existent repository is permitted to be
  321. * created (the caller is responsible for calling create).
  322. * @return the new repository instance.
  323. * @throws IOException
  324. * the repository could not be read (likely its core.version
  325. * property is not supported).
  326. * @throws RepositoryNotFoundException
  327. * There is no repository at the given location, only thrown
  328. * if {@code mustExist} is true.
  329. */
  330. Repository open(boolean mustExist) throws IOException,
  331. RepositoryNotFoundException;
  332. }
  333. /** Location of a Repository, using the standard java.io.File API. */
  334. public static class FileKey implements Key {
  335. /**
  336. * Obtain a pointer to an exact location on disk.
  337. * <p>
  338. * No guessing is performed, the given location is exactly the GIT_DIR
  339. * directory of the repository.
  340. *
  341. * @param directory
  342. * location where the repository database is.
  343. * @param fs
  344. * the file system abstraction which will be necessary to
  345. * perform certain file system operations.
  346. * @return a key for the given directory.
  347. * @see #lenient(File, FS)
  348. */
  349. public static FileKey exact(File directory, FS fs) {
  350. return new FileKey(directory, fs);
  351. }
  352. /**
  353. * Obtain a pointer to a location on disk.
  354. * <p>
  355. * The method performs some basic guessing to locate the repository.
  356. * Searched paths are:
  357. * <ol>
  358. * <li>{@code directory} // assume exact match</li>
  359. * <li>{@code directory} + "/.git" // assume working directory</li>
  360. * <li>{@code directory} + ".git" // assume bare</li>
  361. * </ol>
  362. *
  363. * @param directory
  364. * location where the repository database might be.
  365. * @param fs
  366. * the file system abstraction which will be necessary to
  367. * perform certain file system operations.
  368. * @return a key for the given directory.
  369. * @see #exact(File, FS)
  370. */
  371. public static FileKey lenient(File directory, FS fs) {
  372. final File gitdir = resolve(directory, fs);
  373. return new FileKey(gitdir != null ? gitdir : directory, fs);
  374. }
  375. private final File path;
  376. private final FS fs;
  377. /**
  378. * @param directory
  379. * exact location of the repository.
  380. * @param fs
  381. * the file system abstraction which will be necessary to
  382. * perform certain file system operations.
  383. */
  384. protected FileKey(File directory, FS fs) {
  385. path = canonical(directory);
  386. this.fs = fs;
  387. }
  388. private static File canonical(File path) {
  389. try {
  390. return path.getCanonicalFile();
  391. } catch (IOException e) {
  392. return path.getAbsoluteFile();
  393. }
  394. }
  395. /** @return location supplied to the constructor. */
  396. public final File getFile() {
  397. return path;
  398. }
  399. @Override
  400. public Repository open(boolean mustExist) throws IOException {
  401. if (mustExist && !isGitRepository(path, fs))
  402. throw new RepositoryNotFoundException(path);
  403. return new FileRepository(path);
  404. }
  405. @Override
  406. public int hashCode() {
  407. return path.hashCode();
  408. }
  409. @Override
  410. public boolean equals(Object o) {
  411. return o instanceof FileKey && path.equals(((FileKey) o).path);
  412. }
  413. @Override
  414. public String toString() {
  415. return path.toString();
  416. }
  417. /**
  418. * Guess if a directory contains a Git repository.
  419. * <p>
  420. * This method guesses by looking for the existence of some key files
  421. * and directories.
  422. *
  423. * @param dir
  424. * the location of the directory to examine.
  425. * @param fs
  426. * the file system abstraction which will be necessary to
  427. * perform certain file system operations.
  428. * @return true if the directory "looks like" a Git repository; false if
  429. * it doesn't look enough like a Git directory to really be a
  430. * Git directory.
  431. */
  432. public static boolean isGitRepository(File dir, FS fs) {
  433. return fs.resolve(dir, Constants.OBJECTS).exists()
  434. && fs.resolve(dir, "refs").exists() //$NON-NLS-1$
  435. && (fs.resolve(dir, Constants.REFTABLE).exists()
  436. || isValidHead(new File(dir, Constants.HEAD)));
  437. }
  438. private static boolean isValidHead(File head) {
  439. final String ref = readFirstLine(head);
  440. return ref != null
  441. && (ref.startsWith("ref: refs/") || ObjectId.isId(ref)); //$NON-NLS-1$
  442. }
  443. private static String readFirstLine(File head) {
  444. try {
  445. final byte[] buf = IO.readFully(head, 4096);
  446. int n = buf.length;
  447. if (n == 0)
  448. return null;
  449. if (buf[n - 1] == '\n')
  450. n--;
  451. return RawParseUtils.decode(buf, 0, n);
  452. } catch (IOException e) {
  453. return null;
  454. }
  455. }
  456. /**
  457. * Guess the proper path for a Git repository.
  458. * <p>
  459. * The method performs some basic guessing to locate the repository.
  460. * Searched paths are:
  461. * <ol>
  462. * <li>{@code directory} // assume exact match</li>
  463. * <li>{@code directory} + "/.git" // assume working directory</li>
  464. * <li>{@code directory} + ".git" // assume bare</li>
  465. * </ol>
  466. *
  467. * @param directory
  468. * location to guess from. Several permutations are tried.
  469. * @param fs
  470. * the file system abstraction which will be necessary to
  471. * perform certain file system operations.
  472. * @return the actual directory location if a better match is found;
  473. * null if there is no suitable match.
  474. */
  475. public static File resolve(File directory, FS fs) {
  476. if (isGitRepository(directory, fs))
  477. return directory;
  478. if (isGitRepository(new File(directory, Constants.DOT_GIT), fs))
  479. return new File(directory, Constants.DOT_GIT);
  480. final String name = directory.getName();
  481. final File parent = directory.getParentFile();
  482. if (isGitRepository(new File(parent, name + Constants.DOT_GIT_EXT), fs))
  483. return new File(parent, name + Constants.DOT_GIT_EXT);
  484. return null;
  485. }
  486. }
  487. }