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