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