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

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