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

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