Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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