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 AtomicReference<PackList> packList;
136 
137 	private final FS fs;
138 
139 	private final AtomicReference<AlternateHandle[]> alternates;
140 
141 	private final UnpackedObjectCache unpackedObjectCache;
142 
143 	private final File shallowFile;
144 
145 	private FileSnapshot shallowFileSnapshot = FileSnapshot.DIRTY;
146 
147 	private Set<ObjectId> shallowCommitsIds;
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(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(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 					removePack(p);
364 				}
365 			}
366 		} while (searchPacksAgain(pList));
367 		return false;
368 	}
369 
370 	@Override
371 	void resolve(Set<ObjectId> matches, AbbreviatedObjectId id)
372 			throws IOException {
373 		resolve(matches, id, null);
374 	}
375 
376 	private void resolve(Set<ObjectId> matches, AbbreviatedObjectId id,
377 			Set<AlternateHandle.Id> skips)
378 			throws IOException {
379 		// Go through the packs once. If we didn't find any resolutions
380 		// scan for new packs and check once more.
381 		int oldSize = matches.size();
382 		PackList pList;
383 		do {
384 			pList = packList.get();
385 			for (PackFile p : pList.packs) {
386 				try {
387 					p.resolve(matches, id, RESOLVE_ABBREV_LIMIT);
388 					p.resetTransientErrorCount();
389 				} catch (IOException e) {
390 					handlePackError(e, p);
391 				}
392 				if (matches.size() > RESOLVE_ABBREV_LIMIT)
393 					return;
394 			}
395 		} while (matches.size() == oldSize && searchPacksAgain(pList));
396 
397 		String fanOut = id.name().substring(0, 2);
398 		String[] entries = new File(getDirectory(), fanOut).list();
399 		if (entries != null) {
400 			for (String e : entries) {
401 				if (e.length() != Constants.OBJECT_ID_STRING_LENGTH - 2)
402 					continue;
403 				try {
404 					ObjectId entId = ObjectId.fromString(fanOut + e);
405 					if (id.prefixCompare(entId) == 0)
406 						matches.add(entId);
407 				} catch (IllegalArgumentException notId) {
408 					continue;
409 				}
410 				if (matches.size() > RESOLVE_ABBREV_LIMIT)
411 					return;
412 			}
413 		}
414 
415 		skips = addMe(skips);
416 		for (AlternateHandle alt : myAlternates()) {
417 			if (!skips.contains(alt.getId())) {
418 				alt.db.resolve(matches, id, skips);
419 				if (matches.size() > RESOLVE_ABBREV_LIMIT) {
420 					return;
421 				}
422 			}
423 		}
424 	}
425 
426 	@Override
427 	ObjectLoader openObject(WindowCursor curs, AnyObjectId objectId)
428 			throws IOException {
429 		if (unpackedObjectCache.isUnpacked(objectId)) {
430 			ObjectLoader ldr = openLooseObject(curs, objectId);
431 			if (ldr != null) {
432 				return ldr;
433 			}
434 		}
435 		ObjectLoader ldr = openPackedFromSelfOrAlternate(curs, objectId, null);
436 		if (ldr != null) {
437 			return ldr;
438 		}
439 		return openLooseFromSelfOrAlternate(curs, objectId, null);
440 	}
441 
442 	private ObjectLoader openPackedFromSelfOrAlternate(WindowCursor curs,
443 			AnyObjectId objectId, Set<AlternateHandle.Id> skips) {
444 		ObjectLoader ldr = openPackedObject(curs, objectId);
445 		if (ldr != null) {
446 			return ldr;
447 		}
448 		skips = addMe(skips);
449 		for (AlternateHandle alt : myAlternates()) {
450 			if (!skips.contains(alt.getId())) {
451 				ldr = alt.db.openPackedFromSelfOrAlternate(curs, objectId, skips);
452 				if (ldr != null) {
453 					return ldr;
454 				}
455 			}
456 		}
457 		return null;
458 	}
459 
460 	private ObjectLoader openLooseFromSelfOrAlternate(WindowCursor curs,
461 			AnyObjectId objectId, Set<AlternateHandle.Id> skips)
462 					throws IOException {
463 		ObjectLoader ldr = openLooseObject(curs, objectId);
464 		if (ldr != null) {
465 			return ldr;
466 		}
467 		skips = addMe(skips);
468 		for (AlternateHandle alt : myAlternates()) {
469 			if (!skips.contains(alt.getId())) {
470 				ldr = alt.db.openLooseFromSelfOrAlternate(curs, objectId, skips);
471 				if (ldr != null) {
472 					return ldr;
473 				}
474 			}
475 		}
476 		return null;
477 	}
478 
479 	ObjectLoader openPackedObject(WindowCursor curs, AnyObjectId objectId) {
480 		PackList pList;
481 		do {
482 			SEARCH: for (;;) {
483 				pList = packList.get();
484 				for (PackFile p : pList.packs) {
485 					try {
486 						ObjectLoader ldr = p.get(curs, objectId);
487 						p.resetTransientErrorCount();
488 						if (ldr != null)
489 							return ldr;
490 					} catch (PackMismatchException e) {
491 						// Pack was modified; refresh the entire pack list.
492 						if (searchPacksAgain(pList))
493 							continue SEARCH;
494 					} catch (IOException e) {
495 						handlePackError(e, p);
496 					}
497 				}
498 				break SEARCH;
499 			}
500 		} while (searchPacksAgain(pList));
501 		return null;
502 	}
503 
504 	@Override
505 	ObjectLoader openLooseObject(WindowCursor curs, AnyObjectId id)
506 			throws IOException {
507 		File path = fileFor(id);
508 		try (FileInputStream in = new FileInputStream(path)) {
509 			unpackedObjectCache.add(id);
510 			return UnpackedObject.open(in, path, id, curs);
511 		} catch (FileNotFoundException noFile) {
512 			if (path.exists()) {
513 				throw noFile;
514 			}
515 			unpackedObjectCache.remove(id);
516 			return null;
517 		}
518 	}
519 
520 	@Override
521 	long getObjectSize(WindowCursor curs, AnyObjectId id)
522 			throws IOException {
523 		if (unpackedObjectCache.isUnpacked(id)) {
524 			long len = getLooseObjectSize(curs, id);
525 			if (0 <= len) {
526 				return len;
527 			}
528 		}
529 		long len = getPackedSizeFromSelfOrAlternate(curs, id, null);
530 		if (0 <= len) {
531 			return len;
532 		}
533 		return getLooseSizeFromSelfOrAlternate(curs, id, null);
534 	}
535 
536 	private long getPackedSizeFromSelfOrAlternate(WindowCursor curs,
537 			AnyObjectId id, Set<AlternateHandle.Id> skips) {
538 		long len = getPackedObjectSize(curs, id);
539 		if (0 <= len) {
540 			return len;
541 		}
542 		skips = addMe(skips);
543 		for (AlternateHandle alt : myAlternates()) {
544 			if (!skips.contains(alt.getId())) {
545 				len = alt.db.getPackedSizeFromSelfOrAlternate(curs, id, skips);
546 				if (0 <= len) {
547 					return len;
548 				}
549 			}
550 		}
551 		return -1;
552 	}
553 
554 	private long getLooseSizeFromSelfOrAlternate(WindowCursor curs,
555 			AnyObjectId id, Set<AlternateHandle.Id> skips) throws IOException {
556 		long len = getLooseObjectSize(curs, id);
557 		if (0 <= len) {
558 			return len;
559 		}
560 		skips = addMe(skips);
561 		for (AlternateHandle alt : myAlternates()) {
562 			if (!skips.contains(alt.getId())) {
563 				len = alt.db.getLooseSizeFromSelfOrAlternate(curs, id, skips);
564 				if (0 <= len) {
565 					return len;
566 				}
567 			}
568 		}
569 		return -1;
570 	}
571 
572 	private long getPackedObjectSize(WindowCursor curs, AnyObjectId id) {
573 		PackList pList;
574 		do {
575 			SEARCH: for (;;) {
576 				pList = packList.get();
577 				for (PackFile p : pList.packs) {
578 					try {
579 						long len = p.getObjectSize(curs, id);
580 						p.resetTransientErrorCount();
581 						if (0 <= len)
582 							return len;
583 					} catch (PackMismatchException e) {
584 						// Pack was modified; refresh the entire pack list.
585 						if (searchPacksAgain(pList))
586 							continue SEARCH;
587 					} catch (IOException e) {
588 						handlePackError(e, p);
589 					}
590 				}
591 				break SEARCH;
592 			}
593 		} while (searchPacksAgain(pList));
594 		return -1;
595 	}
596 
597 	private long getLooseObjectSize(WindowCursor curs, AnyObjectId id)
598 			throws IOException {
599 		File f = fileFor(id);
600 		try (FileInputStream in = new FileInputStream(f)) {
601 			unpackedObjectCache.add(id);
602 			return UnpackedObject.getSize(in, id, curs);
603 		} catch (FileNotFoundException noFile) {
604 			if (f.exists()) {
605 				throw noFile;
606 			}
607 			unpackedObjectCache.remove(id);
608 			return -1;
609 		}
610 	}
611 
612 	@Override
613 	void selectObjectRepresentation(PackWriter packer, ObjectToPack otp,
614 																	WindowCursor curs) throws IOException {
615 		selectObjectRepresentation(packer, otp, curs, null);
616 	}
617 
618 	private void selectObjectRepresentation(PackWriter packer, ObjectToPack otp,
619 			WindowCursor curs, Set<AlternateHandle.Id> skips) throws IOException {
620 		PackList pList = packList.get();
621 		SEARCH: for (;;) {
622 			for (PackFile p : pList.packs) {
623 				try {
624 					LocalObjectRepresentation rep = p.representation(curs, otp);
625 					p.resetTransientErrorCount();
626 					if (rep != null)
627 						packer.select(otp, rep);
628 				} catch (PackMismatchException e) {
629 					// Pack was modified; refresh the entire pack list.
630 					//
631 					pList = scanPacks(pList);
632 					continue SEARCH;
633 				} catch (IOException e) {
634 					handlePackError(e, p);
635 				}
636 			}
637 			break SEARCH;
638 		}
639 
640 		skips = addMe(skips);
641 		for (AlternateHandle h : myAlternates()) {
642 			if (!skips.contains(h.getId())) {
643 				h.db.selectObjectRepresentation(packer, otp, curs, skips);
644 			}
645 		}
646 	}
647 
648 	private void handlePackError(IOException e, PackFile p) {
649 		String warnTmpl = null;
650 		int transientErrorCount = 0;
651 		String errTmpl = JGitText.get().exceptionWhileReadingPack;
652 		if ((e instanceof CorruptObjectException)
653 				|| (e instanceof PackInvalidException)) {
654 			warnTmpl = JGitText.get().corruptPack;
655 			// Assume the pack is corrupted, and remove it from the list.
656 			removePack(p);
657 		} else if (e instanceof FileNotFoundException) {
658 			if (p.getPackFile().exists()) {
659 				errTmpl = JGitText.get().packInaccessible;
660 				transientErrorCount = p.incrementTransientErrorCount();
661 			} else {
662 				warnTmpl = JGitText.get().packWasDeleted;
663 				removePack(p);
664 			}
665 		} else if (FileUtils.isStaleFileHandleInCausalChain(e)) {
666 			warnTmpl = JGitText.get().packHandleIsStale;
667 			removePack(p);
668 		} else {
669 			transientErrorCount = p.incrementTransientErrorCount();
670 		}
671 		if (warnTmpl != null) {
672 			if (LOG.isDebugEnabled()) {
673 				LOG.debug(MessageFormat.format(warnTmpl,
674 						p.getPackFile().getAbsolutePath()), e);
675 			} else {
676 				LOG.warn(MessageFormat.format(warnTmpl,
677 						p.getPackFile().getAbsolutePath()));
678 			}
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 	private 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(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(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(PackFile[] list, 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(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(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 (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 PackFile oldPack = forReuse.remove(packName);
914 			if (oldPack != null) {
915 				list.add(oldPack);
916 				continue;
917 			}
918 
919 			final File packFile = new File(packDirectory, packName);
920 			list.add(new PackFile(packFile, extensions));
921 			foundNew = true;
922 		}
923 
924 		// If we did not discover any new files, the modification time was not
925 		// changed, and we did not remove any files, then the set of files is
926 		// the same as the set we were given. Instead of building a new object
927 		// return the same collection.
928 		//
929 		if (!foundNew && forReuse.isEmpty() && snapshot.equals(old.snapshot)) {
930 			old.snapshot.setClean(snapshot);
931 			return old;
932 		}
933 
934 		for (PackFile p : forReuse.values()) {
935 			p.close();
936 		}
937 
938 		if (list.isEmpty())
939 			return new PackList(snapshot, NO_PACKS.packs);
940 
941 		final PackFile[] r = list.toArray(new PackFile[list.size()]);
942 		Arrays.sort(r, PackFile.SORT);
943 		return new PackList(snapshot, r);
944 	}
945 
946 	private static Map<String, PackFile> reuseMap(PackList old) {
947 		final Map<String, PackFile> forReuse = new HashMap<>();
948 		for (PackFile p : old.packs) {
949 			if (p.invalid()) {
950 				// The pack instance is corrupted, and cannot be safely used
951 				// again. Do not include it in our reuse map.
952 				//
953 				p.close();
954 				continue;
955 			}
956 
957 			final PackFile prior = forReuse.put(p.getPackFile().getName(), p);
958 			if (prior != null) {
959 				// This should never occur. It should be impossible for us
960 				// to have two pack files with the same name, as all of them
961 				// came out of the same directory. If it does, we promised to
962 				// close any PackFiles we did not reuse, so close the second,
963 				// readers are likely to be actively using the first.
964 				//
965 				forReuse.put(prior.getPackFile().getName(), prior);
966 				p.close();
967 			}
968 		}
969 		return forReuse;
970 	}
971 
972 	private Set<String> listPackDirectory() {
973 		final String[] nameList = packDirectory.list();
974 		if (nameList == null)
975 			return Collections.emptySet();
976 		final Set<String> nameSet = new HashSet<>(nameList.length << 1);
977 		for (String name : nameList) {
978 			if (name.startsWith("pack-")) //$NON-NLS-1$
979 				nameSet.add(name);
980 		}
981 		return nameSet;
982 	}
983 
984 	void closeAllPackHandles(File packFile) {
985 		// if the packfile already exists (because we are rewriting a
986 		// packfile for the same set of objects maybe with different
987 		// PackConfig) then make sure we get rid of all handles on the file.
988 		// Windows will not allow for rename otherwise.
989 		if (packFile.exists()) {
990 			for (PackFile p : getPacks()) {
991 				if (packFile.getPath().equals(p.getPackFile().getPath())) {
992 					p.close();
993 					break;
994 				}
995 			}
996 		}
997 	}
998 
999 	AlternateHandle[] myAlternates() {
1000 		AlternateHandle[] alt = alternates.get();
1001 		if (alt == null) {
1002 			synchronized (alternates) {
1003 				alt = alternates.get();
1004 				if (alt == null) {
1005 					try {
1006 						alt = loadAlternates();
1007 					} catch (IOException e) {
1008 						alt = new AlternateHandle[0];
1009 					}
1010 					alternates.set(alt);
1011 				}
1012 			}
1013 		}
1014 		return alt;
1015 	}
1016 
1017 	Set<AlternateHandle.Id> addMe(Set<AlternateHandle.Id> skips) {
1018 		if (skips == null) {
1019 			skips = new HashSet<>();
1020 		}
1021 		skips.add(handle.getId());
1022 		return skips;
1023 	}
1024 
1025 	private AlternateHandle[] loadAlternates() throws IOException {
1026 		final List<AlternateHandle> l = new ArrayList<>(4);
1027 		try (BufferedReader br = open(alternatesFile)) {
1028 			String line;
1029 			while ((line = br.readLine()) != null) {
1030 				l.add(openAlternate(line));
1031 			}
1032 		}
1033 		return l.toArray(new AlternateHandle[l.size()]);
1034 	}
1035 
1036 	private static BufferedReader open(File f)
1037 			throws FileNotFoundException {
1038 		return new BufferedReader(new FileReader(f));
1039 	}
1040 
1041 	private AlternateHandle openAlternate(String location)
1042 			throws IOException {
1043 		final File objdir = fs.resolve(objects, location);
1044 		return openAlternate(objdir);
1045 	}
1046 
1047 	private AlternateHandle openAlternate(File objdir) throws IOException {
1048 		final File parent = objdir.getParentFile();
1049 		if (FileKey.isGitRepository(parent, fs)) {
1050 			FileKey key = FileKey.exact(parent, fs);
1051 			FileRepository db = (FileRepository) RepositoryCache.open(key);
1052 			return new AlternateRepository(db);
1053 		}
1054 
1055 		ObjectDirectory db = new ObjectDirectory(config, objdir, null, fs, null);
1056 		return new AlternateHandle(db);
1057 	}
1058 
1059 	/**
1060 	 * {@inheritDoc}
1061 	 * <p>
1062 	 * Compute the location of a loose object file.
1063 	 */
1064 	@Override
1065 	public File fileFor(AnyObjectId objectId) {
1066 		String n = objectId.name();
1067 		String d = n.substring(0, 2);
1068 		String f = n.substring(2);
1069 		return new File(new File(getDirectory(), d), f);
1070 	}
1071 
1072 	private static final class PackList {
1073 		/** State just before reading the pack directory. */
1074 		final FileSnapshot snapshot;
1075 
1076 		/** All known packs, sorted by {@link PackFile#SORT}. */
1077 		final PackFile[] packs;
1078 
1079 		PackList(FileSnapshot monitor, PackFile[] packs) {
1080 			this.snapshot = monitor;
1081 			this.packs = packs;
1082 		}
1083 	}
1084 
1085 	static class AlternateHandle {
1086 		static class Id {
1087 			String alternateId;
1088 
1089 			public Id(File object) {
1090 				try {
1091 					this.alternateId = object.getCanonicalPath();
1092 				} catch (Exception e) {
1093 					alternateId = null;
1094 				}
1095 			}
1096 
1097 			@Override
1098 			public boolean equals(Object o) {
1099 				if (o == this) {
1100 					return true;
1101 				}
1102 				if (o == null || !(o instanceof Id)) {
1103 					return false;
1104 				}
1105 				Id aId = (Id) o;
1106 				return Objects.equals(alternateId, aId.alternateId);
1107 			}
1108 
1109 			@Override
1110 			public int hashCode() {
1111 				if (alternateId == null) {
1112 					return 1;
1113 				}
1114 				return alternateId.hashCode();
1115 			}
1116 		}
1117 
1118 		final ObjectDirectory db;
1119 
1120 		AlternateHandle(ObjectDirectory db) {
1121 			this.db = db;
1122 		}
1123 
1124 		void close() {
1125 			db.close();
1126 		}
1127 
1128 		public Id getId(){
1129 			return db.getAlternateId();
1130 		}
1131 	}
1132 
1133 	static class AlternateRepository extends AlternateHandle {
1134 		final FileRepository repository;
1135 
1136 		AlternateRepository(FileRepository r) {
1137 			super(r.getObjectDatabase());
1138 			repository = r;
1139 		}
1140 
1141 		@Override
1142 		void close() {
1143 			repository.close();
1144 		}
1145 	}
1146 
1147 	/** {@inheritDoc} */
1148 	@Override
1149 	public ObjectDatabase newCachedDatabase() {
1150 		return newCachedFileObjectDatabase();
1151 	}
1152 
1153 	CachedObjectDirectory newCachedFileObjectDatabase() {
1154 		return new CachedObjectDirectory(this);
1155 	}
1156 
1157 	AlternateHandle.Id getAlternateId() {
1158 		return new AlternateHandle.Id(objects);
1159 	}
1160 }