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.internal.storage.file;
45  
46  import static org.eclipse.jgit.internal.storage.pack.PackExt.INDEX;
47  import static org.eclipse.jgit.internal.storage.pack.PackExt.PACK;
48  
49  import java.io.BufferedReader;
50  import java.io.File;
51  import java.io.FileInputStream;
52  import java.io.FileNotFoundException;
53  import java.io.FileReader;
54  import java.io.IOException;
55  import java.nio.file.AtomicMoveNotSupportedException;
56  import java.nio.file.Files;
57  import java.nio.file.StandardCopyOption;
58  import java.text.MessageFormat;
59  import java.util.ArrayList;
60  import java.util.Arrays;
61  import java.util.Collection;
62  import java.util.Collections;
63  import java.util.HashMap;
64  import java.util.HashSet;
65  import java.util.List;
66  import java.util.Map;
67  import java.util.Objects;
68  import java.util.Set;
69  import java.util.concurrent.atomic.AtomicReference;
70  
71  import org.eclipse.jgit.errors.CorruptObjectException;
72  import org.eclipse.jgit.errors.PackInvalidException;
73  import org.eclipse.jgit.errors.PackMismatchException;
74  import org.eclipse.jgit.internal.JGitText;
75  import org.eclipse.jgit.internal.storage.pack.ObjectToPack;
76  import org.eclipse.jgit.internal.storage.pack.PackExt;
77  import org.eclipse.jgit.internal.storage.pack.PackWriter;
78  import org.eclipse.jgit.lib.AbbreviatedObjectId;
79  import org.eclipse.jgit.lib.AnyObjectId;
80  import org.eclipse.jgit.lib.Config;
81  import org.eclipse.jgit.lib.ConfigConstants;
82  import org.eclipse.jgit.lib.Constants;
83  import org.eclipse.jgit.lib.ObjectDatabase;
84  import org.eclipse.jgit.lib.ObjectId;
85  import org.eclipse.jgit.lib.ObjectLoader;
86  import org.eclipse.jgit.lib.RepositoryCache;
87  import org.eclipse.jgit.lib.RepositoryCache.FileKey;
88  import org.eclipse.jgit.util.FS;
89  import org.eclipse.jgit.util.FileUtils;
90  import org.slf4j.Logger;
91  import org.slf4j.LoggerFactory;
92  
93  /**
94   * Traditional file system based {@link org.eclipse.jgit.lib.ObjectDatabase}.
95   * <p>
96   * This is the classical object database representation for a Git repository,
97   * where objects are stored loose by hashing them into directories by their
98   * {@link org.eclipse.jgit.lib.ObjectId}, or are stored in compressed containers
99   * known as {@link org.eclipse.jgit.internal.storage.file.PackFile}s.
100  * <p>
101  * Optionally an object database can reference one or more alternates; other
102  * ObjectDatabase instances that are searched in addition to the current
103  * database.
104  * <p>
105  * Databases are divided into two halves: a half that is considered to be fast
106  * to search (the {@code PackFile}s), and a half that is considered to be slow
107  * to search (loose objects). When alternates are present the fast half is fully
108  * searched (recursively through all alternates) before the slow half is
109  * considered.
110  */
111 public class ObjectDirectory extends FileObjectDatabase {
112 	private final static Logger LOG = LoggerFactory
113 			.getLogger(ObjectDirectory.class);
114 
115 	private static final PackList NO_PACKS = new PackList(
116 			FileSnapshot.DIRTY, new PackFile[0]);
117 
118 	/** Maximum number of candidates offered as resolutions of abbreviation. */
119 	private static final int RESOLVE_ABBREV_LIMIT = 256;
120 
121 	private final AlternateHandle handle = new AlternateHandle(this);
122 
123 	private final Config config;
124 
125 	private final File objects;
126 
127 	private final File infoDirectory;
128 
129 	private final File packDirectory;
130 
131 	private final File preservedDirectory;
132 
133 	private final File alternatesFile;
134 
135 	private final FS fs;
136 
137 	private final AtomicReference<AlternateHandle[]> alternates;
138 
139 	private final UnpackedObjectCache unpackedObjectCache;
140 
141 	private final File shallowFile;
142 
143 	private FileSnapshot shallowFileSnapshot = FileSnapshot.DIRTY;
144 
145 	private Set<ObjectId> shallowCommitsIds;
146 
147 	final AtomicReference<PackList> packList;
148 
149 	/**
150 	 * Initialize a reference to an on-disk object directory.
151 	 *
152 	 * @param cfg
153 	 *            configuration this directory consults for write settings.
154 	 * @param dir
155 	 *            the location of the <code>objects</code> directory.
156 	 * @param alternatePaths
157 	 *            a list of alternate object directories
158 	 * @param fs
159 	 *            the file system abstraction which will be necessary to perform
160 	 *            certain file system operations.
161 	 * @param shallowFile
162 	 *            file which contains IDs of shallow commits, null if shallow
163 	 *            commits handling should be turned off
164 	 * @throws java.io.IOException
165 	 *             an alternate object cannot be opened.
166 	 */
167 	public ObjectDirectory(final Config cfg, final File dir,
168 			File[] alternatePaths, FS fs, File shallowFile) throws IOException {
169 		config = cfg;
170 		objects = dir;
171 		infoDirectory = new File(objects, "info"); //$NON-NLS-1$
172 		packDirectory = new File(objects, "pack"); //$NON-NLS-1$
173 		preservedDirectory = new File(packDirectory, "preserved"); //$NON-NLS-1$
174 		alternatesFile = new File(infoDirectory, "alternates"); //$NON-NLS-1$
175 		packList = new AtomicReference<>(NO_PACKS);
176 		unpackedObjectCache = new UnpackedObjectCache();
177 		this.fs = fs;
178 		this.shallowFile = shallowFile;
179 
180 		alternates = new AtomicReference<>();
181 		if (alternatePaths != null) {
182 			AlternateHandle[] alt;
183 
184 			alt = new AlternateHandle[alternatePaths.length];
185 			for (int i = 0; i < alternatePaths.length; i++)
186 				alt[i] = openAlternate(alternatePaths[i]);
187 			alternates.set(alt);
188 		}
189 	}
190 
191 	/** {@inheritDoc} */
192 	@Override
193 	public final File getDirectory() {
194 		return objects;
195 	}
196 
197 	/**
198 	 * <p>Getter for the field <code>packDirectory</code>.</p>
199 	 *
200 	 * @return the location of the <code>pack</code> directory.
201 	 * @since 4.10
202 	 */
203 	public final File getPackDirectory() {
204 		return packDirectory;
205 	}
206 
207 	/**
208 	 * <p>Getter for the field <code>preservedDirectory</code>.</p>
209 	 *
210 	 * @return the location of the <code>preserved</code> directory.
211 	 */
212 	public final File getPreservedDirectory() {
213 		return preservedDirectory;
214 	}
215 
216 	/** {@inheritDoc} */
217 	@Override
218 	public boolean exists() {
219 		return fs.exists(objects);
220 	}
221 
222 	/** {@inheritDoc} */
223 	@Override
224 	public void create() throws IOException {
225 		FileUtils.mkdirs(objects);
226 		FileUtils.mkdir(infoDirectory);
227 		FileUtils.mkdir(packDirectory);
228 	}
229 
230 	/** {@inheritDoc} */
231 	@Override
232 	public ObjectDirectoryInserter newInserter() {
233 		return new ObjectDirectoryInserter(this, config);
234 	}
235 
236 	/**
237 	 * Create a new inserter that inserts all objects as pack files, not loose
238 	 * objects.
239 	 *
240 	 * @return new inserter.
241 	 */
242 	public PackInserter newPackInserter() {
243 		return new PackInserter(this);
244 	}
245 
246 	/** {@inheritDoc} */
247 	@Override
248 	public void close() {
249 		unpackedObjectCache.clear();
250 
251 		final PackList packs = packList.get();
252 		if (packs != NO_PACKS && packList.compareAndSet(packs, NO_PACKS)) {
253 			for (PackFile p : packs.packs)
254 				p.close();
255 		}
256 
257 		// Fully close all loaded alternates and clear the alternate list.
258 		AlternateHandle[] alt = alternates.get();
259 		if (alt != null && alternates.compareAndSet(alt, null)) {
260 			for(final AlternateHandle od : alt)
261 				od.close();
262 		}
263 	}
264 
265 	/** {@inheritDoc} */
266 	@Override
267 	public Collection<PackFile> getPacks() {
268 		PackList list = packList.get();
269 		if (list == NO_PACKS)
270 			list = scanPacks(list);
271 		PackFile[] packs = list.packs;
272 		return Collections.unmodifiableCollection(Arrays.asList(packs));
273 	}
274 
275 	/**
276 	 * {@inheritDoc}
277 	 * <p>
278 	 * Add a single existing pack to the list of available pack files.
279 	 */
280 	@Override
281 	public PackFile openPack(final File pack)
282 			throws IOException {
283 		final String p = pack.getName();
284 		if (p.length() != 50 || !p.startsWith("pack-") || !p.endsWith(".pack")) //$NON-NLS-1$ //$NON-NLS-2$
285 			throw new IOException(MessageFormat.format(JGitText.get().notAValidPack, pack));
286 
287 		// The pack and index are assumed to exist. The existence of other
288 		// extensions needs to be explicitly checked.
289 		//
290 		int extensions = PACK.getBit() | INDEX.getBit();
291 		final String base = p.substring(0, p.length() - 4);
292 		for (PackExt ext : PackExt.values()) {
293 			if ((extensions & ext.getBit()) == 0) {
294 				final String name = base + ext.getExtension();
295 				if (new File(pack.getParentFile(), name).exists())
296 					extensions |= ext.getBit();
297 			}
298 		}
299 
300 		PackFile res = new PackFile(pack, extensions);
301 		insertPack(res);
302 		return res;
303 	}
304 
305 	/** {@inheritDoc} */
306 	@Override
307 	public String toString() {
308 		return "ObjectDirectory[" + getDirectory() + "]"; //$NON-NLS-1$ //$NON-NLS-2$
309 	}
310 
311 	/** {@inheritDoc} */
312 	@Override
313 	public boolean has(AnyObjectId objectId) {
314 		return unpackedObjectCache.isUnpacked(objectId)
315 				|| hasPackedInSelfOrAlternate(objectId, null)
316 				|| hasLooseInSelfOrAlternate(objectId, null);
317 	}
318 
319 	private boolean hasPackedInSelfOrAlternate(AnyObjectId objectId,
320 			Set<AlternateHandle.Id> skips) {
321 		if (hasPackedObject(objectId)) {
322 			return true;
323 		}
324 		skips = addMe(skips);
325 		for (AlternateHandle alt : myAlternates()) {
326 			if (!skips.contains(alt.getId())) {
327 				if (alt.db.hasPackedInSelfOrAlternate(objectId, skips)) {
328 					return true;
329 				}
330 			}
331 		}
332 		return false;
333 	}
334 
335 	private boolean hasLooseInSelfOrAlternate(AnyObjectId objectId,
336 			Set<AlternateHandle.Id> skips) {
337 		if (fileFor(objectId).exists()) {
338 			return true;
339 		}
340 		skips = addMe(skips);
341 		for (AlternateHandle alt : myAlternates()) {
342 			if (!skips.contains(alt.getId())) {
343 				if (alt.db.hasLooseInSelfOrAlternate(objectId, skips)) {
344 					return true;
345 				}
346 			}
347 		}
348 		return false;
349 	}
350 
351 	boolean hasPackedObject(AnyObjectId objectId) {
352 		PackList pList;
353 		do {
354 			pList = packList.get();
355 			for (PackFile p : pList.packs) {
356 				try {
357 					if (p.hasObject(objectId))
358 						return true;
359 				} catch (IOException e) {
360 					// The hasObject call should have only touched the index,
361 					// so any failure here indicates the index is unreadable
362 					// by this process, and the pack is likewise not readable.
363 					LOG.warn(MessageFormat.format(
364 							JGitText.get().unableToReadPackfile,
365 							p.getPackFile().getAbsolutePath()), e);
366 					removePack(p);
367 				}
368 			}
369 		} while (searchPacksAgain(pList));
370 		return false;
371 	}
372 
373 	@Override
374 	void resolve(Set<ObjectId> matches, AbbreviatedObjectId id)
375 			throws IOException {
376 		resolve(matches, id, null);
377 	}
378 
379 	private void resolve(Set<ObjectId> matches, AbbreviatedObjectId id,
380 			Set<AlternateHandle.Id> skips)
381 			throws IOException {
382 		// Go through the packs once. If we didn't find any resolutions
383 		// scan for new packs and check once more.
384 		int oldSize = matches.size();
385 		PackList pList;
386 		do {
387 			pList = packList.get();
388 			for (PackFile p : pList.packs) {
389 				try {
390 					p.resolve(matches, id, RESOLVE_ABBREV_LIMIT);
391 					p.resetTransientErrorCount();
392 				} catch (IOException e) {
393 					handlePackError(e, p);
394 				}
395 				if (matches.size() > RESOLVE_ABBREV_LIMIT)
396 					return;
397 			}
398 		} while (matches.size() == oldSize && searchPacksAgain(pList));
399 
400 		String fanOut = id.name().substring(0, 2);
401 		String[] entries = new File(getDirectory(), fanOut).list();
402 		if (entries != null) {
403 			for (String e : entries) {
404 				if (e.length() != Constants.OBJECT_ID_STRING_LENGTH - 2)
405 					continue;
406 				try {
407 					ObjectId entId = ObjectId.fromString(fanOut + e);
408 					if (id.prefixCompare(entId) == 0)
409 						matches.add(entId);
410 				} catch (IllegalArgumentException notId) {
411 					continue;
412 				}
413 				if (matches.size() > RESOLVE_ABBREV_LIMIT)
414 					return;
415 			}
416 		}
417 
418 		skips = addMe(skips);
419 		for (AlternateHandle alt : myAlternates()) {
420 			if (!skips.contains(alt.getId())) {
421 				alt.db.resolve(matches, id, skips);
422 				if (matches.size() > RESOLVE_ABBREV_LIMIT) {
423 					return;
424 				}
425 			}
426 		}
427 	}
428 
429 	@Override
430 	ObjectLoader openObject(WindowCursor curs, AnyObjectId objectId)
431 			throws IOException {
432 		if (unpackedObjectCache.isUnpacked(objectId)) {
433 			ObjectLoader ldr = openLooseObject(curs, objectId);
434 			if (ldr != null) {
435 				return ldr;
436 			}
437 		}
438 		ObjectLoader ldr = openPackedFromSelfOrAlternate(curs, objectId, null);
439 		if (ldr != null) {
440 			return ldr;
441 		}
442 		return openLooseFromSelfOrAlternate(curs, objectId, null);
443 	}
444 
445 	private ObjectLoader openPackedFromSelfOrAlternate(WindowCursor curs,
446 			AnyObjectId objectId, Set<AlternateHandle.Id> skips) {
447 		ObjectLoader ldr = openPackedObject(curs, objectId);
448 		if (ldr != null) {
449 			return ldr;
450 		}
451 		skips = addMe(skips);
452 		for (AlternateHandle alt : myAlternates()) {
453 			if (!skips.contains(alt.getId())) {
454 				ldr = alt.db.openPackedFromSelfOrAlternate(curs, objectId, skips);
455 				if (ldr != null) {
456 					return ldr;
457 				}
458 			}
459 		}
460 		return null;
461 	}
462 
463 	private ObjectLoader openLooseFromSelfOrAlternate(WindowCursor curs,
464 			AnyObjectId objectId, Set<AlternateHandle.Id> skips)
465 					throws IOException {
466 		ObjectLoader ldr = openLooseObject(curs, objectId);
467 		if (ldr != null) {
468 			return ldr;
469 		}
470 		skips = addMe(skips);
471 		for (AlternateHandle alt : myAlternates()) {
472 			if (!skips.contains(alt.getId())) {
473 				ldr = alt.db.openLooseFromSelfOrAlternate(curs, objectId, skips);
474 				if (ldr != null) {
475 					return ldr;
476 				}
477 			}
478 		}
479 		return null;
480 	}
481 
482 	ObjectLoader openPackedObject(WindowCursor curs, AnyObjectId objectId) {
483 		PackList pList;
484 		do {
485 			SEARCH: for (;;) {
486 				pList = packList.get();
487 				for (PackFile p : pList.packs) {
488 					try {
489 						ObjectLoader ldr = p.get(curs, objectId);
490 						p.resetTransientErrorCount();
491 						if (ldr != null)
492 							return ldr;
493 					} catch (PackMismatchException e) {
494 						// Pack was modified; refresh the entire pack list.
495 						if (searchPacksAgain(pList))
496 							continue SEARCH;
497 					} catch (IOException e) {
498 						handlePackError(e, p);
499 					}
500 				}
501 				break SEARCH;
502 			}
503 		} while (searchPacksAgain(pList));
504 		return null;
505 	}
506 
507 	@Override
508 	ObjectLoader openLooseObject(WindowCursor curs, AnyObjectId id)
509 			throws IOException {
510 		File path = fileFor(id);
511 		try (FileInputStream in = new FileInputStream(path)) {
512 			unpackedObjectCache.add(id);
513 			return UnpackedObject.open(in, path, id, curs);
514 		} catch (FileNotFoundException noFile) {
515 			if (path.exists()) {
516 				throw noFile;
517 			}
518 			unpackedObjectCache.remove(id);
519 			return null;
520 		}
521 	}
522 
523 	@Override
524 	long getObjectSize(WindowCursor curs, AnyObjectId id)
525 			throws IOException {
526 		if (unpackedObjectCache.isUnpacked(id)) {
527 			long len = getLooseObjectSize(curs, id);
528 			if (0 <= len) {
529 				return len;
530 			}
531 		}
532 		long len = getPackedSizeFromSelfOrAlternate(curs, id, null);
533 		if (0 <= len) {
534 			return len;
535 		}
536 		return getLooseSizeFromSelfOrAlternate(curs, id, null);
537 	}
538 
539 	private long getPackedSizeFromSelfOrAlternate(WindowCursor curs,
540 			AnyObjectId id, Set<AlternateHandle.Id> skips) {
541 		long len = getPackedObjectSize(curs, id);
542 		if (0 <= len) {
543 			return len;
544 		}
545 		skips = addMe(skips);
546 		for (AlternateHandle alt : myAlternates()) {
547 			if (!skips.contains(alt.getId())) {
548 				len = alt.db.getPackedSizeFromSelfOrAlternate(curs, id, skips);
549 				if (0 <= len) {
550 					return len;
551 				}
552 			}
553 		}
554 		return -1;
555 	}
556 
557 	private long getLooseSizeFromSelfOrAlternate(WindowCursor curs,
558 			AnyObjectId id, Set<AlternateHandle.Id> skips) throws IOException {
559 		long len = getLooseObjectSize(curs, id);
560 		if (0 <= len) {
561 			return len;
562 		}
563 		skips = addMe(skips);
564 		for (AlternateHandle alt : myAlternates()) {
565 			if (!skips.contains(alt.getId())) {
566 				len = alt.db.getLooseSizeFromSelfOrAlternate(curs, id, skips);
567 				if (0 <= len) {
568 					return len;
569 				}
570 			}
571 		}
572 		return -1;
573 	}
574 
575 	private long getPackedObjectSize(WindowCursor curs, AnyObjectId id) {
576 		PackList pList;
577 		do {
578 			SEARCH: for (;;) {
579 				pList = packList.get();
580 				for (PackFile p : pList.packs) {
581 					try {
582 						long len = p.getObjectSize(curs, id);
583 						p.resetTransientErrorCount();
584 						if (0 <= len)
585 							return len;
586 					} catch (PackMismatchException e) {
587 						// Pack was modified; refresh the entire pack list.
588 						if (searchPacksAgain(pList))
589 							continue SEARCH;
590 					} catch (IOException e) {
591 						handlePackError(e, p);
592 					}
593 				}
594 				break SEARCH;
595 			}
596 		} while (searchPacksAgain(pList));
597 		return -1;
598 	}
599 
600 	private long getLooseObjectSize(WindowCursor curs, AnyObjectId id)
601 			throws IOException {
602 		File f = fileFor(id);
603 		try (FileInputStream in = new FileInputStream(f)) {
604 			unpackedObjectCache.add(id);
605 			return UnpackedObject.getSize(in, id, curs);
606 		} catch (FileNotFoundException noFile) {
607 			if (f.exists()) {
608 				throw noFile;
609 			}
610 			unpackedObjectCache.remove(id);
611 			return -1;
612 		}
613 	}
614 
615 	@Override
616 	void selectObjectRepresentation(PackWriter packer, ObjectToPack otp,
617 																	WindowCursor curs) throws IOException {
618 		selectObjectRepresentation(packer, otp, curs, null);
619 	}
620 
621 	private void selectObjectRepresentation(PackWriter packer, ObjectToPack otp,
622 			WindowCursor curs, Set<AlternateHandle.Id> skips) throws IOException {
623 		PackList pList = packList.get();
624 		SEARCH: for (;;) {
625 			for (final PackFile p : pList.packs) {
626 				try {
627 					LocalObjectRepresentation rep = p.representation(curs, otp);
628 					p.resetTransientErrorCount();
629 					if (rep != null)
630 						packer.select(otp, rep);
631 				} catch (PackMismatchException e) {
632 					// Pack was modified; refresh the entire pack list.
633 					//
634 					pList = scanPacks(pList);
635 					continue SEARCH;
636 				} catch (IOException e) {
637 					handlePackError(e, p);
638 				}
639 			}
640 			break SEARCH;
641 		}
642 
643 		skips = addMe(skips);
644 		for (AlternateHandle h : myAlternates()) {
645 			if (!skips.contains(h.getId())) {
646 				h.db.selectObjectRepresentation(packer, otp, curs, skips);
647 			}
648 		}
649 	}
650 
651 	private void handlePackError(IOException e, PackFile p) {
652 		String warnTmpl = null;
653 		int transientErrorCount = 0;
654 		String errTmpl = JGitText.get().exceptionWhileReadingPack;
655 		if ((e instanceof CorruptObjectException)
656 				|| (e instanceof PackInvalidException)) {
657 			warnTmpl = JGitText.get().corruptPack;
658 			LOG.warn(MessageFormat.format(warnTmpl,
659 					p.getPackFile().getAbsolutePath()), e);
660 			// Assume the pack is corrupted, and remove it from the list.
661 			removePack(p);
662 		} else if (e instanceof FileNotFoundException) {
663 			if (p.getPackFile().exists()) {
664 				errTmpl = JGitText.get().packInaccessible;
665 				transientErrorCount = p.incrementTransientErrorCount();
666 			} else {
667 				warnTmpl = JGitText.get().packWasDeleted;
668 				removePack(p);
669 			}
670 		} else if (FileUtils.isStaleFileHandleInCausalChain(e)) {
671 			warnTmpl = JGitText.get().packHandleIsStale;
672 			removePack(p);
673 		} else {
674 			transientErrorCount = p.incrementTransientErrorCount();
675 		}
676 		if (warnTmpl != null) {
677 			LOG.warn(MessageFormat.format(warnTmpl,
678 					p.getPackFile().getAbsolutePath()), e);
679 		} else {
680 			if (doLogExponentialBackoff(transientErrorCount)) {
681 				// Don't remove the pack from the list, as the error may be
682 				// transient.
683 				LOG.error(MessageFormat.format(errTmpl,
684 						p.getPackFile().getAbsolutePath(),
685 						Integer.valueOf(transientErrorCount)), e);
686 			}
687 		}
688 	}
689 
690 	/**
691 	 * @param n
692 	 *            count of consecutive failures
693 	 * @return @{code true} if i is a power of 2
694 	 */
695 	private boolean doLogExponentialBackoff(int n) {
696 		return (n & (n - 1)) == 0;
697 	}
698 
699 	@Override
700 	InsertLooseObjectResult insertUnpackedObject(File tmp, ObjectId id,
701 			boolean createDuplicate) throws IOException {
702 		// If the object is already in the repository, remove temporary file.
703 		//
704 		if (unpackedObjectCache.isUnpacked(id)) {
705 			FileUtils.delete(tmp, FileUtils.RETRY);
706 			return InsertLooseObjectResult.EXISTS_LOOSE;
707 		}
708 		if (!createDuplicate && has(id)) {
709 			FileUtils.delete(tmp, FileUtils.RETRY);
710 			return InsertLooseObjectResult.EXISTS_PACKED;
711 		}
712 
713 		final File dst = fileFor(id);
714 		if (dst.exists()) {
715 			// We want to be extra careful and avoid replacing an object
716 			// that already exists. We can't be sure renameTo() would
717 			// fail on all platforms if dst exists, so we check first.
718 			//
719 			FileUtils.delete(tmp, FileUtils.RETRY);
720 			return InsertLooseObjectResult.EXISTS_LOOSE;
721 		}
722 		try {
723 			Files.move(FileUtils.toPath(tmp), FileUtils.toPath(dst),
724 					StandardCopyOption.ATOMIC_MOVE);
725 			dst.setReadOnly();
726 			unpackedObjectCache.add(id);
727 			return InsertLooseObjectResult.INSERTED;
728 		} catch (AtomicMoveNotSupportedException e) {
729 			LOG.error(e.getMessage(), e);
730 		} catch (IOException e) {
731 			// ignore
732 		}
733 
734 		// Maybe the directory doesn't exist yet as the object
735 		// directories are always lazily created. Note that we
736 		// try the rename first as the directory likely does exist.
737 		//
738 		FileUtils.mkdir(dst.getParentFile(), true);
739 		try {
740 			Files.move(FileUtils.toPath(tmp), FileUtils.toPath(dst),
741 					StandardCopyOption.ATOMIC_MOVE);
742 			dst.setReadOnly();
743 			unpackedObjectCache.add(id);
744 			return InsertLooseObjectResult.INSERTED;
745 		} catch (AtomicMoveNotSupportedException e) {
746 			LOG.error(e.getMessage(), e);
747 		} catch (IOException e) {
748 			LOG.debug(e.getMessage(), e);
749 		}
750 
751 		if (!createDuplicate && has(id)) {
752 			FileUtils.delete(tmp, FileUtils.RETRY);
753 			return InsertLooseObjectResult.EXISTS_PACKED;
754 		}
755 
756 		// The object failed to be renamed into its proper
757 		// location and it doesn't exist in the repository
758 		// either. We really don't know what went wrong, so
759 		// fail.
760 		//
761 		FileUtils.delete(tmp, FileUtils.RETRY);
762 		return InsertLooseObjectResult.FAILURE;
763 	}
764 
765 	boolean searchPacksAgain(PackList old) {
766 		// Whether to trust the pack folder's modification time. If set
767 		// to false we will always scan the .git/objects/pack folder to
768 		// check for new pack files. If set to true (default) we use the
769 		// lastmodified attribute of the folder and assume that no new
770 		// pack files can be in this folder if his modification time has
771 		// not changed.
772 		boolean trustFolderStat = config.getBoolean(
773 				ConfigConstants.CONFIG_CORE_SECTION,
774 				ConfigConstants.CONFIG_KEY_TRUSTFOLDERSTAT, true);
775 
776 		return ((!trustFolderStat) || old.snapshot.isModified(packDirectory))
777 				&& old != scanPacks(old);
778 	}
779 
780 	@Override
781 	Config getConfig() {
782 		return config;
783 	}
784 
785 	@Override
786 	FS getFS() {
787 		return fs;
788 	}
789 
790 	@Override
791 	Set<ObjectId> getShallowCommits() throws IOException {
792 		if (shallowFile == null || !shallowFile.isFile())
793 			return Collections.emptySet();
794 
795 		if (shallowFileSnapshot == null
796 				|| shallowFileSnapshot.isModified(shallowFile)) {
797 			shallowCommitsIds = new HashSet<>();
798 
799 			try (BufferedReader reader = open(shallowFile)) {
800 				String line;
801 				while ((line = reader.readLine()) != null) {
802 					try {
803 						shallowCommitsIds.add(ObjectId.fromString(line));
804 					} catch (IllegalArgumentException ex) {
805 						throw new IOException(MessageFormat
806 								.format(JGitText.get().badShallowLine, line));
807 					}
808 				}
809 			}
810 
811 			shallowFileSnapshot = FileSnapshot.save(shallowFile);
812 		}
813 
814 		return shallowCommitsIds;
815 	}
816 
817 	private void insertPack(final PackFile pf) {
818 		PackList o, n;
819 		do {
820 			o = packList.get();
821 
822 			// If the pack in question is already present in the list
823 			// (picked up by a concurrent thread that did a scan?) we
824 			// do not want to insert it a second time.
825 			//
826 			final PackFile[] oldList = o.packs;
827 			final String name = pf.getPackFile().getName();
828 			for (PackFile p : oldList) {
829 				if (name.equals(p.getPackFile().getName()))
830 					return;
831 			}
832 
833 			final PackFile[] newList = new PackFile[1 + oldList.length];
834 			newList[0] = pf;
835 			System.arraycopy(oldList, 0, newList, 1, oldList.length);
836 			n = new PackList(o.snapshot, newList);
837 		} while (!packList.compareAndSet(o, n));
838 	}
839 
840 	private void removePack(final PackFile deadPack) {
841 		PackList o, n;
842 		do {
843 			o = packList.get();
844 
845 			final PackFile[] oldList = o.packs;
846 			final int j = indexOf(oldList, deadPack);
847 			if (j < 0)
848 				break;
849 
850 			final PackFile[] newList = new PackFile[oldList.length - 1];
851 			System.arraycopy(oldList, 0, newList, 0, j);
852 			System.arraycopy(oldList, j + 1, newList, j, newList.length - j);
853 			n = new PackList(o.snapshot, newList);
854 		} while (!packList.compareAndSet(o, n));
855 		deadPack.close();
856 	}
857 
858 	private static int indexOf(final PackFile[] list, final PackFile pack) {
859 		for (int i = 0; i < list.length; i++) {
860 			if (list[i] == pack)
861 				return i;
862 		}
863 		return -1;
864 	}
865 
866 	private PackList scanPacks(final PackList original) {
867 		synchronized (packList) {
868 			PackList o, n;
869 			do {
870 				o = packList.get();
871 				if (o != original) {
872 					// Another thread did the scan for us, while we
873 					// were blocked on the monitor above.
874 					//
875 					return o;
876 				}
877 				n = scanPacksImpl(o);
878 				if (n == o)
879 					return n;
880 			} while (!packList.compareAndSet(o, n));
881 			return n;
882 		}
883 	}
884 
885 	private PackList scanPacksImpl(final PackList old) {
886 		final Map<String, PackFile> forReuse = reuseMap(old);
887 		final FileSnapshot snapshot = FileSnapshot.save(packDirectory);
888 		final Set<String> names = listPackDirectory();
889 		final List<PackFile> list = new ArrayList<>(names.size() >> 2);
890 		boolean foundNew = false;
891 		for (final String indexName : names) {
892 			// Must match "pack-[0-9a-f]{40}.idx" to be an index.
893 			//
894 			if (indexName.length() != 49 || !indexName.endsWith(".idx")) //$NON-NLS-1$
895 				continue;
896 
897 			final String base = indexName.substring(0, indexName.length() - 3);
898 			int extensions = 0;
899 			for (PackExt ext : PackExt.values()) {
900 				if (names.contains(base + ext.getExtension()))
901 					extensions |= ext.getBit();
902 			}
903 
904 			if ((extensions & PACK.getBit()) == 0) {
905 				// Sometimes C Git's HTTP fetch transport leaves a
906 				// .idx file behind and does not download the .pack.
907 				// We have to skip over such useless indexes.
908 				//
909 				continue;
910 			}
911 
912 			final String packName = base + PACK.getExtension();
913 			final File packFile = new File(packDirectory, packName);
914 			final PackFile oldPack = forReuse.remove(packName);
915 			if (oldPack != null
916 					&& !oldPack.getFileSnapshot().isModified(packFile)) {
917 				list.add(oldPack);
918 				continue;
919 			}
920 
921 			list.add(new PackFile(packFile, extensions));
922 			foundNew = true;
923 		}
924 
925 		// If we did not discover any new files, the modification time was not
926 		// changed, and we did not remove any files, then the set of files is
927 		// the same as the set we were given. Instead of building a new object
928 		// return the same collection.
929 		//
930 		if (!foundNew && forReuse.isEmpty() && snapshot.equals(old.snapshot)) {
931 			old.snapshot.setClean(snapshot);
932 			return old;
933 		}
934 
935 		for (final PackFile p : forReuse.values()) {
936 			p.close();
937 		}
938 
939 		if (list.isEmpty())
940 			return new PackList(snapshot, NO_PACKS.packs);
941 
942 		final PackFile[] r = list.toArray(new PackFile[list.size()]);
943 		Arrays.sort(r, PackFile.SORT);
944 		return new PackList(snapshot, r);
945 	}
946 
947 	private static Map<String, PackFile> reuseMap(final PackList old) {
948 		final Map<String, PackFile> forReuse = new HashMap<>();
949 		for (final PackFile p : old.packs) {
950 			if (p.invalid()) {
951 				// The pack instance is corrupted, and cannot be safely used
952 				// again. Do not include it in our reuse map.
953 				//
954 				p.close();
955 				continue;
956 			}
957 
958 			final PackFile prior = forReuse.put(p.getPackFile().getName(), p);
959 			if (prior != null) {
960 				// This should never occur. It should be impossible for us
961 				// to have two pack files with the same name, as all of them
962 				// came out of the same directory. If it does, we promised to
963 				// close any PackFiles we did not reuse, so close the second,
964 				// readers are likely to be actively using the first.
965 				//
966 				forReuse.put(prior.getPackFile().getName(), prior);
967 				p.close();
968 			}
969 		}
970 		return forReuse;
971 	}
972 
973 	private Set<String> listPackDirectory() {
974 		final String[] nameList = packDirectory.list();
975 		if (nameList == null)
976 			return Collections.emptySet();
977 		final Set<String> nameSet = new HashSet<>(nameList.length << 1);
978 		for (final String name : nameList) {
979 			if (name.startsWith("pack-")) //$NON-NLS-1$
980 				nameSet.add(name);
981 		}
982 		return nameSet;
983 	}
984 
985 	void closeAllPackHandles(File packFile) {
986 		// if the packfile already exists (because we are rewriting a
987 		// packfile for the same set of objects maybe with different
988 		// PackConfig) then make sure we get rid of all handles on the file.
989 		// Windows will not allow for rename otherwise.
990 		if (packFile.exists()) {
991 			for (PackFile p : getPacks()) {
992 				if (packFile.getPath().equals(p.getPackFile().getPath())) {
993 					p.close();
994 					break;
995 				}
996 			}
997 		}
998 	}
999 
1000 	AlternateHandle[] myAlternates() {
1001 		AlternateHandle[] alt = alternates.get();
1002 		if (alt == null) {
1003 			synchronized (alternates) {
1004 				alt = alternates.get();
1005 				if (alt == null) {
1006 					try {
1007 						alt = loadAlternates();
1008 					} catch (IOException e) {
1009 						alt = new AlternateHandle[0];
1010 					}
1011 					alternates.set(alt);
1012 				}
1013 			}
1014 		}
1015 		return alt;
1016 	}
1017 
1018 	Set<AlternateHandle.Id> addMe(Set<AlternateHandle.Id> skips) {
1019 		if (skips == null) {
1020 			skips = new HashSet<>();
1021 		}
1022 		skips.add(handle.getId());
1023 		return skips;
1024 	}
1025 
1026 	private AlternateHandle[] loadAlternates() throws IOException {
1027 		final List<AlternateHandle> l = new ArrayList<>(4);
1028 		try (BufferedReader br = open(alternatesFile)) {
1029 			String line;
1030 			while ((line = br.readLine()) != null) {
1031 				l.add(openAlternate(line));
1032 			}
1033 		}
1034 		return l.toArray(new AlternateHandle[l.size()]);
1035 	}
1036 
1037 	private static BufferedReader open(final File f)
1038 			throws FileNotFoundException {
1039 		return new BufferedReader(new FileReader(f));
1040 	}
1041 
1042 	private AlternateHandle openAlternate(final String location)
1043 			throws IOException {
1044 		final File objdir = fs.resolve(objects, location);
1045 		return openAlternate(objdir);
1046 	}
1047 
1048 	private AlternateHandle openAlternate(File objdir) throws IOException {
1049 		final File parent = objdir.getParentFile();
1050 		if (FileKey.isGitRepository(parent, fs)) {
1051 			FileKey key = FileKey.exact(parent, fs);
1052 			FileRepository db = (FileRepository) RepositoryCache.open(key);
1053 			return new AlternateRepository(db);
1054 		}
1055 
1056 		ObjectDirectory db = new ObjectDirectory(config, objdir, null, fs, null);
1057 		return new AlternateHandle(db);
1058 	}
1059 
1060 	/**
1061 	 * {@inheritDoc}
1062 	 * <p>
1063 	 * Compute the location of a loose object file.
1064 	 */
1065 	@Override
1066 	public File fileFor(AnyObjectId objectId) {
1067 		String n = objectId.name();
1068 		String d = n.substring(0, 2);
1069 		String f = n.substring(2);
1070 		return new File(new File(getDirectory(), d), f);
1071 	}
1072 
1073 	static final class PackList {
1074 		/** State just before reading the pack directory. */
1075 		final FileSnapshot snapshot;
1076 
1077 		/** All known packs, sorted by {@link PackFile#SORT}. */
1078 		final PackFile[] packs;
1079 
1080 		PackList(final FileSnapshot monitor, final PackFile[] packs) {
1081 			this.snapshot = monitor;
1082 			this.packs = packs;
1083 		}
1084 	}
1085 
1086 	static class AlternateHandle {
1087 		static class Id {
1088 			String alternateId;
1089 
1090 			public Id(File object) {
1091 				try {
1092 					this.alternateId = object.getCanonicalPath();
1093 				} catch (Exception e) {
1094 					alternateId = null;
1095 				}
1096 			}
1097 
1098 			@Override
1099 			public boolean equals(Object o) {
1100 				if (o == this) {
1101 					return true;
1102 				}
1103 				if (o == null || !(o instanceof Id)) {
1104 					return false;
1105 				}
1106 				Id aId = (Id) o;
1107 				return Objects.equals(alternateId, aId.alternateId);
1108 			}
1109 
1110 			@Override
1111 			public int hashCode() {
1112 				if (alternateId == null) {
1113 					return 1;
1114 				}
1115 				return alternateId.hashCode();
1116 			}
1117 		}
1118 
1119 		final ObjectDirectory db;
1120 
1121 		AlternateHandle(ObjectDirectory db) {
1122 			this.db = db;
1123 		}
1124 
1125 		void close() {
1126 			db.close();
1127 		}
1128 
1129 		public Id getId(){
1130 			return db.getAlternateId();
1131 		}
1132 	}
1133 
1134 	static class AlternateRepository extends AlternateHandle {
1135 		final FileRepository repository;
1136 
1137 		AlternateRepository(FileRepository r) {
1138 			super(r.getObjectDatabase());
1139 			repository = r;
1140 		}
1141 
1142 		@Override
1143 		void close() {
1144 			repository.close();
1145 		}
1146 	}
1147 
1148 	/** {@inheritDoc} */
1149 	@Override
1150 	public ObjectDatabase newCachedDatabase() {
1151 		return newCachedFileObjectDatabase();
1152 	}
1153 
1154 	CachedObjectDirectory newCachedFileObjectDatabase() {
1155 		return new CachedObjectDirectory(this);
1156 	}
1157 
1158 	AlternateHandle.Id getAlternateId() {
1159 		return new AlternateHandle.Id(objects);
1160 	}
1161 }