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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010
  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.internal.storage.file;
  44. import static org.eclipse.jgit.internal.storage.pack.PackExt.INDEX;
  45. import static org.eclipse.jgit.internal.storage.pack.PackExt.PACK;
  46. import java.io.BufferedReader;
  47. import java.io.File;
  48. import java.io.FileInputStream;
  49. import java.io.FileNotFoundException;
  50. import java.io.FileReader;
  51. import java.io.IOException;
  52. import java.nio.file.AtomicMoveNotSupportedException;
  53. import java.nio.file.Files;
  54. import java.nio.file.StandardCopyOption;
  55. import java.text.MessageFormat;
  56. import java.util.ArrayList;
  57. import java.util.Arrays;
  58. import java.util.Collection;
  59. import java.util.Collections;
  60. import java.util.HashMap;
  61. import java.util.HashSet;
  62. import java.util.List;
  63. import java.util.Map;
  64. import java.util.Set;
  65. import java.util.concurrent.atomic.AtomicReference;
  66. import org.eclipse.jgit.errors.CorruptObjectException;
  67. import org.eclipse.jgit.errors.PackInvalidException;
  68. import org.eclipse.jgit.errors.PackMismatchException;
  69. import org.eclipse.jgit.internal.JGitText;
  70. import org.eclipse.jgit.internal.storage.pack.ObjectToPack;
  71. import org.eclipse.jgit.internal.storage.pack.PackExt;
  72. import org.eclipse.jgit.internal.storage.pack.PackWriter;
  73. import org.eclipse.jgit.lib.AbbreviatedObjectId;
  74. import org.eclipse.jgit.lib.AnyObjectId;
  75. import org.eclipse.jgit.lib.Config;
  76. import org.eclipse.jgit.lib.ConfigConstants;
  77. import org.eclipse.jgit.lib.Constants;
  78. import org.eclipse.jgit.lib.ObjectDatabase;
  79. import org.eclipse.jgit.lib.ObjectId;
  80. import org.eclipse.jgit.lib.ObjectLoader;
  81. import org.eclipse.jgit.lib.RepositoryCache;
  82. import org.eclipse.jgit.lib.RepositoryCache.FileKey;
  83. import org.eclipse.jgit.util.FS;
  84. import org.eclipse.jgit.util.FileUtils;
  85. import org.slf4j.Logger;
  86. import org.slf4j.LoggerFactory;
  87. /**
  88. * Traditional file system based {@link ObjectDatabase}.
  89. * <p>
  90. * This is the classical object database representation for a Git repository,
  91. * where objects are stored loose by hashing them into directories by their
  92. * {@link ObjectId}, or are stored in compressed containers known as
  93. * {@link PackFile}s.
  94. * <p>
  95. * Optionally an object database can reference one or more alternates; other
  96. * ObjectDatabase instances that are searched in addition to the current
  97. * database.
  98. * <p>
  99. * Databases are divided into two halves: a half that is considered to be fast
  100. * to search (the {@code PackFile}s), and a half that is considered to be slow
  101. * to search (loose objects). When alternates are present the fast half is fully
  102. * searched (recursively through all alternates) before the slow half is
  103. * considered.
  104. */
  105. public class ObjectDirectory extends FileObjectDatabase {
  106. private final static Logger LOG = LoggerFactory
  107. .getLogger(ObjectDirectory.class);
  108. private static final PackList NO_PACKS = new PackList(
  109. FileSnapshot.DIRTY, new PackFile[0]);
  110. /** Maximum number of candidates offered as resolutions of abbreviation. */
  111. private static final int RESOLVE_ABBREV_LIMIT = 256;
  112. private final Config config;
  113. private final File objects;
  114. private final File infoDirectory;
  115. private final File packDirectory;
  116. private final File alternatesFile;
  117. private final FS fs;
  118. private final AtomicReference<AlternateHandle[]> alternates;
  119. private final UnpackedObjectCache unpackedObjectCache;
  120. private final File shallowFile;
  121. private FileSnapshot shallowFileSnapshot = FileSnapshot.DIRTY;
  122. private Set<ObjectId> shallowCommitsIds;
  123. final AtomicReference<PackList> packList;
  124. /**
  125. * Initialize a reference to an on-disk object directory.
  126. *
  127. * @param cfg
  128. * configuration this directory consults for write settings.
  129. * @param dir
  130. * the location of the <code>objects</code> directory.
  131. * @param alternatePaths
  132. * a list of alternate object directories
  133. * @param fs
  134. * the file system abstraction which will be necessary to perform
  135. * certain file system operations.
  136. * @param shallowFile
  137. * file which contains IDs of shallow commits, null if shallow
  138. * commits handling should be turned off
  139. * @throws IOException
  140. * an alternate object cannot be opened.
  141. */
  142. public ObjectDirectory(final Config cfg, final File dir,
  143. File[] alternatePaths, FS fs, File shallowFile) throws IOException {
  144. config = cfg;
  145. objects = dir;
  146. infoDirectory = new File(objects, "info"); //$NON-NLS-1$
  147. packDirectory = new File(objects, "pack"); //$NON-NLS-1$
  148. alternatesFile = new File(infoDirectory, "alternates"); //$NON-NLS-1$
  149. packList = new AtomicReference<PackList>(NO_PACKS);
  150. unpackedObjectCache = new UnpackedObjectCache();
  151. this.fs = fs;
  152. this.shallowFile = shallowFile;
  153. alternates = new AtomicReference<AlternateHandle[]>();
  154. if (alternatePaths != null) {
  155. AlternateHandle[] alt;
  156. alt = new AlternateHandle[alternatePaths.length];
  157. for (int i = 0; i < alternatePaths.length; i++)
  158. alt[i] = openAlternate(alternatePaths[i]);
  159. alternates.set(alt);
  160. }
  161. }
  162. /**
  163. * @return the location of the <code>objects</code> directory.
  164. */
  165. public final File getDirectory() {
  166. return objects;
  167. }
  168. @Override
  169. public boolean exists() {
  170. return fs.exists(objects);
  171. }
  172. @Override
  173. public void create() throws IOException {
  174. FileUtils.mkdirs(objects);
  175. FileUtils.mkdir(infoDirectory);
  176. FileUtils.mkdir(packDirectory);
  177. }
  178. @Override
  179. public ObjectDirectoryInserter newInserter() {
  180. return new ObjectDirectoryInserter(this, config);
  181. }
  182. @Override
  183. public void close() {
  184. unpackedObjectCache.clear();
  185. final PackList packs = packList.get();
  186. if (packs != NO_PACKS && packList.compareAndSet(packs, NO_PACKS)) {
  187. for (PackFile p : packs.packs)
  188. p.close();
  189. }
  190. // Fully close all loaded alternates and clear the alternate list.
  191. AlternateHandle[] alt = alternates.get();
  192. if (alt != null && alternates.compareAndSet(alt, null)) {
  193. for(final AlternateHandle od : alt)
  194. od.close();
  195. }
  196. }
  197. /**
  198. * @return unmodifiable collection of all known pack files local to this
  199. * directory. Most recent packs are presented first. Packs most
  200. * likely to contain more recent objects appear before packs
  201. * containing objects referenced by commits further back in the
  202. * history of the repository.
  203. */
  204. @Override
  205. public Collection<PackFile> getPacks() {
  206. PackList list = packList.get();
  207. if (list == NO_PACKS)
  208. list = scanPacks(list);
  209. PackFile[] packs = list.packs;
  210. return Collections.unmodifiableCollection(Arrays.asList(packs));
  211. }
  212. /**
  213. * Add a single existing pack to the list of available pack files.
  214. *
  215. * @param pack
  216. * path of the pack file to open.
  217. * @return the pack that was opened and added to the database.
  218. * @throws IOException
  219. * index file could not be opened, read, or is not recognized as
  220. * a Git pack file index.
  221. */
  222. public PackFile openPack(final File pack)
  223. throws IOException {
  224. final String p = pack.getName();
  225. if (p.length() != 50 || !p.startsWith("pack-") || !p.endsWith(".pack")) //$NON-NLS-1$ //$NON-NLS-2$
  226. throw new IOException(MessageFormat.format(JGitText.get().notAValidPack, pack));
  227. // The pack and index are assumed to exist. The existence of other
  228. // extensions needs to be explicitly checked.
  229. //
  230. int extensions = PACK.getBit() | INDEX.getBit();
  231. final String base = p.substring(0, p.length() - 4);
  232. for (PackExt ext : PackExt.values()) {
  233. if ((extensions & ext.getBit()) == 0) {
  234. final String name = base + ext.getExtension();
  235. if (new File(pack.getParentFile(), name).exists())
  236. extensions |= ext.getBit();
  237. }
  238. }
  239. PackFile res = new PackFile(pack, extensions);
  240. insertPack(res);
  241. return res;
  242. }
  243. @Override
  244. public String toString() {
  245. return "ObjectDirectory[" + getDirectory() + "]"; //$NON-NLS-1$ //$NON-NLS-2$
  246. }
  247. @Override
  248. public boolean has(AnyObjectId objectId) {
  249. return unpackedObjectCache.isUnpacked(objectId)
  250. || hasPackedInSelfOrAlternate(objectId)
  251. || hasLooseInSelfOrAlternate(objectId);
  252. }
  253. private boolean hasPackedInSelfOrAlternate(AnyObjectId objectId) {
  254. if (hasPackedObject(objectId))
  255. return true;
  256. for (AlternateHandle alt : myAlternates()) {
  257. if (alt.db.hasPackedInSelfOrAlternate(objectId))
  258. return true;
  259. }
  260. return false;
  261. }
  262. private boolean hasLooseInSelfOrAlternate(AnyObjectId objectId) {
  263. if (fileFor(objectId).exists())
  264. return true;
  265. for (AlternateHandle alt : myAlternates()) {
  266. if (alt.db.hasLooseInSelfOrAlternate(objectId))
  267. return true;
  268. }
  269. return false;
  270. }
  271. boolean hasPackedObject(AnyObjectId objectId) {
  272. PackList pList;
  273. do {
  274. pList = packList.get();
  275. for (PackFile p : pList.packs) {
  276. try {
  277. if (p.hasObject(objectId))
  278. return true;
  279. } catch (IOException e) {
  280. // The hasObject call should have only touched the index,
  281. // so any failure here indicates the index is unreadable
  282. // by this process, and the pack is likewise not readable.
  283. removePack(p);
  284. }
  285. }
  286. } while (searchPacksAgain(pList));
  287. return false;
  288. }
  289. @Override
  290. void resolve(Set<ObjectId> matches, AbbreviatedObjectId id)
  291. throws IOException {
  292. // Go through the packs once. If we didn't find any resolutions
  293. // scan for new packs and check once more.
  294. int oldSize = matches.size();
  295. PackList pList;
  296. do {
  297. pList = packList.get();
  298. for (PackFile p : pList.packs) {
  299. try {
  300. p.resolve(matches, id, RESOLVE_ABBREV_LIMIT);
  301. p.resetTransientErrorCount();
  302. } catch (IOException e) {
  303. handlePackError(e, p);
  304. }
  305. if (matches.size() > RESOLVE_ABBREV_LIMIT)
  306. return;
  307. }
  308. } while (matches.size() == oldSize && searchPacksAgain(pList));
  309. String fanOut = id.name().substring(0, 2);
  310. String[] entries = new File(getDirectory(), fanOut).list();
  311. if (entries != null) {
  312. for (String e : entries) {
  313. if (e.length() != Constants.OBJECT_ID_STRING_LENGTH - 2)
  314. continue;
  315. try {
  316. ObjectId entId = ObjectId.fromString(fanOut + e);
  317. if (id.prefixCompare(entId) == 0)
  318. matches.add(entId);
  319. } catch (IllegalArgumentException notId) {
  320. continue;
  321. }
  322. if (matches.size() > RESOLVE_ABBREV_LIMIT)
  323. return;
  324. }
  325. }
  326. for (AlternateHandle alt : myAlternates()) {
  327. alt.db.resolve(matches, id);
  328. if (matches.size() > RESOLVE_ABBREV_LIMIT)
  329. return;
  330. }
  331. }
  332. @Override
  333. ObjectLoader openObject(WindowCursor curs, AnyObjectId objectId)
  334. throws IOException {
  335. if (unpackedObjectCache.isUnpacked(objectId)) {
  336. ObjectLoader ldr = openLooseObject(curs, objectId);
  337. if (ldr != null)
  338. return ldr;
  339. }
  340. ObjectLoader ldr = openPackedFromSelfOrAlternate(curs, objectId);
  341. if (ldr != null)
  342. return ldr;
  343. return openLooseFromSelfOrAlternate(curs, objectId);
  344. }
  345. private ObjectLoader openPackedFromSelfOrAlternate(WindowCursor curs,
  346. AnyObjectId objectId) {
  347. ObjectLoader ldr = openPackedObject(curs, objectId);
  348. if (ldr != null)
  349. return ldr;
  350. for (AlternateHandle alt : myAlternates()) {
  351. ldr = alt.db.openPackedFromSelfOrAlternate(curs, objectId);
  352. if (ldr != null)
  353. return ldr;
  354. }
  355. return null;
  356. }
  357. private ObjectLoader openLooseFromSelfOrAlternate(WindowCursor curs,
  358. AnyObjectId objectId) throws IOException {
  359. ObjectLoader ldr = openLooseObject(curs, objectId);
  360. if (ldr != null)
  361. return ldr;
  362. for (AlternateHandle alt : myAlternates()) {
  363. ldr = alt.db.openLooseFromSelfOrAlternate(curs, objectId);
  364. if (ldr != null)
  365. return ldr;
  366. }
  367. return null;
  368. }
  369. ObjectLoader openPackedObject(WindowCursor curs, AnyObjectId objectId) {
  370. PackList pList;
  371. do {
  372. SEARCH: for (;;) {
  373. pList = packList.get();
  374. for (PackFile p : pList.packs) {
  375. try {
  376. ObjectLoader ldr = p.get(curs, objectId);
  377. p.resetTransientErrorCount();
  378. if (ldr != null)
  379. return ldr;
  380. } catch (PackMismatchException e) {
  381. // Pack was modified; refresh the entire pack list.
  382. if (searchPacksAgain(pList))
  383. continue SEARCH;
  384. } catch (IOException e) {
  385. handlePackError(e, p);
  386. }
  387. }
  388. break SEARCH;
  389. }
  390. } while (searchPacksAgain(pList));
  391. return null;
  392. }
  393. ObjectLoader openLooseObject(WindowCursor curs, AnyObjectId id)
  394. throws IOException {
  395. File path = fileFor(id);
  396. try (FileInputStream in = new FileInputStream(path)) {
  397. unpackedObjectCache.add(id);
  398. return UnpackedObject.open(in, path, id, curs);
  399. } catch (FileNotFoundException noFile) {
  400. if (path.exists()) {
  401. throw noFile;
  402. }
  403. unpackedObjectCache.remove(id);
  404. return null;
  405. }
  406. }
  407. long getObjectSize(WindowCursor curs, AnyObjectId id)
  408. throws IOException {
  409. if (unpackedObjectCache.isUnpacked(id)) {
  410. long len = getLooseObjectSize(curs, id);
  411. if (0 <= len)
  412. return len;
  413. }
  414. long len = getPackedSizeFromSelfOrAlternate(curs, id);
  415. if (0 <= len)
  416. return len;
  417. return getLooseSizeFromSelfOrAlternate(curs, id);
  418. }
  419. private long getPackedSizeFromSelfOrAlternate(WindowCursor curs,
  420. AnyObjectId id) {
  421. long len = getPackedObjectSize(curs, id);
  422. if (0 <= len)
  423. return len;
  424. for (AlternateHandle alt : myAlternates()) {
  425. len = alt.db.getPackedSizeFromSelfOrAlternate(curs, id);
  426. if (0 <= len)
  427. return len;
  428. }
  429. return -1;
  430. }
  431. private long getLooseSizeFromSelfOrAlternate(WindowCursor curs,
  432. AnyObjectId id) throws IOException {
  433. long len = getLooseObjectSize(curs, id);
  434. if (0 <= len)
  435. return len;
  436. for (AlternateHandle alt : myAlternates()) {
  437. len = alt.db.getLooseSizeFromSelfOrAlternate(curs, id);
  438. if (0 <= len)
  439. return len;
  440. }
  441. return -1;
  442. }
  443. private long getPackedObjectSize(WindowCursor curs, AnyObjectId id) {
  444. PackList pList;
  445. do {
  446. SEARCH: for (;;) {
  447. pList = packList.get();
  448. for (PackFile p : pList.packs) {
  449. try {
  450. long len = p.getObjectSize(curs, id);
  451. p.resetTransientErrorCount();
  452. if (0 <= len)
  453. return len;
  454. } catch (PackMismatchException e) {
  455. // Pack was modified; refresh the entire pack list.
  456. if (searchPacksAgain(pList))
  457. continue SEARCH;
  458. } catch (IOException e) {
  459. handlePackError(e, p);
  460. }
  461. }
  462. break SEARCH;
  463. }
  464. } while (searchPacksAgain(pList));
  465. return -1;
  466. }
  467. private long getLooseObjectSize(WindowCursor curs, AnyObjectId id)
  468. throws IOException {
  469. File f = fileFor(id);
  470. try (FileInputStream in = new FileInputStream(f)) {
  471. unpackedObjectCache.add(id);
  472. return UnpackedObject.getSize(in, id, curs);
  473. } catch (FileNotFoundException noFile) {
  474. if (f.exists()) {
  475. throw noFile;
  476. }
  477. unpackedObjectCache.remove(id);
  478. return -1;
  479. }
  480. }
  481. @Override
  482. void selectObjectRepresentation(PackWriter packer, ObjectToPack otp,
  483. WindowCursor curs) throws IOException {
  484. PackList pList = packList.get();
  485. SEARCH: for (;;) {
  486. for (final PackFile p : pList.packs) {
  487. try {
  488. LocalObjectRepresentation rep = p.representation(curs, otp);
  489. p.resetTransientErrorCount();
  490. if (rep != null)
  491. packer.select(otp, rep);
  492. } catch (PackMismatchException e) {
  493. // Pack was modified; refresh the entire pack list.
  494. //
  495. pList = scanPacks(pList);
  496. continue SEARCH;
  497. } catch (IOException e) {
  498. handlePackError(e, p);
  499. }
  500. }
  501. break SEARCH;
  502. }
  503. for (AlternateHandle h : myAlternates())
  504. h.db.selectObjectRepresentation(packer, otp, curs);
  505. }
  506. private void handlePackError(IOException e, PackFile p) {
  507. String warnTmpl = null;
  508. int transientErrorCount = 0;
  509. String errTmpl = JGitText.get().exceptionWhileReadingPack;
  510. if ((e instanceof CorruptObjectException)
  511. || (e instanceof PackInvalidException)) {
  512. warnTmpl = JGitText.get().corruptPack;
  513. // Assume the pack is corrupted, and remove it from the list.
  514. removePack(p);
  515. } else if (e instanceof FileNotFoundException) {
  516. if (p.getPackFile().exists()) {
  517. errTmpl = JGitText.get().packInaccessible;
  518. transientErrorCount = p.incrementTransientErrorCount();
  519. } else {
  520. warnTmpl = JGitText.get().packWasDeleted;
  521. removePack(p);
  522. }
  523. } else if (FileUtils.isStaleFileHandle(e)) {
  524. warnTmpl = JGitText.get().packHandleIsStale;
  525. removePack(p);
  526. } else {
  527. transientErrorCount = p.incrementTransientErrorCount();
  528. }
  529. if (warnTmpl != null) {
  530. if (LOG.isDebugEnabled()) {
  531. LOG.debug(MessageFormat.format(warnTmpl,
  532. p.getPackFile().getAbsolutePath()), e);
  533. } else {
  534. LOG.warn(MessageFormat.format(warnTmpl,
  535. p.getPackFile().getAbsolutePath()));
  536. }
  537. } else {
  538. if (doLogExponentialBackoff(transientErrorCount)) {
  539. // Don't remove the pack from the list, as the error may be
  540. // transient.
  541. LOG.error(MessageFormat.format(errTmpl,
  542. p.getPackFile().getAbsolutePath()),
  543. Integer.valueOf(transientErrorCount), e);
  544. }
  545. }
  546. }
  547. /**
  548. * @param n
  549. * count of consecutive failures
  550. * @return @{code true} if i is a power of 2
  551. */
  552. private boolean doLogExponentialBackoff(int n) {
  553. return (n & (n - 1)) == 0;
  554. }
  555. @Override
  556. InsertLooseObjectResult insertUnpackedObject(File tmp, ObjectId id,
  557. boolean createDuplicate) throws IOException {
  558. // If the object is already in the repository, remove temporary file.
  559. //
  560. if (unpackedObjectCache.isUnpacked(id)) {
  561. FileUtils.delete(tmp, FileUtils.RETRY);
  562. return InsertLooseObjectResult.EXISTS_LOOSE;
  563. }
  564. if (!createDuplicate && has(id)) {
  565. FileUtils.delete(tmp, FileUtils.RETRY);
  566. return InsertLooseObjectResult.EXISTS_PACKED;
  567. }
  568. final File dst = fileFor(id);
  569. if (dst.exists()) {
  570. // We want to be extra careful and avoid replacing an object
  571. // that already exists. We can't be sure renameTo() would
  572. // fail on all platforms if dst exists, so we check first.
  573. //
  574. FileUtils.delete(tmp, FileUtils.RETRY);
  575. return InsertLooseObjectResult.EXISTS_LOOSE;
  576. }
  577. try {
  578. Files.move(tmp.toPath(), dst.toPath(),
  579. StandardCopyOption.ATOMIC_MOVE);
  580. dst.setReadOnly();
  581. unpackedObjectCache.add(id);
  582. return InsertLooseObjectResult.INSERTED;
  583. } catch (AtomicMoveNotSupportedException e) {
  584. LOG.error(e.getMessage(), e);
  585. } catch (IOException e) {
  586. // ignore
  587. }
  588. // Maybe the directory doesn't exist yet as the object
  589. // directories are always lazily created. Note that we
  590. // try the rename first as the directory likely does exist.
  591. //
  592. FileUtils.mkdir(dst.getParentFile(), true);
  593. try {
  594. Files.move(tmp.toPath(), dst.toPath(),
  595. StandardCopyOption.ATOMIC_MOVE);
  596. dst.setReadOnly();
  597. unpackedObjectCache.add(id);
  598. return InsertLooseObjectResult.INSERTED;
  599. } catch (AtomicMoveNotSupportedException e) {
  600. LOG.error(e.getMessage(), e);
  601. } catch (IOException e) {
  602. LOG.debug(e.getMessage(), e);
  603. }
  604. if (!createDuplicate && has(id)) {
  605. FileUtils.delete(tmp, FileUtils.RETRY);
  606. return InsertLooseObjectResult.EXISTS_PACKED;
  607. }
  608. // The object failed to be renamed into its proper
  609. // location and it doesn't exist in the repository
  610. // either. We really don't know what went wrong, so
  611. // fail.
  612. //
  613. FileUtils.delete(tmp, FileUtils.RETRY);
  614. return InsertLooseObjectResult.FAILURE;
  615. }
  616. boolean searchPacksAgain(PackList old) {
  617. // Whether to trust the pack folder's modification time. If set
  618. // to false we will always scan the .git/objects/pack folder to
  619. // check for new pack files. If set to true (default) we use the
  620. // lastmodified attribute of the folder and assume that no new
  621. // pack files can be in this folder if his modification time has
  622. // not changed.
  623. boolean trustFolderStat = config.getBoolean(
  624. ConfigConstants.CONFIG_CORE_SECTION,
  625. ConfigConstants.CONFIG_KEY_TRUSTFOLDERSTAT, true);
  626. return ((!trustFolderStat) || old.snapshot.isModified(packDirectory))
  627. && old != scanPacks(old);
  628. }
  629. Config getConfig() {
  630. return config;
  631. }
  632. @Override
  633. FS getFS() {
  634. return fs;
  635. }
  636. @Override
  637. Set<ObjectId> getShallowCommits() throws IOException {
  638. if (shallowFile == null || !shallowFile.isFile())
  639. return Collections.emptySet();
  640. if (shallowFileSnapshot == null
  641. || shallowFileSnapshot.isModified(shallowFile)) {
  642. shallowCommitsIds = new HashSet<ObjectId>();
  643. final BufferedReader reader = open(shallowFile);
  644. try {
  645. String line;
  646. while ((line = reader.readLine()) != null)
  647. shallowCommitsIds.add(ObjectId.fromString(line));
  648. } finally {
  649. reader.close();
  650. }
  651. shallowFileSnapshot = FileSnapshot.save(shallowFile);
  652. }
  653. return shallowCommitsIds;
  654. }
  655. private void insertPack(final PackFile pf) {
  656. PackList o, n;
  657. do {
  658. o = packList.get();
  659. // If the pack in question is already present in the list
  660. // (picked up by a concurrent thread that did a scan?) we
  661. // do not want to insert it a second time.
  662. //
  663. final PackFile[] oldList = o.packs;
  664. final String name = pf.getPackFile().getName();
  665. for (PackFile p : oldList) {
  666. if (PackFile.SORT.compare(pf, p) < 0)
  667. break;
  668. if (name.equals(p.getPackFile().getName()))
  669. return;
  670. }
  671. final PackFile[] newList = new PackFile[1 + oldList.length];
  672. newList[0] = pf;
  673. System.arraycopy(oldList, 0, newList, 1, oldList.length);
  674. n = new PackList(o.snapshot, newList);
  675. } while (!packList.compareAndSet(o, n));
  676. }
  677. private void removePack(final PackFile deadPack) {
  678. PackList o, n;
  679. do {
  680. o = packList.get();
  681. final PackFile[] oldList = o.packs;
  682. final int j = indexOf(oldList, deadPack);
  683. if (j < 0)
  684. break;
  685. final PackFile[] newList = new PackFile[oldList.length - 1];
  686. System.arraycopy(oldList, 0, newList, 0, j);
  687. System.arraycopy(oldList, j + 1, newList, j, newList.length - j);
  688. n = new PackList(o.snapshot, newList);
  689. } while (!packList.compareAndSet(o, n));
  690. deadPack.close();
  691. }
  692. private static int indexOf(final PackFile[] list, final PackFile pack) {
  693. for (int i = 0; i < list.length; i++) {
  694. if (list[i] == pack)
  695. return i;
  696. }
  697. return -1;
  698. }
  699. private PackList scanPacks(final PackList original) {
  700. synchronized (packList) {
  701. PackList o, n;
  702. do {
  703. o = packList.get();
  704. if (o != original) {
  705. // Another thread did the scan for us, while we
  706. // were blocked on the monitor above.
  707. //
  708. return o;
  709. }
  710. n = scanPacksImpl(o);
  711. if (n == o)
  712. return n;
  713. } while (!packList.compareAndSet(o, n));
  714. return n;
  715. }
  716. }
  717. private PackList scanPacksImpl(final PackList old) {
  718. final Map<String, PackFile> forReuse = reuseMap(old);
  719. final FileSnapshot snapshot = FileSnapshot.save(packDirectory);
  720. final Set<String> names = listPackDirectory();
  721. final List<PackFile> list = new ArrayList<PackFile>(names.size() >> 2);
  722. boolean foundNew = false;
  723. for (final String indexName : names) {
  724. // Must match "pack-[0-9a-f]{40}.idx" to be an index.
  725. //
  726. if (indexName.length() != 49 || !indexName.endsWith(".idx")) //$NON-NLS-1$
  727. continue;
  728. final String base = indexName.substring(0, indexName.length() - 3);
  729. int extensions = 0;
  730. for (PackExt ext : PackExt.values()) {
  731. if (names.contains(base + ext.getExtension()))
  732. extensions |= ext.getBit();
  733. }
  734. if ((extensions & PACK.getBit()) == 0) {
  735. // Sometimes C Git's HTTP fetch transport leaves a
  736. // .idx file behind and does not download the .pack.
  737. // We have to skip over such useless indexes.
  738. //
  739. continue;
  740. }
  741. final String packName = base + PACK.getExtension();
  742. final File packFile = new File(packDirectory, packName);
  743. final PackFile oldPack = forReuse.remove(packName);
  744. if (oldPack != null
  745. && !oldPack.getFileSnapshot().isModified(packFile)) {
  746. list.add(oldPack);
  747. continue;
  748. }
  749. list.add(new PackFile(packFile, extensions));
  750. foundNew = true;
  751. }
  752. // If we did not discover any new files, the modification time was not
  753. // changed, and we did not remove any files, then the set of files is
  754. // the same as the set we were given. Instead of building a new object
  755. // return the same collection.
  756. //
  757. if (!foundNew && forReuse.isEmpty() && snapshot.equals(old.snapshot)) {
  758. old.snapshot.setClean(snapshot);
  759. return old;
  760. }
  761. for (final PackFile p : forReuse.values()) {
  762. p.close();
  763. }
  764. if (list.isEmpty())
  765. return new PackList(snapshot, NO_PACKS.packs);
  766. final PackFile[] r = list.toArray(new PackFile[list.size()]);
  767. Arrays.sort(r, PackFile.SORT);
  768. return new PackList(snapshot, r);
  769. }
  770. private static Map<String, PackFile> reuseMap(final PackList old) {
  771. final Map<String, PackFile> forReuse = new HashMap<String, PackFile>();
  772. for (final PackFile p : old.packs) {
  773. if (p.invalid()) {
  774. // The pack instance is corrupted, and cannot be safely used
  775. // again. Do not include it in our reuse map.
  776. //
  777. p.close();
  778. continue;
  779. }
  780. final PackFile prior = forReuse.put(p.getPackFile().getName(), p);
  781. if (prior != null) {
  782. // This should never occur. It should be impossible for us
  783. // to have two pack files with the same name, as all of them
  784. // came out of the same directory. If it does, we promised to
  785. // close any PackFiles we did not reuse, so close the second,
  786. // readers are likely to be actively using the first.
  787. //
  788. forReuse.put(prior.getPackFile().getName(), prior);
  789. p.close();
  790. }
  791. }
  792. return forReuse;
  793. }
  794. private Set<String> listPackDirectory() {
  795. final String[] nameList = packDirectory.list();
  796. if (nameList == null)
  797. return Collections.emptySet();
  798. final Set<String> nameSet = new HashSet<String>(nameList.length << 1);
  799. for (final String name : nameList) {
  800. if (name.startsWith("pack-")) //$NON-NLS-1$
  801. nameSet.add(name);
  802. }
  803. return nameSet;
  804. }
  805. AlternateHandle[] myAlternates() {
  806. AlternateHandle[] alt = alternates.get();
  807. if (alt == null) {
  808. synchronized (alternates) {
  809. alt = alternates.get();
  810. if (alt == null) {
  811. try {
  812. alt = loadAlternates();
  813. } catch (IOException e) {
  814. alt = new AlternateHandle[0];
  815. }
  816. alternates.set(alt);
  817. }
  818. }
  819. }
  820. return alt;
  821. }
  822. private AlternateHandle[] loadAlternates() throws IOException {
  823. final List<AlternateHandle> l = new ArrayList<AlternateHandle>(4);
  824. final BufferedReader br = open(alternatesFile);
  825. try {
  826. String line;
  827. while ((line = br.readLine()) != null) {
  828. l.add(openAlternate(line));
  829. }
  830. } finally {
  831. br.close();
  832. }
  833. return l.toArray(new AlternateHandle[l.size()]);
  834. }
  835. private static BufferedReader open(final File f)
  836. throws FileNotFoundException {
  837. return new BufferedReader(new FileReader(f));
  838. }
  839. private AlternateHandle openAlternate(final String location)
  840. throws IOException {
  841. final File objdir = fs.resolve(objects, location);
  842. return openAlternate(objdir);
  843. }
  844. private AlternateHandle openAlternate(File objdir) throws IOException {
  845. final File parent = objdir.getParentFile();
  846. if (FileKey.isGitRepository(parent, fs)) {
  847. FileKey key = FileKey.exact(parent, fs);
  848. FileRepository db = (FileRepository) RepositoryCache.open(key);
  849. return new AlternateRepository(db);
  850. }
  851. ObjectDirectory db = new ObjectDirectory(config, objdir, null, fs, null);
  852. return new AlternateHandle(db);
  853. }
  854. /**
  855. * Compute the location of a loose object file.
  856. *
  857. * @param objectId
  858. * identity of the loose object to map to the directory.
  859. * @return location of the object, if it were to exist as a loose object.
  860. */
  861. public File fileFor(AnyObjectId objectId) {
  862. String n = objectId.name();
  863. String d = n.substring(0, 2);
  864. String f = n.substring(2);
  865. return new File(new File(getDirectory(), d), f);
  866. }
  867. static final class PackList {
  868. /** State just before reading the pack directory. */
  869. final FileSnapshot snapshot;
  870. /** All known packs, sorted by {@link PackFile#SORT}. */
  871. final PackFile[] packs;
  872. PackList(final FileSnapshot monitor, final PackFile[] packs) {
  873. this.snapshot = monitor;
  874. this.packs = packs;
  875. }
  876. }
  877. static class AlternateHandle {
  878. final ObjectDirectory db;
  879. AlternateHandle(ObjectDirectory db) {
  880. this.db = db;
  881. }
  882. void close() {
  883. db.close();
  884. }
  885. }
  886. static class AlternateRepository extends AlternateHandle {
  887. final FileRepository repository;
  888. AlternateRepository(FileRepository r) {
  889. super(r.getObjectDatabase());
  890. repository = r;
  891. }
  892. void close() {
  893. repository.close();
  894. }
  895. }
  896. @Override
  897. public ObjectDatabase newCachedDatabase() {
  898. return newCachedFileObjectDatabase();
  899. }
  900. CachedObjectDirectory newCachedFileObjectDatabase() {
  901. return new CachedObjectDirectory(this);
  902. }
  903. }