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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804
  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.FileInputStream;
  47. import java.io.FileNotFoundException;
  48. import java.io.FileReader;
  49. import java.io.IOException;
  50. import java.text.MessageFormat;
  51. import java.util.ArrayList;
  52. import java.util.Arrays;
  53. import java.util.Collection;
  54. import java.util.Collections;
  55. import java.util.HashMap;
  56. import java.util.HashSet;
  57. import java.util.List;
  58. import java.util.Map;
  59. import java.util.Set;
  60. import java.util.concurrent.atomic.AtomicReference;
  61. import org.eclipse.jgit.JGitText;
  62. import org.eclipse.jgit.errors.PackMismatchException;
  63. import org.eclipse.jgit.lib.AbbreviatedObjectId;
  64. import org.eclipse.jgit.lib.AnyObjectId;
  65. import org.eclipse.jgit.lib.Config;
  66. import org.eclipse.jgit.lib.Constants;
  67. import org.eclipse.jgit.lib.ObjectDatabase;
  68. import org.eclipse.jgit.lib.ObjectId;
  69. import org.eclipse.jgit.lib.ObjectLoader;
  70. import org.eclipse.jgit.lib.RepositoryCache;
  71. import org.eclipse.jgit.lib.RepositoryCache.FileKey;
  72. import org.eclipse.jgit.storage.pack.ObjectToPack;
  73. import org.eclipse.jgit.storage.pack.PackWriter;
  74. import org.eclipse.jgit.util.FS;
  75. /**
  76. * Traditional file system based {@link ObjectDatabase}.
  77. * <p>
  78. * This is the classical object database representation for a Git repository,
  79. * where objects are stored loose by hashing them into directories by their
  80. * {@link ObjectId}, or are stored in compressed containers known as
  81. * {@link PackFile}s.
  82. * <p>
  83. * Optionally an object database can reference one or more alternates; other
  84. * ObjectDatabase instances that are searched in addition to the current
  85. * database.
  86. * <p>
  87. * Databases are divided into two halves: a half that is considered to be fast
  88. * to search (the {@code PackFile}s), and a half that is considered to be slow
  89. * to search (loose objects). When alternates are present the fast half is fully
  90. * searched (recursively through all alternates) before the slow half is
  91. * considered.
  92. */
  93. public class ObjectDirectory extends FileObjectDatabase {
  94. private static final PackList NO_PACKS = new PackList(-1, -1, new PackFile[0]);
  95. /** Maximum number of candidates offered as resolutions of abbreviation. */
  96. private static final int RESOLVE_ABBREV_LIMIT = 256;
  97. private final Config config;
  98. private final File objects;
  99. private final File infoDirectory;
  100. private final File packDirectory;
  101. private final File alternatesFile;
  102. private final AtomicReference<PackList> packList;
  103. private final FS fs;
  104. private final AtomicReference<AlternateHandle[]> alternates;
  105. private final UnpackedObjectCache unpackedObjectCache;
  106. /**
  107. * Initialize a reference to an on-disk object directory.
  108. *
  109. * @param cfg
  110. * configuration this directory consults for write settings.
  111. * @param dir
  112. * the location of the <code>objects</code> directory.
  113. * @param alternatePaths
  114. * a list of alternate object directories
  115. * @param fs
  116. * the file system abstraction which will be necessary to perform
  117. * certain file system operations.
  118. * @throws IOException
  119. * an alternate object cannot be opened.
  120. */
  121. public ObjectDirectory(final Config cfg, final File dir,
  122. File[] alternatePaths, FS fs) throws IOException {
  123. config = cfg;
  124. objects = dir;
  125. infoDirectory = new File(objects, "info");
  126. packDirectory = new File(objects, "pack");
  127. alternatesFile = new File(infoDirectory, "alternates");
  128. packList = new AtomicReference<PackList>(NO_PACKS);
  129. unpackedObjectCache = new UnpackedObjectCache();
  130. this.fs = fs;
  131. alternates = new AtomicReference<AlternateHandle[]>();
  132. if (alternatePaths != null) {
  133. AlternateHandle[] alt;
  134. alt = new AlternateHandle[alternatePaths.length];
  135. for (int i = 0; i < alternatePaths.length; i++)
  136. alt[i] = openAlternate(alternatePaths[i]);
  137. alternates.set(alt);
  138. }
  139. }
  140. /**
  141. * @return the location of the <code>objects</code> directory.
  142. */
  143. public final File getDirectory() {
  144. return objects;
  145. }
  146. @Override
  147. public boolean exists() {
  148. return objects.exists();
  149. }
  150. @Override
  151. public void create() throws IOException {
  152. objects.mkdirs();
  153. infoDirectory.mkdir();
  154. packDirectory.mkdir();
  155. }
  156. @Override
  157. public ObjectDirectoryInserter newInserter() {
  158. return new ObjectDirectoryInserter(this, config);
  159. }
  160. @Override
  161. public void close() {
  162. unpackedObjectCache.clear();
  163. final PackList packs = packList.get();
  164. packList.set(NO_PACKS);
  165. for (final PackFile p : packs.packs)
  166. p.close();
  167. // Fully close all loaded alternates and clear the alternate list.
  168. AlternateHandle[] alt = alternates.get();
  169. if (alt != null) {
  170. alternates.set(null);
  171. for(final AlternateHandle od : alt)
  172. od.close();
  173. }
  174. }
  175. /**
  176. * Compute the location of a loose object file.
  177. *
  178. * @param objectId
  179. * identity of the loose object to map to the directory.
  180. * @return location of the object, if it were to exist as a loose object.
  181. */
  182. public File fileFor(final AnyObjectId objectId) {
  183. return fileFor(objectId.name());
  184. }
  185. private File fileFor(final String objectName) {
  186. final String d = objectName.substring(0, 2);
  187. final String f = objectName.substring(2);
  188. return new File(new File(objects, d), f);
  189. }
  190. /**
  191. * @return unmodifiable collection of all known pack files local to this
  192. * directory. Most recent packs are presented first. Packs most
  193. * likely to contain more recent objects appear before packs
  194. * containing objects referenced by commits further back in the
  195. * history of the repository.
  196. */
  197. public Collection<PackFile> getPacks() {
  198. final PackFile[] packs = packList.get().packs;
  199. return Collections.unmodifiableCollection(Arrays.asList(packs));
  200. }
  201. /**
  202. * Add a single existing pack to the list of available pack files.
  203. *
  204. * @param pack
  205. * path of the pack file to open.
  206. * @param idx
  207. * path of the corresponding index file.
  208. * @throws IOException
  209. * index file could not be opened, read, or is not recognized as
  210. * a Git pack file index.
  211. */
  212. public void openPack(final File pack, final File idx) throws IOException {
  213. final String p = pack.getName();
  214. final String i = idx.getName();
  215. if (p.length() != 50 || !p.startsWith("pack-") || !p.endsWith(".pack"))
  216. throw new IOException(MessageFormat.format(JGitText.get().notAValidPack, pack));
  217. if (i.length() != 49 || !i.startsWith("pack-") || !i.endsWith(".idx"))
  218. throw new IOException(MessageFormat.format(JGitText.get().notAValidPack, idx));
  219. if (!p.substring(0, 45).equals(i.substring(0, 45)))
  220. throw new IOException(MessageFormat.format(JGitText.get().packDoesNotMatchIndex, pack));
  221. insertPack(new PackFile(idx, pack));
  222. }
  223. @Override
  224. public String toString() {
  225. return "ObjectDirectory[" + getDirectory() + "]";
  226. }
  227. boolean hasObject1(final AnyObjectId objectId) {
  228. if (unpackedObjectCache.isUnpacked(objectId))
  229. return true;
  230. for (final PackFile p : packList.get().packs) {
  231. try {
  232. if (p.hasObject(objectId)) {
  233. return true;
  234. }
  235. } catch (IOException e) {
  236. // The hasObject call should have only touched the index,
  237. // so any failure here indicates the index is unreadable
  238. // by this process, and the pack is likewise not readable.
  239. //
  240. removePack(p);
  241. continue;
  242. }
  243. }
  244. return false;
  245. }
  246. void resolve(Set<ObjectId> matches, AbbreviatedObjectId id)
  247. throws IOException {
  248. // Go through the packs once. If we didn't find any resolutions
  249. // scan for new packs and check once more.
  250. //
  251. int oldSize = matches.size();
  252. PackList pList = packList.get();
  253. for (;;) {
  254. for (PackFile p : pList.packs) {
  255. try {
  256. p.resolve(matches, id, RESOLVE_ABBREV_LIMIT);
  257. } catch (IOException e) {
  258. // Assume the pack is corrupted.
  259. //
  260. removePack(p);
  261. }
  262. if (matches.size() > RESOLVE_ABBREV_LIMIT)
  263. return;
  264. }
  265. if (matches.size() == oldSize) {
  266. PackList nList = scanPacks(pList);
  267. if (nList == pList || nList.packs.length == 0)
  268. break;
  269. pList = nList;
  270. continue;
  271. }
  272. break;
  273. }
  274. String fanOut = id.name().substring(0, 2);
  275. String[] entries = new File(getDirectory(), fanOut).list();
  276. if (entries != null) {
  277. for (String e : entries) {
  278. if (e.length() != Constants.OBJECT_ID_STRING_LENGTH - 2)
  279. continue;
  280. try {
  281. ObjectId entId = ObjectId.fromString(fanOut + e);
  282. if (id.prefixCompare(entId) == 0)
  283. matches.add(entId);
  284. } catch (IllegalArgumentException notId) {
  285. continue;
  286. }
  287. if (matches.size() > RESOLVE_ABBREV_LIMIT)
  288. return;
  289. }
  290. }
  291. for (AlternateHandle alt : myAlternates()) {
  292. alt.db.resolve(matches, id);
  293. if (matches.size() > RESOLVE_ABBREV_LIMIT)
  294. return;
  295. }
  296. }
  297. ObjectLoader openObject1(final WindowCursor curs,
  298. final AnyObjectId objectId) throws IOException {
  299. if (unpackedObjectCache.isUnpacked(objectId)) {
  300. ObjectLoader ldr = openObject2(curs, objectId.name(), objectId);
  301. if (ldr != null)
  302. return ldr;
  303. else
  304. unpackedObjectCache.remove(objectId);
  305. }
  306. PackList pList = packList.get();
  307. SEARCH: for (;;) {
  308. for (final PackFile p : pList.packs) {
  309. try {
  310. final ObjectLoader ldr = p.get(curs, objectId);
  311. if (ldr != null)
  312. return ldr;
  313. } catch (PackMismatchException e) {
  314. // Pack was modified; refresh the entire pack list.
  315. //
  316. pList = scanPacks(pList);
  317. continue SEARCH;
  318. } catch (IOException e) {
  319. // Assume the pack is corrupted.
  320. //
  321. removePack(p);
  322. }
  323. }
  324. return null;
  325. }
  326. }
  327. long getObjectSize1(final WindowCursor curs, final AnyObjectId objectId)
  328. throws IOException {
  329. PackList pList = packList.get();
  330. SEARCH: for (;;) {
  331. for (final PackFile p : pList.packs) {
  332. try {
  333. long sz = p.getObjectSize(curs, objectId);
  334. if (0 <= sz)
  335. return sz;
  336. } catch (PackMismatchException e) {
  337. // Pack was modified; refresh the entire pack list.
  338. //
  339. pList = scanPacks(pList);
  340. continue SEARCH;
  341. } catch (IOException e) {
  342. // Assume the pack is corrupted.
  343. //
  344. removePack(p);
  345. }
  346. }
  347. return -1;
  348. }
  349. }
  350. @Override
  351. long getObjectSize2(WindowCursor curs, String objectName,
  352. AnyObjectId objectId) throws IOException {
  353. try {
  354. File path = fileFor(objectName);
  355. FileInputStream in = new FileInputStream(path);
  356. try {
  357. return UnpackedObject.getSize(in, objectId, curs);
  358. } finally {
  359. in.close();
  360. }
  361. } catch (FileNotFoundException noFile) {
  362. return -1;
  363. }
  364. }
  365. @Override
  366. void selectObjectRepresentation(PackWriter packer, ObjectToPack otp,
  367. WindowCursor curs) throws IOException {
  368. PackList pList = packList.get();
  369. SEARCH: for (;;) {
  370. for (final PackFile p : pList.packs) {
  371. try {
  372. LocalObjectRepresentation rep = p.representation(curs, otp);
  373. if (rep != null)
  374. packer.select(otp, rep);
  375. } catch (PackMismatchException e) {
  376. // Pack was modified; refresh the entire pack list.
  377. //
  378. pList = scanPacks(pList);
  379. continue SEARCH;
  380. } catch (IOException e) {
  381. // Assume the pack is corrupted.
  382. //
  383. removePack(p);
  384. }
  385. }
  386. break SEARCH;
  387. }
  388. for (AlternateHandle h : myAlternates())
  389. h.db.selectObjectRepresentation(packer, otp, curs);
  390. }
  391. boolean hasObject2(final String objectName) {
  392. return fileFor(objectName).exists();
  393. }
  394. ObjectLoader openObject2(final WindowCursor curs,
  395. final String objectName, final AnyObjectId objectId)
  396. throws IOException {
  397. try {
  398. File path = fileFor(objectName);
  399. FileInputStream in = new FileInputStream(path);
  400. try {
  401. unpackedObjectCache.add(objectId);
  402. return UnpackedObject.open(in, path, objectId, curs);
  403. } finally {
  404. in.close();
  405. }
  406. } catch (FileNotFoundException noFile) {
  407. unpackedObjectCache.remove(objectId);
  408. return null;
  409. }
  410. }
  411. @Override
  412. InsertLooseObjectResult insertUnpackedObject(File tmp, ObjectId id,
  413. boolean createDuplicate) {
  414. // If the object is already in the repository, remove temporary file.
  415. //
  416. if (unpackedObjectCache.isUnpacked(id)) {
  417. tmp.delete();
  418. return InsertLooseObjectResult.EXISTS_LOOSE;
  419. }
  420. if (!createDuplicate && has(id)) {
  421. tmp.delete();
  422. return InsertLooseObjectResult.EXISTS_PACKED;
  423. }
  424. tmp.setReadOnly();
  425. final File dst = fileFor(id);
  426. if (dst.exists()) {
  427. // We want to be extra careful and avoid replacing an object
  428. // that already exists. We can't be sure renameTo() would
  429. // fail on all platforms if dst exists, so we check first.
  430. //
  431. tmp.delete();
  432. return InsertLooseObjectResult.EXISTS_LOOSE;
  433. }
  434. if (tmp.renameTo(dst)) {
  435. unpackedObjectCache.add(id);
  436. return InsertLooseObjectResult.INSERTED;
  437. }
  438. // Maybe the directory doesn't exist yet as the object
  439. // directories are always lazily created. Note that we
  440. // try the rename first as the directory likely does exist.
  441. //
  442. dst.getParentFile().mkdir();
  443. if (tmp.renameTo(dst)) {
  444. unpackedObjectCache.add(id);
  445. return InsertLooseObjectResult.INSERTED;
  446. }
  447. if (!createDuplicate && has(id)) {
  448. tmp.delete();
  449. return InsertLooseObjectResult.EXISTS_PACKED;
  450. }
  451. // The object failed to be renamed into its proper
  452. // location and it doesn't exist in the repository
  453. // either. We really don't know what went wrong, so
  454. // fail.
  455. //
  456. tmp.delete();
  457. return InsertLooseObjectResult.FAILURE;
  458. }
  459. boolean tryAgain1() {
  460. final PackList old = packList.get();
  461. if (old.tryAgain(packDirectory.lastModified()))
  462. return old != scanPacks(old);
  463. return false;
  464. }
  465. private void insertPack(final PackFile pf) {
  466. PackList o, n;
  467. do {
  468. o = packList.get();
  469. // If the pack in question is already present in the list
  470. // (picked up by a concurrent thread that did a scan?) we
  471. // do not want to insert it a second time.
  472. //
  473. final PackFile[] oldList = o.packs;
  474. final String name = pf.getPackFile().getName();
  475. for (PackFile p : oldList) {
  476. if (PackFile.SORT.compare(pf, p) < 0)
  477. break;
  478. if (name.equals(p.getPackFile().getName()))
  479. return;
  480. }
  481. final PackFile[] newList = new PackFile[1 + oldList.length];
  482. newList[0] = pf;
  483. System.arraycopy(oldList, 0, newList, 1, oldList.length);
  484. n = new PackList(o.lastRead, o.lastModified, newList);
  485. } while (!packList.compareAndSet(o, n));
  486. }
  487. private void removePack(final PackFile deadPack) {
  488. PackList o, n;
  489. do {
  490. o = packList.get();
  491. final PackFile[] oldList = o.packs;
  492. final int j = indexOf(oldList, deadPack);
  493. if (j < 0)
  494. break;
  495. final PackFile[] newList = new PackFile[oldList.length - 1];
  496. System.arraycopy(oldList, 0, newList, 0, j);
  497. System.arraycopy(oldList, j + 1, newList, j, newList.length - j);
  498. n = new PackList(o.lastRead, o.lastModified, newList);
  499. } while (!packList.compareAndSet(o, n));
  500. deadPack.close();
  501. }
  502. private static int indexOf(final PackFile[] list, final PackFile pack) {
  503. for (int i = 0; i < list.length; i++) {
  504. if (list[i] == pack)
  505. return i;
  506. }
  507. return -1;
  508. }
  509. private PackList scanPacks(final PackList original) {
  510. synchronized (packList) {
  511. PackList o, n;
  512. do {
  513. o = packList.get();
  514. if (o != original) {
  515. // Another thread did the scan for us, while we
  516. // were blocked on the monitor above.
  517. //
  518. return o;
  519. }
  520. n = scanPacksImpl(o);
  521. if (n == o)
  522. return n;
  523. } while (!packList.compareAndSet(o, n));
  524. return n;
  525. }
  526. }
  527. private PackList scanPacksImpl(final PackList old) {
  528. final Map<String, PackFile> forReuse = reuseMap(old);
  529. final long lastRead = System.currentTimeMillis();
  530. final long lastModified = packDirectory.lastModified();
  531. final Set<String> names = listPackDirectory();
  532. final List<PackFile> list = new ArrayList<PackFile>(names.size() >> 2);
  533. boolean foundNew = false;
  534. for (final String indexName : names) {
  535. // Must match "pack-[0-9a-f]{40}.idx" to be an index.
  536. //
  537. if (indexName.length() != 49 || !indexName.endsWith(".idx"))
  538. continue;
  539. final String base = indexName.substring(0, indexName.length() - 4);
  540. final String packName = base + ".pack";
  541. if (!names.contains(packName)) {
  542. // Sometimes C Git's HTTP fetch transport leaves a
  543. // .idx file behind and does not download the .pack.
  544. // We have to skip over such useless indexes.
  545. //
  546. continue;
  547. }
  548. final PackFile oldPack = forReuse.remove(packName);
  549. if (oldPack != null) {
  550. list.add(oldPack);
  551. continue;
  552. }
  553. final File packFile = new File(packDirectory, packName);
  554. final File idxFile = new File(packDirectory, indexName);
  555. list.add(new PackFile(idxFile, packFile));
  556. foundNew = true;
  557. }
  558. // If we did not discover any new files, the modification time was not
  559. // changed, and we did not remove any files, then the set of files is
  560. // the same as the set we were given. Instead of building a new object
  561. // return the same collection.
  562. //
  563. if (!foundNew && lastModified == old.lastModified && forReuse.isEmpty())
  564. return old.updateLastRead(lastRead);
  565. for (final PackFile p : forReuse.values()) {
  566. p.close();
  567. }
  568. if (list.isEmpty())
  569. return new PackList(lastRead, lastModified, NO_PACKS.packs);
  570. final PackFile[] r = list.toArray(new PackFile[list.size()]);
  571. Arrays.sort(r, PackFile.SORT);
  572. return new PackList(lastRead, lastModified, r);
  573. }
  574. private static Map<String, PackFile> reuseMap(final PackList old) {
  575. final Map<String, PackFile> forReuse = new HashMap<String, PackFile>();
  576. for (final PackFile p : old.packs) {
  577. if (p.invalid()) {
  578. // The pack instance is corrupted, and cannot be safely used
  579. // again. Do not include it in our reuse map.
  580. //
  581. p.close();
  582. continue;
  583. }
  584. final PackFile prior = forReuse.put(p.getPackFile().getName(), p);
  585. if (prior != null) {
  586. // This should never occur. It should be impossible for us
  587. // to have two pack files with the same name, as all of them
  588. // came out of the same directory. If it does, we promised to
  589. // close any PackFiles we did not reuse, so close the second,
  590. // readers are likely to be actively using the first.
  591. //
  592. forReuse.put(prior.getPackFile().getName(), prior);
  593. p.close();
  594. }
  595. }
  596. return forReuse;
  597. }
  598. private Set<String> listPackDirectory() {
  599. final String[] nameList = packDirectory.list();
  600. if (nameList == null)
  601. return Collections.emptySet();
  602. final Set<String> nameSet = new HashSet<String>(nameList.length << 1);
  603. for (final String name : nameList) {
  604. if (name.startsWith("pack-"))
  605. nameSet.add(name);
  606. }
  607. return nameSet;
  608. }
  609. AlternateHandle[] myAlternates() {
  610. AlternateHandle[] alt = alternates.get();
  611. if (alt == null) {
  612. synchronized (alternates) {
  613. alt = alternates.get();
  614. if (alt == null) {
  615. try {
  616. alt = loadAlternates();
  617. } catch (IOException e) {
  618. alt = new AlternateHandle[0];
  619. }
  620. alternates.set(alt);
  621. }
  622. }
  623. }
  624. return alt;
  625. }
  626. private AlternateHandle[] loadAlternates() throws IOException {
  627. final List<AlternateHandle> l = new ArrayList<AlternateHandle>(4);
  628. final BufferedReader br = open(alternatesFile);
  629. try {
  630. String line;
  631. while ((line = br.readLine()) != null) {
  632. l.add(openAlternate(line));
  633. }
  634. } finally {
  635. br.close();
  636. }
  637. return l.toArray(new AlternateHandle[l.size()]);
  638. }
  639. private static BufferedReader open(final File f)
  640. throws FileNotFoundException {
  641. return new BufferedReader(new FileReader(f));
  642. }
  643. private AlternateHandle openAlternate(final String location)
  644. throws IOException {
  645. final File objdir = fs.resolve(objects, location);
  646. return openAlternate(objdir);
  647. }
  648. private AlternateHandle openAlternate(File objdir) throws IOException {
  649. final File parent = objdir.getParentFile();
  650. if (FileKey.isGitRepository(parent, fs)) {
  651. FileKey key = FileKey.exact(parent, fs);
  652. FileRepository db = (FileRepository) RepositoryCache.open(key);
  653. return new AlternateRepository(db);
  654. }
  655. ObjectDirectory db = new ObjectDirectory(config, objdir, null, fs);
  656. return new AlternateHandle(db);
  657. }
  658. private static final class PackList {
  659. /** Last wall-clock time the directory was read. */
  660. volatile long lastRead;
  661. /** Last modification time of {@link ObjectDirectory#packDirectory}. */
  662. final long lastModified;
  663. /** All known packs, sorted by {@link PackFile#SORT}. */
  664. final PackFile[] packs;
  665. private boolean cannotBeRacilyClean;
  666. PackList(final long lastRead, final long lastModified,
  667. final PackFile[] packs) {
  668. this.lastRead = lastRead;
  669. this.lastModified = lastModified;
  670. this.packs = packs;
  671. this.cannotBeRacilyClean = notRacyClean(lastRead);
  672. }
  673. private boolean notRacyClean(final long read) {
  674. return read - lastModified > 2 * 60 * 1000L;
  675. }
  676. PackList updateLastRead(final long now) {
  677. if (notRacyClean(now))
  678. cannotBeRacilyClean = true;
  679. lastRead = now;
  680. return this;
  681. }
  682. boolean tryAgain(final long currLastModified) {
  683. // Any difference indicates the directory was modified.
  684. //
  685. if (lastModified != currLastModified)
  686. return true;
  687. // We have already determined the last read was far enough
  688. // after the last modification that any new modifications
  689. // are certain to change the last modified time.
  690. //
  691. if (cannotBeRacilyClean)
  692. return false;
  693. if (notRacyClean(lastRead)) {
  694. // Our last read should have marked cannotBeRacilyClean,
  695. // but this thread may not have seen the change. The read
  696. // of the volatile field lastRead should have fixed that.
  697. //
  698. return false;
  699. }
  700. // We last read this directory too close to its last observed
  701. // modification time. We may have missed a modification. Scan
  702. // the directory again, to ensure we still see the same state.
  703. //
  704. return true;
  705. }
  706. }
  707. @Override
  708. public ObjectDatabase newCachedDatabase() {
  709. return newCachedFileObjectDatabase();
  710. }
  711. FileObjectDatabase newCachedFileObjectDatabase() {
  712. return new CachedObjectDirectory(this);
  713. }
  714. }