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

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