Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

ObjectDirectory.java 28KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976
  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. package org.eclipse.jgit.internal.storage.file;
  44. import static org.eclipse.jgit.internal.storage.pack.PackExt.INDEX;
  45. import static org.eclipse.jgit.internal.storage.pack.PackExt.PACK;
  46. import java.io.BufferedReader;
  47. import java.io.File;
  48. import java.io.FileInputStream;
  49. import java.io.FileNotFoundException;
  50. import java.io.FileReader;
  51. import java.io.IOException;
  52. import java.text.MessageFormat;
  53. import java.util.ArrayList;
  54. import java.util.Arrays;
  55. import java.util.Collection;
  56. import java.util.Collections;
  57. import java.util.HashMap;
  58. import java.util.HashSet;
  59. import java.util.List;
  60. import java.util.Map;
  61. import java.util.Set;
  62. import java.util.concurrent.atomic.AtomicReference;
  63. import org.eclipse.jgit.errors.CorruptObjectException;
  64. import org.eclipse.jgit.errors.PackInvalidException;
  65. import org.eclipse.jgit.errors.PackMismatchException;
  66. import org.eclipse.jgit.internal.JGitText;
  67. import org.eclipse.jgit.internal.storage.pack.ObjectToPack;
  68. import org.eclipse.jgit.internal.storage.pack.PackExt;
  69. import org.eclipse.jgit.internal.storage.pack.PackWriter;
  70. import org.eclipse.jgit.lib.AbbreviatedObjectId;
  71. import org.eclipse.jgit.lib.AnyObjectId;
  72. import org.eclipse.jgit.lib.Config;
  73. import org.eclipse.jgit.lib.ConfigConstants;
  74. import org.eclipse.jgit.lib.Constants;
  75. import org.eclipse.jgit.lib.ObjectDatabase;
  76. import org.eclipse.jgit.lib.ObjectId;
  77. import org.eclipse.jgit.lib.ObjectLoader;
  78. import org.eclipse.jgit.lib.RepositoryCache;
  79. import org.eclipse.jgit.lib.RepositoryCache.FileKey;
  80. import org.eclipse.jgit.util.FS;
  81. import org.eclipse.jgit.util.FileUtils;
  82. import org.slf4j.Logger;
  83. import org.slf4j.LoggerFactory;
  84. /**
  85. * Traditional file system based {@link ObjectDatabase}.
  86. * <p>
  87. * This is the classical object database representation for a Git repository,
  88. * where objects are stored loose by hashing them into directories by their
  89. * {@link ObjectId}, or are stored in compressed containers known as
  90. * {@link PackFile}s.
  91. * <p>
  92. * Optionally an object database can reference one or more alternates; other
  93. * ObjectDatabase instances that are searched in addition to the current
  94. * database.
  95. * <p>
  96. * Databases are divided into two halves: a half that is considered to be fast
  97. * to search (the {@code PackFile}s), and a half that is considered to be slow
  98. * to search (loose objects). When alternates are present the fast half is fully
  99. * searched (recursively through all alternates) before the slow half is
  100. * considered.
  101. */
  102. public class ObjectDirectory extends FileObjectDatabase {
  103. private final static Logger LOG = LoggerFactory
  104. .getLogger(ObjectDirectory.class);
  105. private static final PackList NO_PACKS = new PackList(
  106. FileSnapshot.DIRTY, new PackFile[0]);
  107. /** Maximum number of candidates offered as resolutions of abbreviation. */
  108. private static final int RESOLVE_ABBREV_LIMIT = 256;
  109. private static final String STALE_FILE_HANDLE_MSG = "stale file handle"; //$NON-NLS-1$
  110. private final Config config;
  111. private final File objects;
  112. private final File infoDirectory;
  113. private final File packDirectory;
  114. private final File alternatesFile;
  115. private final AtomicReference<PackList> packList;
  116. private final FS fs;
  117. private final AtomicReference<AlternateHandle[]> alternates;
  118. private final UnpackedObjectCache unpackedObjectCache;
  119. private final File shallowFile;
  120. private FileSnapshot shallowFileSnapshot = FileSnapshot.DIRTY;
  121. private Set<ObjectId> shallowCommitsIds;
  122. /**
  123. * Initialize a reference to an on-disk object directory.
  124. *
  125. * @param cfg
  126. * configuration this directory consults for write settings.
  127. * @param dir
  128. * the location of the <code>objects</code> directory.
  129. * @param alternatePaths
  130. * a list of alternate object directories
  131. * @param fs
  132. * the file system abstraction which will be necessary to perform
  133. * certain file system operations.
  134. * @param shallowFile
  135. * file which contains IDs of shallow commits, null if shallow
  136. * commits handling should be turned off
  137. * @throws IOException
  138. * an alternate object cannot be opened.
  139. */
  140. public ObjectDirectory(final Config cfg, final File dir,
  141. File[] alternatePaths, FS fs, File shallowFile) throws IOException {
  142. config = cfg;
  143. objects = dir;
  144. infoDirectory = new File(objects, "info"); //$NON-NLS-1$
  145. packDirectory = new File(objects, "pack"); //$NON-NLS-1$
  146. alternatesFile = new File(infoDirectory, "alternates"); //$NON-NLS-1$
  147. packList = new AtomicReference<PackList>(NO_PACKS);
  148. unpackedObjectCache = new UnpackedObjectCache();
  149. this.fs = fs;
  150. this.shallowFile = shallowFile;
  151. alternates = new AtomicReference<AlternateHandle[]>();
  152. if (alternatePaths != null) {
  153. AlternateHandle[] alt;
  154. alt = new AlternateHandle[alternatePaths.length];
  155. for (int i = 0; i < alternatePaths.length; i++)
  156. alt[i] = openAlternate(alternatePaths[i]);
  157. alternates.set(alt);
  158. }
  159. }
  160. /**
  161. * @return the location of the <code>objects</code> directory.
  162. */
  163. public final File getDirectory() {
  164. return objects;
  165. }
  166. @Override
  167. public boolean exists() {
  168. return fs.exists(objects);
  169. }
  170. @Override
  171. public void create() throws IOException {
  172. FileUtils.mkdirs(objects);
  173. FileUtils.mkdir(infoDirectory);
  174. FileUtils.mkdir(packDirectory);
  175. }
  176. @Override
  177. public ObjectDirectoryInserter newInserter() {
  178. return new ObjectDirectoryInserter(this, config);
  179. }
  180. @Override
  181. public void close() {
  182. unpackedObjectCache.clear();
  183. final PackList packs = packList.get();
  184. if (packs != NO_PACKS && packList.compareAndSet(packs, NO_PACKS)) {
  185. for (PackFile p : packs.packs)
  186. p.close();
  187. }
  188. // Fully close all loaded alternates and clear the alternate list.
  189. AlternateHandle[] alt = alternates.get();
  190. if (alt != null && alternates.compareAndSet(alt, null)) {
  191. for(final AlternateHandle od : alt)
  192. od.close();
  193. }
  194. }
  195. /**
  196. * @return unmodifiable collection of all known pack files local to this
  197. * directory. Most recent packs are presented first. Packs most
  198. * likely to contain more recent objects appear before packs
  199. * containing objects referenced by commits further back in the
  200. * history of the repository.
  201. */
  202. @Override
  203. public Collection<PackFile> getPacks() {
  204. PackList list = packList.get();
  205. if (list == NO_PACKS)
  206. list = scanPacks(list);
  207. PackFile[] packs = list.packs;
  208. return Collections.unmodifiableCollection(Arrays.asList(packs));
  209. }
  210. /**
  211. * Add a single existing pack to the list of available pack files.
  212. *
  213. * @param pack
  214. * path of the pack file to open.
  215. * @return the pack that was opened and added to the database.
  216. * @throws IOException
  217. * index file could not be opened, read, or is not recognized as
  218. * a Git pack file index.
  219. */
  220. public PackFile openPack(final File pack)
  221. throws IOException {
  222. final String p = pack.getName();
  223. if (p.length() != 50 || !p.startsWith("pack-") || !p.endsWith(".pack")) //$NON-NLS-1$ //$NON-NLS-2$
  224. throw new IOException(MessageFormat.format(JGitText.get().notAValidPack, pack));
  225. // The pack and index are assumed to exist. The existence of other
  226. // extensions needs to be explicitly checked.
  227. //
  228. int extensions = PACK.getBit() | INDEX.getBit();
  229. final String base = p.substring(0, p.length() - 4);
  230. for (PackExt ext : PackExt.values()) {
  231. if ((extensions & ext.getBit()) == 0) {
  232. final String name = base + ext.getExtension();
  233. if (new File(pack.getParentFile(), name).exists())
  234. extensions |= ext.getBit();
  235. }
  236. }
  237. PackFile res = new PackFile(pack, extensions);
  238. insertPack(res);
  239. return res;
  240. }
  241. @Override
  242. public String toString() {
  243. return "ObjectDirectory[" + getDirectory() + "]"; //$NON-NLS-1$ //$NON-NLS-2$
  244. }
  245. @Override
  246. public boolean has(AnyObjectId objectId) {
  247. return unpackedObjectCache.isUnpacked(objectId)
  248. || hasPackedInSelfOrAlternate(objectId)
  249. || hasLooseInSelfOrAlternate(objectId);
  250. }
  251. private boolean hasPackedInSelfOrAlternate(AnyObjectId objectId) {
  252. if (hasPackedObject(objectId))
  253. return true;
  254. for (AlternateHandle alt : myAlternates()) {
  255. if (alt.db.hasPackedInSelfOrAlternate(objectId))
  256. return true;
  257. }
  258. return false;
  259. }
  260. private boolean hasLooseInSelfOrAlternate(AnyObjectId objectId) {
  261. if (fileFor(objectId).exists())
  262. return true;
  263. for (AlternateHandle alt : myAlternates()) {
  264. if (alt.db.hasLooseInSelfOrAlternate(objectId))
  265. return true;
  266. }
  267. return false;
  268. }
  269. boolean hasPackedObject(AnyObjectId objectId) {
  270. PackList pList;
  271. do {
  272. pList = packList.get();
  273. for (PackFile p : pList.packs) {
  274. try {
  275. if (p.hasObject(objectId))
  276. return true;
  277. } catch (IOException e) {
  278. // The hasObject call should have only touched the index,
  279. // so any failure here indicates the index is unreadable
  280. // by this process, and the pack is likewise not readable.
  281. removePack(p);
  282. }
  283. }
  284. } while (searchPacksAgain(pList));
  285. return false;
  286. }
  287. @Override
  288. void resolve(Set<ObjectId> matches, AbbreviatedObjectId id)
  289. throws IOException {
  290. // Go through the packs once. If we didn't find any resolutions
  291. // scan for new packs and check once more.
  292. int oldSize = matches.size();
  293. PackList pList;
  294. do {
  295. pList = packList.get();
  296. for (PackFile p : pList.packs) {
  297. try {
  298. p.resolve(matches, id, RESOLVE_ABBREV_LIMIT);
  299. } catch (IOException e) {
  300. handlePackError(e, p);
  301. }
  302. if (matches.size() > RESOLVE_ABBREV_LIMIT)
  303. return;
  304. }
  305. } while (matches.size() == oldSize && searchPacksAgain(pList));
  306. String fanOut = id.name().substring(0, 2);
  307. String[] entries = new File(getDirectory(), fanOut).list();
  308. if (entries != null) {
  309. for (String e : entries) {
  310. if (e.length() != Constants.OBJECT_ID_STRING_LENGTH - 2)
  311. continue;
  312. try {
  313. ObjectId entId = ObjectId.fromString(fanOut + e);
  314. if (id.prefixCompare(entId) == 0)
  315. matches.add(entId);
  316. } catch (IllegalArgumentException notId) {
  317. continue;
  318. }
  319. if (matches.size() > RESOLVE_ABBREV_LIMIT)
  320. return;
  321. }
  322. }
  323. for (AlternateHandle alt : myAlternates()) {
  324. alt.db.resolve(matches, id);
  325. if (matches.size() > RESOLVE_ABBREV_LIMIT)
  326. return;
  327. }
  328. }
  329. @Override
  330. ObjectLoader openObject(WindowCursor curs, AnyObjectId objectId)
  331. throws IOException {
  332. if (unpackedObjectCache.isUnpacked(objectId)) {
  333. ObjectLoader ldr = openLooseObject(curs, objectId);
  334. if (ldr != null)
  335. return ldr;
  336. }
  337. ObjectLoader ldr = openPackedFromSelfOrAlternate(curs, objectId);
  338. if (ldr != null)
  339. return ldr;
  340. return openLooseFromSelfOrAlternate(curs, objectId);
  341. }
  342. private ObjectLoader openPackedFromSelfOrAlternate(WindowCursor curs,
  343. AnyObjectId objectId) {
  344. ObjectLoader ldr = openPackedObject(curs, objectId);
  345. if (ldr != null)
  346. return ldr;
  347. for (AlternateHandle alt : myAlternates()) {
  348. ldr = alt.db.openPackedFromSelfOrAlternate(curs, objectId);
  349. if (ldr != null)
  350. return ldr;
  351. }
  352. return null;
  353. }
  354. private ObjectLoader openLooseFromSelfOrAlternate(WindowCursor curs,
  355. AnyObjectId objectId) throws IOException {
  356. ObjectLoader ldr = openLooseObject(curs, objectId);
  357. if (ldr != null)
  358. return ldr;
  359. for (AlternateHandle alt : myAlternates()) {
  360. ldr = alt.db.openLooseFromSelfOrAlternate(curs, objectId);
  361. if (ldr != null)
  362. return ldr;
  363. }
  364. return null;
  365. }
  366. ObjectLoader openPackedObject(WindowCursor curs, AnyObjectId objectId) {
  367. PackList pList;
  368. do {
  369. SEARCH: for (;;) {
  370. pList = packList.get();
  371. for (PackFile p : pList.packs) {
  372. try {
  373. ObjectLoader ldr = p.get(curs, objectId);
  374. if (ldr != null)
  375. return ldr;
  376. } catch (PackMismatchException e) {
  377. // Pack was modified; refresh the entire pack list.
  378. if (searchPacksAgain(pList))
  379. continue SEARCH;
  380. } catch (IOException e) {
  381. handlePackError(e, p);
  382. }
  383. }
  384. break SEARCH;
  385. }
  386. } while (searchPacksAgain(pList));
  387. return null;
  388. }
  389. ObjectLoader openLooseObject(WindowCursor curs, AnyObjectId id)
  390. throws IOException {
  391. try {
  392. File path = fileFor(id);
  393. FileInputStream in = new FileInputStream(path);
  394. try {
  395. unpackedObjectCache.add(id);
  396. return UnpackedObject.open(in, path, id, curs);
  397. } finally {
  398. in.close();
  399. }
  400. } catch (FileNotFoundException noFile) {
  401. unpackedObjectCache.remove(id);
  402. return null;
  403. }
  404. }
  405. long getObjectSize(WindowCursor curs, AnyObjectId id)
  406. throws IOException {
  407. if (unpackedObjectCache.isUnpacked(id)) {
  408. long len = getLooseObjectSize(curs, id);
  409. if (0 <= len)
  410. return len;
  411. }
  412. long len = getPackedSizeFromSelfOrAlternate(curs, id);
  413. if (0 <= len)
  414. return len;
  415. return getLooseSizeFromSelfOrAlternate(curs, id);
  416. }
  417. private long getPackedSizeFromSelfOrAlternate(WindowCursor curs,
  418. AnyObjectId id) {
  419. long len = getPackedObjectSize(curs, id);
  420. if (0 <= len)
  421. return len;
  422. for (AlternateHandle alt : myAlternates()) {
  423. len = alt.db.getPackedSizeFromSelfOrAlternate(curs, id);
  424. if (0 <= len)
  425. return len;
  426. }
  427. return -1;
  428. }
  429. private long getLooseSizeFromSelfOrAlternate(WindowCursor curs,
  430. AnyObjectId id) throws IOException {
  431. long len = getLooseObjectSize(curs, id);
  432. if (0 <= len)
  433. return len;
  434. for (AlternateHandle alt : myAlternates()) {
  435. len = alt.db.getLooseSizeFromSelfOrAlternate(curs, id);
  436. if (0 <= len)
  437. return len;
  438. }
  439. return -1;
  440. }
  441. private long getPackedObjectSize(WindowCursor curs, AnyObjectId id) {
  442. PackList pList;
  443. do {
  444. SEARCH: for (;;) {
  445. pList = packList.get();
  446. for (PackFile p : pList.packs) {
  447. try {
  448. long len = p.getObjectSize(curs, id);
  449. if (0 <= len)
  450. return len;
  451. } catch (PackMismatchException e) {
  452. // Pack was modified; refresh the entire pack list.
  453. if (searchPacksAgain(pList))
  454. continue SEARCH;
  455. } catch (IOException e) {
  456. handlePackError(e, p);
  457. }
  458. }
  459. break SEARCH;
  460. }
  461. } while (searchPacksAgain(pList));
  462. return -1;
  463. }
  464. private long getLooseObjectSize(WindowCursor curs, AnyObjectId id)
  465. throws IOException {
  466. try {
  467. FileInputStream in = new FileInputStream(fileFor(id));
  468. try {
  469. unpackedObjectCache.add(id);
  470. return UnpackedObject.getSize(in, id, curs);
  471. } finally {
  472. in.close();
  473. }
  474. } catch (FileNotFoundException noFile) {
  475. unpackedObjectCache.remove(id);
  476. return -1;
  477. }
  478. }
  479. @Override
  480. void selectObjectRepresentation(PackWriter packer, ObjectToPack otp,
  481. WindowCursor curs) throws IOException {
  482. PackList pList = packList.get();
  483. SEARCH: for (;;) {
  484. for (final PackFile p : pList.packs) {
  485. try {
  486. LocalObjectRepresentation rep = p.representation(curs, otp);
  487. if (rep != null)
  488. packer.select(otp, rep);
  489. } catch (PackMismatchException e) {
  490. // Pack was modified; refresh the entire pack list.
  491. //
  492. pList = scanPacks(pList);
  493. continue SEARCH;
  494. } catch (IOException e) {
  495. handlePackError(e, p);
  496. }
  497. }
  498. break SEARCH;
  499. }
  500. for (AlternateHandle h : myAlternates())
  501. h.db.selectObjectRepresentation(packer, otp, curs);
  502. }
  503. private void handlePackError(IOException e, PackFile p) {
  504. String warnTmpl = null;
  505. if ((e instanceof CorruptObjectException)
  506. || (e instanceof PackInvalidException)) {
  507. warnTmpl = JGitText.get().corruptPack;
  508. // Assume the pack is corrupted, and remove it from the list.
  509. removePack(p);
  510. } else if (e instanceof FileNotFoundException) {
  511. warnTmpl = JGitText.get().packWasDeleted;
  512. removePack(p);
  513. } else if (e.getMessage() != null
  514. && e.getMessage().toLowerCase().contains(STALE_FILE_HANDLE_MSG)) {
  515. warnTmpl = JGitText.get().packHandleIsStale;
  516. removePack(p);
  517. }
  518. if (warnTmpl != null) {
  519. if (LOG.isDebugEnabled()) {
  520. LOG.debug(MessageFormat.format(warnTmpl,
  521. p.getPackFile().getAbsolutePath()), e);
  522. } else {
  523. LOG.warn(MessageFormat.format(warnTmpl,
  524. p.getPackFile().getAbsolutePath()));
  525. }
  526. } else {
  527. // Don't remove the pack from the list, as the error may be
  528. // transient.
  529. LOG.error(MessageFormat.format(
  530. JGitText.get().exceptionWhileReadingPack, p.getPackFile()
  531. .getAbsolutePath()), e);
  532. }
  533. }
  534. @Override
  535. InsertLooseObjectResult insertUnpackedObject(File tmp, ObjectId id,
  536. boolean createDuplicate) throws IOException {
  537. // If the object is already in the repository, remove temporary file.
  538. //
  539. if (unpackedObjectCache.isUnpacked(id)) {
  540. FileUtils.delete(tmp, FileUtils.RETRY);
  541. return InsertLooseObjectResult.EXISTS_LOOSE;
  542. }
  543. if (!createDuplicate && has(id)) {
  544. FileUtils.delete(tmp, FileUtils.RETRY);
  545. return InsertLooseObjectResult.EXISTS_PACKED;
  546. }
  547. final File dst = fileFor(id);
  548. if (fs.exists(dst)) {
  549. // We want to be extra careful and avoid replacing an object
  550. // that already exists. We can't be sure renameTo() would
  551. // fail on all platforms if dst exists, so we check first.
  552. //
  553. FileUtils.delete(tmp, FileUtils.RETRY);
  554. return InsertLooseObjectResult.EXISTS_LOOSE;
  555. }
  556. if (tmp.renameTo(dst)) {
  557. dst.setReadOnly();
  558. unpackedObjectCache.add(id);
  559. return InsertLooseObjectResult.INSERTED;
  560. }
  561. // Maybe the directory doesn't exist yet as the object
  562. // directories are always lazily created. Note that we
  563. // try the rename first as the directory likely does exist.
  564. //
  565. FileUtils.mkdir(dst.getParentFile(), true);
  566. if (tmp.renameTo(dst)) {
  567. dst.setReadOnly();
  568. unpackedObjectCache.add(id);
  569. return InsertLooseObjectResult.INSERTED;
  570. }
  571. if (!createDuplicate && has(id)) {
  572. FileUtils.delete(tmp, FileUtils.RETRY);
  573. return InsertLooseObjectResult.EXISTS_PACKED;
  574. }
  575. // The object failed to be renamed into its proper
  576. // location and it doesn't exist in the repository
  577. // either. We really don't know what went wrong, so
  578. // fail.
  579. //
  580. FileUtils.delete(tmp, FileUtils.RETRY);
  581. return InsertLooseObjectResult.FAILURE;
  582. }
  583. private boolean searchPacksAgain(PackList old) {
  584. // Whether to trust the pack folder's modification time. If set
  585. // to false we will always scan the .git/objects/pack folder to
  586. // check for new pack files. If set to true (default) we use the
  587. // lastmodified attribute of the folder and assume that no new
  588. // pack files can be in this folder if his modification time has
  589. // not changed.
  590. boolean trustFolderStat = config.getBoolean(
  591. ConfigConstants.CONFIG_CORE_SECTION,
  592. ConfigConstants.CONFIG_KEY_TRUSTFOLDERSTAT, true);
  593. return ((!trustFolderStat) || old.snapshot.isModified(packDirectory))
  594. && old != scanPacks(old);
  595. }
  596. Config getConfig() {
  597. return config;
  598. }
  599. @Override
  600. FS getFS() {
  601. return fs;
  602. }
  603. @Override
  604. Set<ObjectId> getShallowCommits() throws IOException {
  605. if (shallowFile == null || !shallowFile.isFile())
  606. return Collections.emptySet();
  607. if (shallowFileSnapshot == null
  608. || shallowFileSnapshot.isModified(shallowFile)) {
  609. shallowCommitsIds = new HashSet<ObjectId>();
  610. final BufferedReader reader = open(shallowFile);
  611. try {
  612. String line;
  613. while ((line = reader.readLine()) != null)
  614. shallowCommitsIds.add(ObjectId.fromString(line));
  615. } finally {
  616. reader.close();
  617. }
  618. shallowFileSnapshot = FileSnapshot.save(shallowFile);
  619. }
  620. return shallowCommitsIds;
  621. }
  622. private void insertPack(final PackFile pf) {
  623. PackList o, n;
  624. do {
  625. o = packList.get();
  626. // If the pack in question is already present in the list
  627. // (picked up by a concurrent thread that did a scan?) we
  628. // do not want to insert it a second time.
  629. //
  630. final PackFile[] oldList = o.packs;
  631. final String name = pf.getPackFile().getName();
  632. for (PackFile p : oldList) {
  633. if (PackFile.SORT.compare(pf, p) < 0)
  634. break;
  635. if (name.equals(p.getPackFile().getName()))
  636. return;
  637. }
  638. final PackFile[] newList = new PackFile[1 + oldList.length];
  639. newList[0] = pf;
  640. System.arraycopy(oldList, 0, newList, 1, oldList.length);
  641. n = new PackList(o.snapshot, newList);
  642. } while (!packList.compareAndSet(o, n));
  643. }
  644. private void removePack(final PackFile deadPack) {
  645. PackList o, n;
  646. do {
  647. o = packList.get();
  648. final PackFile[] oldList = o.packs;
  649. final int j = indexOf(oldList, deadPack);
  650. if (j < 0)
  651. break;
  652. final PackFile[] newList = new PackFile[oldList.length - 1];
  653. System.arraycopy(oldList, 0, newList, 0, j);
  654. System.arraycopy(oldList, j + 1, newList, j, newList.length - j);
  655. n = new PackList(o.snapshot, newList);
  656. } while (!packList.compareAndSet(o, n));
  657. deadPack.close();
  658. }
  659. private static int indexOf(final PackFile[] list, final PackFile pack) {
  660. for (int i = 0; i < list.length; i++) {
  661. if (list[i] == pack)
  662. return i;
  663. }
  664. return -1;
  665. }
  666. private PackList scanPacks(final PackList original) {
  667. synchronized (packList) {
  668. PackList o, n;
  669. do {
  670. o = packList.get();
  671. if (o != original) {
  672. // Another thread did the scan for us, while we
  673. // were blocked on the monitor above.
  674. //
  675. return o;
  676. }
  677. n = scanPacksImpl(o);
  678. if (n == o)
  679. return n;
  680. } while (!packList.compareAndSet(o, n));
  681. return n;
  682. }
  683. }
  684. private PackList scanPacksImpl(final PackList old) {
  685. final Map<String, PackFile> forReuse = reuseMap(old);
  686. final FileSnapshot snapshot = FileSnapshot.save(packDirectory);
  687. final Set<String> names = listPackDirectory();
  688. final List<PackFile> list = new ArrayList<PackFile>(names.size() >> 2);
  689. boolean foundNew = false;
  690. for (final String indexName : names) {
  691. // Must match "pack-[0-9a-f]{40}.idx" to be an index.
  692. //
  693. if (indexName.length() != 49 || !indexName.endsWith(".idx")) //$NON-NLS-1$
  694. continue;
  695. final String base = indexName.substring(0, indexName.length() - 3);
  696. int extensions = 0;
  697. for (PackExt ext : PackExt.values()) {
  698. if (names.contains(base + ext.getExtension()))
  699. extensions |= ext.getBit();
  700. }
  701. if ((extensions & PACK.getBit()) == 0) {
  702. // Sometimes C Git's HTTP fetch transport leaves a
  703. // .idx file behind and does not download the .pack.
  704. // We have to skip over such useless indexes.
  705. //
  706. continue;
  707. }
  708. final String packName = base + PACK.getExtension();
  709. final PackFile oldPack = forReuse.remove(packName);
  710. if (oldPack != null) {
  711. list.add(oldPack);
  712. continue;
  713. }
  714. final File packFile = new File(packDirectory, packName);
  715. list.add(new PackFile(packFile, extensions));
  716. foundNew = true;
  717. }
  718. // If we did not discover any new files, the modification time was not
  719. // changed, and we did not remove any files, then the set of files is
  720. // the same as the set we were given. Instead of building a new object
  721. // return the same collection.
  722. //
  723. if (!foundNew && forReuse.isEmpty() && snapshot.equals(old.snapshot)) {
  724. old.snapshot.setClean(snapshot);
  725. return old;
  726. }
  727. for (final PackFile p : forReuse.values()) {
  728. p.close();
  729. }
  730. if (list.isEmpty())
  731. return new PackList(snapshot, NO_PACKS.packs);
  732. final PackFile[] r = list.toArray(new PackFile[list.size()]);
  733. Arrays.sort(r, PackFile.SORT);
  734. return new PackList(snapshot, r);
  735. }
  736. private static Map<String, PackFile> reuseMap(final PackList old) {
  737. final Map<String, PackFile> forReuse = new HashMap<String, PackFile>();
  738. for (final PackFile p : old.packs) {
  739. if (p.invalid()) {
  740. // The pack instance is corrupted, and cannot be safely used
  741. // again. Do not include it in our reuse map.
  742. //
  743. p.close();
  744. continue;
  745. }
  746. final PackFile prior = forReuse.put(p.getPackFile().getName(), p);
  747. if (prior != null) {
  748. // This should never occur. It should be impossible for us
  749. // to have two pack files with the same name, as all of them
  750. // came out of the same directory. If it does, we promised to
  751. // close any PackFiles we did not reuse, so close the second,
  752. // readers are likely to be actively using the first.
  753. //
  754. forReuse.put(prior.getPackFile().getName(), prior);
  755. p.close();
  756. }
  757. }
  758. return forReuse;
  759. }
  760. private Set<String> listPackDirectory() {
  761. final String[] nameList = packDirectory.list();
  762. if (nameList == null)
  763. return Collections.emptySet();
  764. final Set<String> nameSet = new HashSet<String>(nameList.length << 1);
  765. for (final String name : nameList) {
  766. if (name.startsWith("pack-")) //$NON-NLS-1$
  767. nameSet.add(name);
  768. }
  769. return nameSet;
  770. }
  771. AlternateHandle[] myAlternates() {
  772. AlternateHandle[] alt = alternates.get();
  773. if (alt == null) {
  774. synchronized (alternates) {
  775. alt = alternates.get();
  776. if (alt == null) {
  777. try {
  778. alt = loadAlternates();
  779. } catch (IOException e) {
  780. alt = new AlternateHandle[0];
  781. }
  782. alternates.set(alt);
  783. }
  784. }
  785. }
  786. return alt;
  787. }
  788. private AlternateHandle[] loadAlternates() throws IOException {
  789. final List<AlternateHandle> l = new ArrayList<AlternateHandle>(4);
  790. final BufferedReader br = open(alternatesFile);
  791. try {
  792. String line;
  793. while ((line = br.readLine()) != null) {
  794. l.add(openAlternate(line));
  795. }
  796. } finally {
  797. br.close();
  798. }
  799. return l.toArray(new AlternateHandle[l.size()]);
  800. }
  801. private static BufferedReader open(final File f)
  802. throws FileNotFoundException {
  803. return new BufferedReader(new FileReader(f));
  804. }
  805. private AlternateHandle openAlternate(final String location)
  806. throws IOException {
  807. final File objdir = fs.resolve(objects, location);
  808. return openAlternate(objdir);
  809. }
  810. private AlternateHandle openAlternate(File objdir) throws IOException {
  811. final File parent = objdir.getParentFile();
  812. if (FileKey.isGitRepository(parent, fs)) {
  813. FileKey key = FileKey.exact(parent, fs);
  814. FileRepository db = (FileRepository) RepositoryCache.open(key);
  815. return new AlternateRepository(db);
  816. }
  817. ObjectDirectory db = new ObjectDirectory(config, objdir, null, fs, null);
  818. return new AlternateHandle(db);
  819. }
  820. /**
  821. * Compute the location of a loose object file.
  822. *
  823. * @param objectId
  824. * identity of the loose object to map to the directory.
  825. * @return location of the object, if it were to exist as a loose object.
  826. */
  827. public File fileFor(AnyObjectId objectId) {
  828. String n = objectId.name();
  829. String d = n.substring(0, 2);
  830. String f = n.substring(2);
  831. return new File(new File(getDirectory(), d), f);
  832. }
  833. private static final class PackList {
  834. /** State just before reading the pack directory. */
  835. final FileSnapshot snapshot;
  836. /** All known packs, sorted by {@link PackFile#SORT}. */
  837. final PackFile[] packs;
  838. PackList(final FileSnapshot monitor, final PackFile[] packs) {
  839. this.snapshot = monitor;
  840. this.packs = packs;
  841. }
  842. }
  843. static class AlternateHandle {
  844. final ObjectDirectory db;
  845. AlternateHandle(ObjectDirectory db) {
  846. this.db = db;
  847. }
  848. void close() {
  849. db.close();
  850. }
  851. }
  852. static class AlternateRepository extends AlternateHandle {
  853. final FileRepository repository;
  854. AlternateRepository(FileRepository r) {
  855. super(r.getObjectDatabase());
  856. repository = r;
  857. }
  858. void close() {
  859. repository.close();
  860. }
  861. }
  862. @Override
  863. public ObjectDatabase newCachedDatabase() {
  864. return newCachedFileObjectDatabase();
  865. }
  866. CachedObjectDirectory newCachedFileObjectDatabase() {
  867. return new CachedObjectDirectory(this);
  868. }
  869. }