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