You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ObjectDirectory.java 29KB

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