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 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  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.lib;
  44. import java.io.BufferedReader;
  45. import java.io.File;
  46. import java.io.FileNotFoundException;
  47. import java.io.FileReader;
  48. import java.io.IOException;
  49. import java.util.ArrayList;
  50. import java.util.Arrays;
  51. import java.util.Collection;
  52. import java.util.Collections;
  53. import java.util.HashMap;
  54. import java.util.HashSet;
  55. import java.util.List;
  56. import java.util.Map;
  57. import java.util.Set;
  58. import java.util.concurrent.atomic.AtomicReference;
  59. import org.eclipse.jgit.errors.PackMismatchException;
  60. import org.eclipse.jgit.lib.RepositoryCache.FileKey;
  61. import org.eclipse.jgit.util.FS;
  62. /**
  63. * Traditional file system based {@link ObjectDatabase}.
  64. * <p>
  65. * This is the classical object database representation for a Git repository,
  66. * where objects are stored loose by hashing them into directories by their
  67. * {@link ObjectId}, or are stored in compressed containers known as
  68. * {@link PackFile}s.
  69. */
  70. public class ObjectDirectory extends ObjectDatabase {
  71. private static final PackList NO_PACKS = new PackList(-1, -1, new PackFile[0]);
  72. private final File objects;
  73. private final File infoDirectory;
  74. private final File packDirectory;
  75. private final File alternatesFile;
  76. private final AtomicReference<PackList> packList;
  77. private final File[] alternateObjectDir;
  78. /**
  79. * Initialize a reference to an on-disk object directory.
  80. *
  81. * @param dir
  82. * the location of the <code>objects</code> directory.
  83. * @param alternateObjectDir
  84. * a list of alternate object directories
  85. */
  86. public ObjectDirectory(final File dir, File[] alternateObjectDir) {
  87. objects = dir;
  88. this.alternateObjectDir = alternateObjectDir;
  89. infoDirectory = new File(objects, "info");
  90. packDirectory = new File(objects, "pack");
  91. alternatesFile = new File(infoDirectory, "alternates");
  92. packList = new AtomicReference<PackList>(NO_PACKS);
  93. }
  94. /**
  95. * @return the location of the <code>objects</code> directory.
  96. */
  97. public final File getDirectory() {
  98. return objects;
  99. }
  100. @Override
  101. public boolean exists() {
  102. return objects.exists();
  103. }
  104. @Override
  105. public void create() throws IOException {
  106. objects.mkdirs();
  107. infoDirectory.mkdir();
  108. packDirectory.mkdir();
  109. }
  110. @Override
  111. public void closeSelf() {
  112. final PackList packs = packList.get();
  113. packList.set(NO_PACKS);
  114. for (final PackFile p : packs.packs)
  115. p.close();
  116. }
  117. /**
  118. * Compute the location of a loose object file.
  119. *
  120. * @param objectId
  121. * identity of the loose object to map to the directory.
  122. * @return location of the object, if it were to exist as a loose object.
  123. */
  124. public File fileFor(final AnyObjectId objectId) {
  125. return fileFor(objectId.name());
  126. }
  127. private File fileFor(final String objectName) {
  128. final String d = objectName.substring(0, 2);
  129. final String f = objectName.substring(2);
  130. return new File(new File(objects, d), f);
  131. }
  132. /**
  133. * @return unmodifiable collection of all known pack files local to this
  134. * directory. Most recent packs are presented first. Packs most
  135. * likely to contain more recent objects appear before packs
  136. * containing objects referenced by commits further back in the
  137. * history of the repository.
  138. */
  139. public Collection<PackFile> getPacks() {
  140. final PackFile[] packs = packList.get().packs;
  141. return Collections.unmodifiableCollection(Arrays.asList(packs));
  142. }
  143. /**
  144. * Add a single existing pack to the list of available pack files.
  145. *
  146. * @param pack
  147. * path of the pack file to open.
  148. * @param idx
  149. * path of the corresponding index file.
  150. * @throws IOException
  151. * index file could not be opened, read, or is not recognized as
  152. * a Git pack file index.
  153. */
  154. public void openPack(final File pack, final File idx) throws IOException {
  155. final String p = pack.getName();
  156. final String i = idx.getName();
  157. if (p.length() != 50 || !p.startsWith("pack-") || !p.endsWith(".pack"))
  158. throw new IOException("Not a valid pack " + pack);
  159. if (i.length() != 49 || !i.startsWith("pack-") || !i.endsWith(".idx"))
  160. throw new IOException("Not a valid pack " + idx);
  161. if (!p.substring(0, 45).equals(i.substring(0, 45)))
  162. throw new IOException("Pack " + pack + "does not match index");
  163. insertPack(new PackFile(idx, pack));
  164. }
  165. @Override
  166. public String toString() {
  167. return "ObjectDirectory[" + getDirectory() + "]";
  168. }
  169. @Override
  170. protected boolean hasObject1(final AnyObjectId objectId) {
  171. for (final PackFile p : packList.get().packs) {
  172. try {
  173. if (p.hasObject(objectId)) {
  174. return true;
  175. }
  176. } catch (IOException e) {
  177. // The hasObject call should have only touched the index,
  178. // so any failure here indicates the index is unreadable
  179. // by this process, and the pack is likewise not readable.
  180. //
  181. removePack(p);
  182. continue;
  183. }
  184. }
  185. return false;
  186. }
  187. @Override
  188. protected ObjectLoader openObject1(final WindowCursor curs,
  189. final AnyObjectId objectId) throws IOException {
  190. PackList pList = packList.get();
  191. SEARCH: for (;;) {
  192. for (final PackFile p : pList.packs) {
  193. try {
  194. final PackedObjectLoader ldr = p.get(curs, objectId);
  195. if (ldr != null) {
  196. ldr.materialize(curs);
  197. return ldr;
  198. }
  199. } catch (PackMismatchException e) {
  200. // Pack was modified; refresh the entire pack list.
  201. //
  202. pList = scanPacks(pList);
  203. continue SEARCH;
  204. } catch (IOException e) {
  205. // Assume the pack is corrupted.
  206. //
  207. removePack(p);
  208. }
  209. }
  210. return null;
  211. }
  212. }
  213. @Override
  214. void openObjectInAllPacks1(final Collection<PackedObjectLoader> out,
  215. final WindowCursor curs, final AnyObjectId objectId)
  216. throws IOException {
  217. PackList pList = packList.get();
  218. SEARCH: for (;;) {
  219. for (final PackFile p : pList.packs) {
  220. try {
  221. final PackedObjectLoader ldr = p.get(curs, objectId);
  222. if (ldr != null) {
  223. out.add(ldr);
  224. }
  225. } catch (PackMismatchException e) {
  226. // Pack was modified; refresh the entire pack list.
  227. //
  228. pList = scanPacks(pList);
  229. continue SEARCH;
  230. } catch (IOException e) {
  231. // Assume the pack is corrupted.
  232. //
  233. removePack(p);
  234. }
  235. }
  236. break SEARCH;
  237. }
  238. }
  239. @Override
  240. protected boolean hasObject2(final String objectName) {
  241. return fileFor(objectName).exists();
  242. }
  243. @Override
  244. protected ObjectLoader openObject2(final WindowCursor curs,
  245. final String objectName, final AnyObjectId objectId)
  246. throws IOException {
  247. try {
  248. return new UnpackedObjectLoader(fileFor(objectName), objectId);
  249. } catch (FileNotFoundException noFile) {
  250. return null;
  251. }
  252. }
  253. @Override
  254. protected boolean tryAgain1() {
  255. final PackList old = packList.get();
  256. if (old.tryAgain(packDirectory.lastModified()))
  257. return old != scanPacks(old);
  258. return false;
  259. }
  260. private void insertPack(final PackFile pf) {
  261. PackList o, n;
  262. do {
  263. o = packList.get();
  264. final PackFile[] oldList = o.packs;
  265. final PackFile[] newList = new PackFile[1 + oldList.length];
  266. newList[0] = pf;
  267. System.arraycopy(oldList, 0, newList, 1, oldList.length);
  268. n = new PackList(o.lastRead, o.lastModified, newList);
  269. } while (!packList.compareAndSet(o, n));
  270. }
  271. private void removePack(final PackFile deadPack) {
  272. PackList o, n;
  273. do {
  274. o = packList.get();
  275. final PackFile[] oldList = o.packs;
  276. final int j = indexOf(oldList, deadPack);
  277. if (j < 0)
  278. break;
  279. final PackFile[] newList = new PackFile[oldList.length - 1];
  280. System.arraycopy(oldList, 0, newList, 0, j);
  281. System.arraycopy(oldList, j + 1, newList, j, newList.length - j);
  282. n = new PackList(o.lastRead, o.lastModified, newList);
  283. } while (!packList.compareAndSet(o, n));
  284. deadPack.close();
  285. }
  286. private static int indexOf(final PackFile[] list, final PackFile pack) {
  287. for (int i = 0; i < list.length; i++) {
  288. if (list[i] == pack)
  289. return i;
  290. }
  291. return -1;
  292. }
  293. private PackList scanPacks(final PackList original) {
  294. synchronized (packList) {
  295. PackList o, n;
  296. do {
  297. o = packList.get();
  298. if (o != original) {
  299. // Another thread did the scan for us, while we
  300. // were blocked on the monitor above.
  301. //
  302. return o;
  303. }
  304. n = scanPacksImpl(o);
  305. if (n == o)
  306. return n;
  307. } while (!packList.compareAndSet(o, n));
  308. return n;
  309. }
  310. }
  311. private PackList scanPacksImpl(final PackList old) {
  312. final Map<String, PackFile> forReuse = reuseMap(old);
  313. final long lastRead = System.currentTimeMillis();
  314. final long lastModified = packDirectory.lastModified();
  315. final Set<String> names = listPackDirectory();
  316. final List<PackFile> list = new ArrayList<PackFile>(names.size() >> 2);
  317. boolean foundNew = false;
  318. for (final String indexName : names) {
  319. // Must match "pack-[0-9a-f]{40}.idx" to be an index.
  320. //
  321. if (indexName.length() != 49 || !indexName.endsWith(".idx"))
  322. continue;
  323. final String base = indexName.substring(0, indexName.length() - 4);
  324. final String packName = base + ".pack";
  325. if (!names.contains(packName)) {
  326. // Sometimes C Git's HTTP fetch transport leaves a
  327. // .idx file behind and does not download the .pack.
  328. // We have to skip over such useless indexes.
  329. //
  330. continue;
  331. }
  332. final PackFile oldPack = forReuse.remove(packName);
  333. if (oldPack != null) {
  334. list.add(oldPack);
  335. continue;
  336. }
  337. final File packFile = new File(packDirectory, packName);
  338. final File idxFile = new File(packDirectory, indexName);
  339. list.add(new PackFile(idxFile, packFile));
  340. foundNew = true;
  341. }
  342. // If we did not discover any new files, the modification time was not
  343. // changed, and we did not remove any files, then the set of files is
  344. // the same as the set we were given. Instead of building a new object
  345. // return the same collection.
  346. //
  347. if (!foundNew && lastModified == old.lastModified && forReuse.isEmpty())
  348. return old.updateLastRead(lastRead);
  349. for (final PackFile p : forReuse.values()) {
  350. p.close();
  351. }
  352. if (list.isEmpty())
  353. return new PackList(lastRead, lastModified, NO_PACKS.packs);
  354. final PackFile[] r = list.toArray(new PackFile[list.size()]);
  355. Arrays.sort(r, PackFile.SORT);
  356. return new PackList(lastRead, lastModified, r);
  357. }
  358. private static Map<String, PackFile> reuseMap(final PackList old) {
  359. final Map<String, PackFile> forReuse = new HashMap<String, PackFile>();
  360. for (final PackFile p : old.packs) {
  361. if (p.invalid()) {
  362. // The pack instance is corrupted, and cannot be safely used
  363. // again. Do not include it in our reuse map.
  364. //
  365. p.close();
  366. continue;
  367. }
  368. final PackFile prior = forReuse.put(p.getPackFile().getName(), p);
  369. if (prior != null) {
  370. // This should never occur. It should be impossible for us
  371. // to have two pack files with the same name, as all of them
  372. // came out of the same directory. If it does, we promised to
  373. // close any PackFiles we did not reuse, so close the second,
  374. // readers are likely to be actively using the first.
  375. //
  376. forReuse.put(prior.getPackFile().getName(), prior);
  377. p.close();
  378. }
  379. }
  380. return forReuse;
  381. }
  382. private Set<String> listPackDirectory() {
  383. final String[] nameList = packDirectory.list();
  384. if (nameList == null)
  385. return Collections.emptySet();
  386. final Set<String> nameSet = new HashSet<String>(nameList.length << 1);
  387. for (final String name : nameList) {
  388. if (name.startsWith("pack-"))
  389. nameSet.add(name);
  390. }
  391. return nameSet;
  392. }
  393. @Override
  394. protected ObjectDatabase[] loadAlternates() throws IOException {
  395. final List<ObjectDatabase> l = new ArrayList<ObjectDatabase>(4);
  396. if (alternateObjectDir != null) {
  397. for (File d : alternateObjectDir) {
  398. l.add(openAlternate(d));
  399. }
  400. } else {
  401. final BufferedReader br = open(alternatesFile);
  402. try {
  403. String line;
  404. while ((line = br.readLine()) != null) {
  405. l.add(openAlternate(line));
  406. }
  407. } finally {
  408. br.close();
  409. }
  410. }
  411. if (l.isEmpty()) {
  412. return NO_ALTERNATES;
  413. }
  414. return l.toArray(new ObjectDatabase[l.size()]);
  415. }
  416. private static BufferedReader open(final File f)
  417. throws FileNotFoundException {
  418. return new BufferedReader(new FileReader(f));
  419. }
  420. private ObjectDatabase openAlternate(final String location)
  421. throws IOException {
  422. final File objdir = FS.resolve(objects, location);
  423. return openAlternate(objdir);
  424. }
  425. private ObjectDatabase openAlternate(File objdir) throws IOException {
  426. final File parent = objdir.getParentFile();
  427. if (FileKey.isGitRepository(parent)) {
  428. final Repository db = RepositoryCache.open(FileKey.exact(parent));
  429. return new AlternateRepositoryDatabase(db);
  430. }
  431. return new ObjectDirectory(objdir, null);
  432. }
  433. private static final class PackList {
  434. /** Last wall-clock time the directory was read. */
  435. volatile long lastRead;
  436. /** Last modification time of {@link ObjectDirectory#packDirectory}. */
  437. final long lastModified;
  438. /** All known packs, sorted by {@link PackFile#SORT}. */
  439. final PackFile[] packs;
  440. private boolean cannotBeRacilyClean;
  441. PackList(final long lastRead, final long lastModified,
  442. final PackFile[] packs) {
  443. this.lastRead = lastRead;
  444. this.lastModified = lastModified;
  445. this.packs = packs;
  446. this.cannotBeRacilyClean = notRacyClean(lastRead);
  447. }
  448. private boolean notRacyClean(final long read) {
  449. return read - lastModified > 2 * 60 * 1000L;
  450. }
  451. PackList updateLastRead(final long now) {
  452. if (notRacyClean(now))
  453. cannotBeRacilyClean = true;
  454. lastRead = now;
  455. return this;
  456. }
  457. boolean tryAgain(final long currLastModified) {
  458. // Any difference indicates the directory was modified.
  459. //
  460. if (lastModified != currLastModified)
  461. return true;
  462. // We have already determined the last read was far enough
  463. // after the last modification that any new modifications
  464. // are certain to change the last modified time.
  465. //
  466. if (cannotBeRacilyClean)
  467. return false;
  468. if (notRacyClean(lastRead)) {
  469. // Our last read should have marked cannotBeRacilyClean,
  470. // but this thread may not have seen the change. The read
  471. // of the volatile field lastRead should have fixed that.
  472. //
  473. return false;
  474. }
  475. // We last read this directory too close to its last observed
  476. // modification time. We may have missed a modification. Scan
  477. // the directory again, to ensure we still see the same state.
  478. //
  479. return true;
  480. }
  481. }
  482. @Override
  483. public ObjectDatabase newCachedDatabase() {
  484. return new CachedObjectDirectory(this);
  485. }
  486. }