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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  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. // If the pack in question is already present in the list
  265. // (picked up by a concurrent thread that did a scan?) we
  266. // do not want to insert it a second time.
  267. //
  268. final PackFile[] oldList = o.packs;
  269. final String name = pf.getPackFile().getName();
  270. for (PackFile p : oldList) {
  271. if (PackFile.SORT.compare(pf, p) < 0)
  272. break;
  273. if (name.equals(p.getPackFile().getName()))
  274. return;
  275. }
  276. final PackFile[] newList = new PackFile[1 + oldList.length];
  277. newList[0] = pf;
  278. System.arraycopy(oldList, 0, newList, 1, oldList.length);
  279. n = new PackList(o.lastRead, o.lastModified, newList);
  280. } while (!packList.compareAndSet(o, n));
  281. }
  282. private void removePack(final PackFile deadPack) {
  283. PackList o, n;
  284. do {
  285. o = packList.get();
  286. final PackFile[] oldList = o.packs;
  287. final int j = indexOf(oldList, deadPack);
  288. if (j < 0)
  289. break;
  290. final PackFile[] newList = new PackFile[oldList.length - 1];
  291. System.arraycopy(oldList, 0, newList, 0, j);
  292. System.arraycopy(oldList, j + 1, newList, j, newList.length - j);
  293. n = new PackList(o.lastRead, o.lastModified, newList);
  294. } while (!packList.compareAndSet(o, n));
  295. deadPack.close();
  296. }
  297. private static int indexOf(final PackFile[] list, final PackFile pack) {
  298. for (int i = 0; i < list.length; i++) {
  299. if (list[i] == pack)
  300. return i;
  301. }
  302. return -1;
  303. }
  304. private PackList scanPacks(final PackList original) {
  305. synchronized (packList) {
  306. PackList o, n;
  307. do {
  308. o = packList.get();
  309. if (o != original) {
  310. // Another thread did the scan for us, while we
  311. // were blocked on the monitor above.
  312. //
  313. return o;
  314. }
  315. n = scanPacksImpl(o);
  316. if (n == o)
  317. return n;
  318. } while (!packList.compareAndSet(o, n));
  319. return n;
  320. }
  321. }
  322. private PackList scanPacksImpl(final PackList old) {
  323. final Map<String, PackFile> forReuse = reuseMap(old);
  324. final long lastRead = System.currentTimeMillis();
  325. final long lastModified = packDirectory.lastModified();
  326. final Set<String> names = listPackDirectory();
  327. final List<PackFile> list = new ArrayList<PackFile>(names.size() >> 2);
  328. boolean foundNew = false;
  329. for (final String indexName : names) {
  330. // Must match "pack-[0-9a-f]{40}.idx" to be an index.
  331. //
  332. if (indexName.length() != 49 || !indexName.endsWith(".idx"))
  333. continue;
  334. final String base = indexName.substring(0, indexName.length() - 4);
  335. final String packName = base + ".pack";
  336. if (!names.contains(packName)) {
  337. // Sometimes C Git's HTTP fetch transport leaves a
  338. // .idx file behind and does not download the .pack.
  339. // We have to skip over such useless indexes.
  340. //
  341. continue;
  342. }
  343. final PackFile oldPack = forReuse.remove(packName);
  344. if (oldPack != null) {
  345. list.add(oldPack);
  346. continue;
  347. }
  348. final File packFile = new File(packDirectory, packName);
  349. final File idxFile = new File(packDirectory, indexName);
  350. list.add(new PackFile(idxFile, packFile));
  351. foundNew = true;
  352. }
  353. // If we did not discover any new files, the modification time was not
  354. // changed, and we did not remove any files, then the set of files is
  355. // the same as the set we were given. Instead of building a new object
  356. // return the same collection.
  357. //
  358. if (!foundNew && lastModified == old.lastModified && forReuse.isEmpty())
  359. return old.updateLastRead(lastRead);
  360. for (final PackFile p : forReuse.values()) {
  361. p.close();
  362. }
  363. if (list.isEmpty())
  364. return new PackList(lastRead, lastModified, NO_PACKS.packs);
  365. final PackFile[] r = list.toArray(new PackFile[list.size()]);
  366. Arrays.sort(r, PackFile.SORT);
  367. return new PackList(lastRead, lastModified, r);
  368. }
  369. private static Map<String, PackFile> reuseMap(final PackList old) {
  370. final Map<String, PackFile> forReuse = new HashMap<String, PackFile>();
  371. for (final PackFile p : old.packs) {
  372. if (p.invalid()) {
  373. // The pack instance is corrupted, and cannot be safely used
  374. // again. Do not include it in our reuse map.
  375. //
  376. p.close();
  377. continue;
  378. }
  379. final PackFile prior = forReuse.put(p.getPackFile().getName(), p);
  380. if (prior != null) {
  381. // This should never occur. It should be impossible for us
  382. // to have two pack files with the same name, as all of them
  383. // came out of the same directory. If it does, we promised to
  384. // close any PackFiles we did not reuse, so close the second,
  385. // readers are likely to be actively using the first.
  386. //
  387. forReuse.put(prior.getPackFile().getName(), prior);
  388. p.close();
  389. }
  390. }
  391. return forReuse;
  392. }
  393. private Set<String> listPackDirectory() {
  394. final String[] nameList = packDirectory.list();
  395. if (nameList == null)
  396. return Collections.emptySet();
  397. final Set<String> nameSet = new HashSet<String>(nameList.length << 1);
  398. for (final String name : nameList) {
  399. if (name.startsWith("pack-"))
  400. nameSet.add(name);
  401. }
  402. return nameSet;
  403. }
  404. @Override
  405. protected ObjectDatabase[] loadAlternates() throws IOException {
  406. final List<ObjectDatabase> l = new ArrayList<ObjectDatabase>(4);
  407. if (alternateObjectDir != null) {
  408. for (File d : alternateObjectDir) {
  409. l.add(openAlternate(d));
  410. }
  411. } else {
  412. final BufferedReader br = open(alternatesFile);
  413. try {
  414. String line;
  415. while ((line = br.readLine()) != null) {
  416. l.add(openAlternate(line));
  417. }
  418. } finally {
  419. br.close();
  420. }
  421. }
  422. if (l.isEmpty()) {
  423. return NO_ALTERNATES;
  424. }
  425. return l.toArray(new ObjectDatabase[l.size()]);
  426. }
  427. private static BufferedReader open(final File f)
  428. throws FileNotFoundException {
  429. return new BufferedReader(new FileReader(f));
  430. }
  431. private ObjectDatabase openAlternate(final String location)
  432. throws IOException {
  433. final File objdir = FS.resolve(objects, location);
  434. return openAlternate(objdir);
  435. }
  436. private ObjectDatabase openAlternate(File objdir) throws IOException {
  437. final File parent = objdir.getParentFile();
  438. if (FileKey.isGitRepository(parent)) {
  439. final Repository db = RepositoryCache.open(FileKey.exact(parent));
  440. return new AlternateRepositoryDatabase(db);
  441. }
  442. return new ObjectDirectory(objdir, null);
  443. }
  444. private static final class PackList {
  445. /** Last wall-clock time the directory was read. */
  446. volatile long lastRead;
  447. /** Last modification time of {@link ObjectDirectory#packDirectory}. */
  448. final long lastModified;
  449. /** All known packs, sorted by {@link PackFile#SORT}. */
  450. final PackFile[] packs;
  451. private boolean cannotBeRacilyClean;
  452. PackList(final long lastRead, final long lastModified,
  453. final PackFile[] packs) {
  454. this.lastRead = lastRead;
  455. this.lastModified = lastModified;
  456. this.packs = packs;
  457. this.cannotBeRacilyClean = notRacyClean(lastRead);
  458. }
  459. private boolean notRacyClean(final long read) {
  460. return read - lastModified > 2 * 60 * 1000L;
  461. }
  462. PackList updateLastRead(final long now) {
  463. if (notRacyClean(now))
  464. cannotBeRacilyClean = true;
  465. lastRead = now;
  466. return this;
  467. }
  468. boolean tryAgain(final long currLastModified) {
  469. // Any difference indicates the directory was modified.
  470. //
  471. if (lastModified != currLastModified)
  472. return true;
  473. // We have already determined the last read was far enough
  474. // after the last modification that any new modifications
  475. // are certain to change the last modified time.
  476. //
  477. if (cannotBeRacilyClean)
  478. return false;
  479. if (notRacyClean(lastRead)) {
  480. // Our last read should have marked cannotBeRacilyClean,
  481. // but this thread may not have seen the change. The read
  482. // of the volatile field lastRead should have fixed that.
  483. //
  484. return false;
  485. }
  486. // We last read this directory too close to its last observed
  487. // modification time. We may have missed a modification. Scan
  488. // the directory again, to ensure we still see the same state.
  489. //
  490. return true;
  491. }
  492. }
  493. @Override
  494. public ObjectDatabase newCachedDatabase() {
  495. return new CachedObjectDirectory(this);
  496. }
  497. }