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

Added read/write support for pack bitmap index. A pack bitmap index is an additional index of compressed bitmaps of the object graph. Furthermore, a logical API of the index functionality is included, as it is expected to be used by the PackWriter. Compressed bitmaps are created using the javaewah library, which is a word-aligned compressed variant of the Java bitset class based on run-length encoding. The library only works with positive integer values. Thus, the maximum number of ObjectIds in a pack file that this index can currently support is limited to Integer.MAX_VALUE. Every ObjectId is given an integer mapping. The integer is the position of the ObjectId in the complete ObjectId list, sorted by offset, for the pack file. That integer is what the bitmaps use to reference the ObjectId. Currently, the new index format can only be used with pack files that contain a complete closure of the object graph e.g. the result of a garbage collection. The index file includes four bitmaps for the Git object types i.e. commits, trees, blobs, and tags. In addition, a collection of bitmaps keyed by an ObjectId is also included. The bitmap for each entry in the collection represents the full closure of ObjectIds reachable from the keyed ObjectId (including the keyed ObjectId itself). The bitmaps are further compressed by XORing the current bitmaps against prior bitmaps in the index, and selecting the smallest representation. The XOR'd bitmap and offset from the current entry to the position of the bitmap to XOR against is the actual representation of the entry in the index file. Each entry contains one byte, which is currently used to note whether the bitmap should be blindly reused. Change-Id: Id328724bf6b4c8366a088233098c18643edcf40f
11 years ago
Use java.io.File to check existence of loose objects in ObjectDirectory It was reported in [1] that 197e3393a51424fae45e51dce4a649ba26e5a368 led to a performance regression in a BFG benchmark. Analysis showed that this is caused by the exists() method in FS_POSIX, now overriding the default implementation in FS. The default implementation of FS.exists() uses java.io.File.exists(), while the new implementation in FS_POSIX uses java.nio.file.Files.exists() - by simply removing the override in FS_POSIX, performance was restored. Profiling showed that java.nio.file.Files.exists() is substantially slower than java.io.File.exists(), to the point where the exists() call doubles the average cost of a call to ObjectDirectory.insertUnpackedObject() - which the BFG uses a lot, because it's rewriting history. Average times measured on Ubuntu were: java.io.File.exists() - 4 microseconds java.nio.file.Files.exists() - 60 microseconds The loose object exists test should be using java.io.File and not FS. ObjectDirectory uses FS.resolve() to traverse symlinks to objects but then once inside objects all 256 sharded directories should be real directories, and the object files should be real files, not dangling symlinks. java.io.File.exists() is sufficient here, and faster. Change ObjectDirectory to use File.exists() once its computed the File handle. This does mean JGit cannot run ObjectDirectory code on an abstract virtual filesystem plugged into NIO2. If you really want to run JGit on an esoteric non-standard filesystem like "in memory" you should look at the DFS storage backend, which has fewer abstraction points to deal with. Or write your own from scratch. [1] https://dev.eclipse.org/mhonarc/lists/jgit-dev/msg02954.html Change-Id: I74684dc3957ae1ca52a7097f83a6c420aa24310f Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
8 years ago
Fix concurrent creation of fan-out object directories If multiple threads attempted to insert loose objects into the same new fan-out directory, the creation of that directory was subject to a race condition that could lead to an unnecessary IOException being thrown - because an inserter could not 'create' a directory that had just been generated by a different thread. All we require is that the directory does indeed *exist*, so not being able to _create_ it is not actually a fatal problem. Setting 'skipExisting' to 'true' on the call to mkdir() fixes the issue. I found this issue as a real world occurrence while working on The BFG Repo Cleaner (https://github.com/rtyley/bfg-repo-cleaner), a tool which concurrently performs a lot of object creation. In order to demonstrate the problem here I've added a small test case which reliably reproduces the issue on the few different hardware systems I've tried. The error thrown when the race-condition arises is this: java.io.IOException: Creating directory /home/roberto/repo.git/objects/e6 failed at org.eclipse.jgit.util.FileUtils.mkdir(FileUtils.java:182) at org.eclipse.jgit.storage.file.ObjectDirectory.insertUnpackedObject(ObjectDirectory.java:590) at org.eclipse.jgit.storage.file.ObjectDirectoryInserter.insertOneObject(ObjectDirectoryInserter.java:113) at org.eclipse.jgit.storage.file.ObjectDirectoryInserter.insert(ObjectDirectoryInserter.java:91) at org.eclipse.jgit.lib.ObjectInserter.insert(ObjectInserter.java:329) Change-Id: I88eac49bc600c56ba9ad290e6133d8a7113125ab
11 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160
  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.Objects;
  65. import java.util.Set;
  66. import java.util.concurrent.atomic.AtomicReference;
  67. import org.eclipse.jgit.errors.CorruptObjectException;
  68. import org.eclipse.jgit.errors.PackInvalidException;
  69. import org.eclipse.jgit.errors.PackMismatchException;
  70. import org.eclipse.jgit.internal.JGitText;
  71. import org.eclipse.jgit.internal.storage.pack.ObjectToPack;
  72. import org.eclipse.jgit.internal.storage.pack.PackExt;
  73. import org.eclipse.jgit.internal.storage.pack.PackWriter;
  74. import org.eclipse.jgit.lib.AbbreviatedObjectId;
  75. import org.eclipse.jgit.lib.AnyObjectId;
  76. import org.eclipse.jgit.lib.Config;
  77. import org.eclipse.jgit.lib.ConfigConstants;
  78. import org.eclipse.jgit.lib.Constants;
  79. import org.eclipse.jgit.lib.ObjectDatabase;
  80. import org.eclipse.jgit.lib.ObjectId;
  81. import org.eclipse.jgit.lib.ObjectLoader;
  82. import org.eclipse.jgit.lib.RepositoryCache;
  83. import org.eclipse.jgit.lib.RepositoryCache.FileKey;
  84. import org.eclipse.jgit.util.FS;
  85. import org.eclipse.jgit.util.FileUtils;
  86. import org.slf4j.Logger;
  87. import org.slf4j.LoggerFactory;
  88. /**
  89. * Traditional file system based {@link org.eclipse.jgit.lib.ObjectDatabase}.
  90. * <p>
  91. * This is the classical object database representation for a Git repository,
  92. * where objects are stored loose by hashing them into directories by their
  93. * {@link org.eclipse.jgit.lib.ObjectId}, or are stored in compressed containers
  94. * known as {@link org.eclipse.jgit.internal.storage.file.PackFile}s.
  95. * <p>
  96. * Optionally an object database can reference one or more alternates; other
  97. * ObjectDatabase instances that are searched in addition to the current
  98. * database.
  99. * <p>
  100. * Databases are divided into two halves: a half that is considered to be fast
  101. * to search (the {@code PackFile}s), and a half that is considered to be slow
  102. * to search (loose objects). When alternates are present the fast half is fully
  103. * searched (recursively through all alternates) before the slow half is
  104. * considered.
  105. */
  106. public class ObjectDirectory extends FileObjectDatabase {
  107. private final static Logger LOG = LoggerFactory
  108. .getLogger(ObjectDirectory.class);
  109. private static final PackList NO_PACKS = new PackList(
  110. FileSnapshot.DIRTY, new PackFile[0]);
  111. /** Maximum number of candidates offered as resolutions of abbreviation. */
  112. private static final int RESOLVE_ABBREV_LIMIT = 256;
  113. private final AlternateHandle handle = new AlternateHandle(this);
  114. private final Config config;
  115. private final File objects;
  116. private final File infoDirectory;
  117. private final File packDirectory;
  118. private final File preservedDirectory;
  119. private final File alternatesFile;
  120. private final AtomicReference<PackList> packList;
  121. private final FS fs;
  122. private final AtomicReference<AlternateHandle[]> alternates;
  123. private final UnpackedObjectCache unpackedObjectCache;
  124. private final File shallowFile;
  125. private FileSnapshot shallowFileSnapshot = FileSnapshot.DIRTY;
  126. private Set<ObjectId> shallowCommitsIds;
  127. /**
  128. * Initialize a reference to an on-disk object directory.
  129. *
  130. * @param cfg
  131. * configuration this directory consults for write settings.
  132. * @param dir
  133. * the location of the <code>objects</code> directory.
  134. * @param alternatePaths
  135. * a list of alternate object directories
  136. * @param fs
  137. * the file system abstraction which will be necessary to perform
  138. * certain file system operations.
  139. * @param shallowFile
  140. * file which contains IDs of shallow commits, null if shallow
  141. * commits handling should be turned off
  142. * @throws java.io.IOException
  143. * an alternate object cannot be opened.
  144. */
  145. public ObjectDirectory(final Config cfg, final File dir,
  146. File[] alternatePaths, FS fs, File shallowFile) throws IOException {
  147. config = cfg;
  148. objects = dir;
  149. infoDirectory = new File(objects, "info"); //$NON-NLS-1$
  150. packDirectory = new File(objects, "pack"); //$NON-NLS-1$
  151. preservedDirectory = new File(packDirectory, "preserved"); //$NON-NLS-1$
  152. alternatesFile = new File(infoDirectory, "alternates"); //$NON-NLS-1$
  153. packList = new AtomicReference<>(NO_PACKS);
  154. unpackedObjectCache = new UnpackedObjectCache();
  155. this.fs = fs;
  156. this.shallowFile = shallowFile;
  157. alternates = new AtomicReference<>();
  158. if (alternatePaths != null) {
  159. AlternateHandle[] alt;
  160. alt = new AlternateHandle[alternatePaths.length];
  161. for (int i = 0; i < alternatePaths.length; i++)
  162. alt[i] = openAlternate(alternatePaths[i]);
  163. alternates.set(alt);
  164. }
  165. }
  166. /** {@inheritDoc} */
  167. @Override
  168. public final File getDirectory() {
  169. return objects;
  170. }
  171. /**
  172. * <p>Getter for the field <code>packDirectory</code>.</p>
  173. *
  174. * @return the location of the <code>pack</code> directory.
  175. * @since 4.10
  176. */
  177. public final File getPackDirectory() {
  178. return packDirectory;
  179. }
  180. /**
  181. * <p>Getter for the field <code>preservedDirectory</code>.</p>
  182. *
  183. * @return the location of the <code>preserved</code> directory.
  184. */
  185. public final File getPreservedDirectory() {
  186. return preservedDirectory;
  187. }
  188. /** {@inheritDoc} */
  189. @Override
  190. public boolean exists() {
  191. return fs.exists(objects);
  192. }
  193. /** {@inheritDoc} */
  194. @Override
  195. public void create() throws IOException {
  196. FileUtils.mkdirs(objects);
  197. FileUtils.mkdir(infoDirectory);
  198. FileUtils.mkdir(packDirectory);
  199. }
  200. /** {@inheritDoc} */
  201. @Override
  202. public ObjectDirectoryInserter newInserter() {
  203. return new ObjectDirectoryInserter(this, config);
  204. }
  205. /**
  206. * Create a new inserter that inserts all objects as pack files, not loose
  207. * objects.
  208. *
  209. * @return new inserter.
  210. */
  211. public PackInserter newPackInserter() {
  212. return new PackInserter(this);
  213. }
  214. /** {@inheritDoc} */
  215. @Override
  216. public void close() {
  217. unpackedObjectCache.clear();
  218. final PackList packs = packList.get();
  219. if (packs != NO_PACKS && packList.compareAndSet(packs, NO_PACKS)) {
  220. for (PackFile p : packs.packs)
  221. p.close();
  222. }
  223. // Fully close all loaded alternates and clear the alternate list.
  224. AlternateHandle[] alt = alternates.get();
  225. if (alt != null && alternates.compareAndSet(alt, null)) {
  226. for(AlternateHandle od : alt)
  227. od.close();
  228. }
  229. }
  230. /** {@inheritDoc} */
  231. @Override
  232. public Collection<PackFile> getPacks() {
  233. PackList list = packList.get();
  234. if (list == NO_PACKS)
  235. list = scanPacks(list);
  236. PackFile[] packs = list.packs;
  237. return Collections.unmodifiableCollection(Arrays.asList(packs));
  238. }
  239. /**
  240. * {@inheritDoc}
  241. * <p>
  242. * Add a single existing pack to the list of available pack files.
  243. */
  244. @Override
  245. public PackFile openPack(File pack)
  246. throws IOException {
  247. final String p = pack.getName();
  248. if (p.length() != 50 || !p.startsWith("pack-") || !p.endsWith(".pack")) //$NON-NLS-1$ //$NON-NLS-2$
  249. throw new IOException(MessageFormat.format(JGitText.get().notAValidPack, pack));
  250. // The pack and index are assumed to exist. The existence of other
  251. // extensions needs to be explicitly checked.
  252. //
  253. int extensions = PACK.getBit() | INDEX.getBit();
  254. final String base = p.substring(0, p.length() - 4);
  255. for (PackExt ext : PackExt.values()) {
  256. if ((extensions & ext.getBit()) == 0) {
  257. final String name = base + ext.getExtension();
  258. if (new File(pack.getParentFile(), name).exists())
  259. extensions |= ext.getBit();
  260. }
  261. }
  262. PackFile res = new PackFile(pack, extensions);
  263. insertPack(res);
  264. return res;
  265. }
  266. /** {@inheritDoc} */
  267. @Override
  268. public String toString() {
  269. return "ObjectDirectory[" + getDirectory() + "]"; //$NON-NLS-1$ //$NON-NLS-2$
  270. }
  271. /** {@inheritDoc} */
  272. @Override
  273. public boolean has(AnyObjectId objectId) {
  274. return unpackedObjectCache.isUnpacked(objectId)
  275. || hasPackedInSelfOrAlternate(objectId, null)
  276. || hasLooseInSelfOrAlternate(objectId, null);
  277. }
  278. private boolean hasPackedInSelfOrAlternate(AnyObjectId objectId,
  279. Set<AlternateHandle.Id> skips) {
  280. if (hasPackedObject(objectId)) {
  281. return true;
  282. }
  283. skips = addMe(skips);
  284. for (AlternateHandle alt : myAlternates()) {
  285. if (!skips.contains(alt.getId())) {
  286. if (alt.db.hasPackedInSelfOrAlternate(objectId, skips)) {
  287. return true;
  288. }
  289. }
  290. }
  291. return false;
  292. }
  293. private boolean hasLooseInSelfOrAlternate(AnyObjectId objectId,
  294. Set<AlternateHandle.Id> skips) {
  295. if (fileFor(objectId).exists()) {
  296. return true;
  297. }
  298. skips = addMe(skips);
  299. for (AlternateHandle alt : myAlternates()) {
  300. if (!skips.contains(alt.getId())) {
  301. if (alt.db.hasLooseInSelfOrAlternate(objectId, skips)) {
  302. return true;
  303. }
  304. }
  305. }
  306. return false;
  307. }
  308. boolean hasPackedObject(AnyObjectId objectId) {
  309. PackList pList;
  310. do {
  311. pList = packList.get();
  312. for (PackFile p : pList.packs) {
  313. try {
  314. if (p.hasObject(objectId))
  315. return true;
  316. } catch (IOException e) {
  317. // The hasObject call should have only touched the index,
  318. // so any failure here indicates the index is unreadable
  319. // by this process, and the pack is likewise not readable.
  320. removePack(p);
  321. }
  322. }
  323. } while (searchPacksAgain(pList));
  324. return false;
  325. }
  326. @Override
  327. void resolve(Set<ObjectId> matches, AbbreviatedObjectId id)
  328. throws IOException {
  329. resolve(matches, id, null);
  330. }
  331. private void resolve(Set<ObjectId> matches, AbbreviatedObjectId id,
  332. Set<AlternateHandle.Id> skips)
  333. throws IOException {
  334. // Go through the packs once. If we didn't find any resolutions
  335. // scan for new packs and check once more.
  336. int oldSize = matches.size();
  337. PackList pList;
  338. do {
  339. pList = packList.get();
  340. for (PackFile p : pList.packs) {
  341. try {
  342. p.resolve(matches, id, RESOLVE_ABBREV_LIMIT);
  343. p.resetTransientErrorCount();
  344. } catch (IOException e) {
  345. handlePackError(e, p);
  346. }
  347. if (matches.size() > RESOLVE_ABBREV_LIMIT)
  348. return;
  349. }
  350. } while (matches.size() == oldSize && searchPacksAgain(pList));
  351. String fanOut = id.name().substring(0, 2);
  352. String[] entries = new File(getDirectory(), fanOut).list();
  353. if (entries != null) {
  354. for (String e : entries) {
  355. if (e.length() != Constants.OBJECT_ID_STRING_LENGTH - 2)
  356. continue;
  357. try {
  358. ObjectId entId = ObjectId.fromString(fanOut + e);
  359. if (id.prefixCompare(entId) == 0)
  360. matches.add(entId);
  361. } catch (IllegalArgumentException notId) {
  362. continue;
  363. }
  364. if (matches.size() > RESOLVE_ABBREV_LIMIT)
  365. return;
  366. }
  367. }
  368. skips = addMe(skips);
  369. for (AlternateHandle alt : myAlternates()) {
  370. if (!skips.contains(alt.getId())) {
  371. alt.db.resolve(matches, id, skips);
  372. if (matches.size() > RESOLVE_ABBREV_LIMIT) {
  373. return;
  374. }
  375. }
  376. }
  377. }
  378. @Override
  379. ObjectLoader openObject(WindowCursor curs, AnyObjectId objectId)
  380. throws IOException {
  381. if (unpackedObjectCache.isUnpacked(objectId)) {
  382. ObjectLoader ldr = openLooseObject(curs, objectId);
  383. if (ldr != null) {
  384. return ldr;
  385. }
  386. }
  387. ObjectLoader ldr = openPackedFromSelfOrAlternate(curs, objectId, null);
  388. if (ldr != null) {
  389. return ldr;
  390. }
  391. return openLooseFromSelfOrAlternate(curs, objectId, null);
  392. }
  393. private ObjectLoader openPackedFromSelfOrAlternate(WindowCursor curs,
  394. AnyObjectId objectId, Set<AlternateHandle.Id> skips) {
  395. ObjectLoader ldr = openPackedObject(curs, objectId);
  396. if (ldr != null) {
  397. return ldr;
  398. }
  399. skips = addMe(skips);
  400. for (AlternateHandle alt : myAlternates()) {
  401. if (!skips.contains(alt.getId())) {
  402. ldr = alt.db.openPackedFromSelfOrAlternate(curs, objectId, skips);
  403. if (ldr != null) {
  404. return ldr;
  405. }
  406. }
  407. }
  408. return null;
  409. }
  410. private ObjectLoader openLooseFromSelfOrAlternate(WindowCursor curs,
  411. AnyObjectId objectId, Set<AlternateHandle.Id> skips)
  412. throws IOException {
  413. ObjectLoader ldr = openLooseObject(curs, objectId);
  414. if (ldr != null) {
  415. return ldr;
  416. }
  417. skips = addMe(skips);
  418. for (AlternateHandle alt : myAlternates()) {
  419. if (!skips.contains(alt.getId())) {
  420. ldr = alt.db.openLooseFromSelfOrAlternate(curs, objectId, skips);
  421. if (ldr != null) {
  422. return ldr;
  423. }
  424. }
  425. }
  426. return null;
  427. }
  428. ObjectLoader openPackedObject(WindowCursor curs, AnyObjectId objectId) {
  429. PackList pList;
  430. do {
  431. SEARCH: for (;;) {
  432. pList = packList.get();
  433. for (PackFile p : pList.packs) {
  434. try {
  435. ObjectLoader ldr = p.get(curs, objectId);
  436. p.resetTransientErrorCount();
  437. if (ldr != null)
  438. return ldr;
  439. } catch (PackMismatchException e) {
  440. // Pack was modified; refresh the entire pack list.
  441. if (searchPacksAgain(pList))
  442. continue SEARCH;
  443. } catch (IOException e) {
  444. handlePackError(e, p);
  445. }
  446. }
  447. break SEARCH;
  448. }
  449. } while (searchPacksAgain(pList));
  450. return null;
  451. }
  452. @Override
  453. ObjectLoader openLooseObject(WindowCursor curs, AnyObjectId id)
  454. throws IOException {
  455. File path = fileFor(id);
  456. try (FileInputStream in = new FileInputStream(path)) {
  457. unpackedObjectCache.add(id);
  458. return UnpackedObject.open(in, path, id, curs);
  459. } catch (FileNotFoundException noFile) {
  460. if (path.exists()) {
  461. throw noFile;
  462. }
  463. unpackedObjectCache.remove(id);
  464. return null;
  465. }
  466. }
  467. @Override
  468. long getObjectSize(WindowCursor curs, AnyObjectId id)
  469. throws IOException {
  470. if (unpackedObjectCache.isUnpacked(id)) {
  471. long len = getLooseObjectSize(curs, id);
  472. if (0 <= len) {
  473. return len;
  474. }
  475. }
  476. long len = getPackedSizeFromSelfOrAlternate(curs, id, null);
  477. if (0 <= len) {
  478. return len;
  479. }
  480. return getLooseSizeFromSelfOrAlternate(curs, id, null);
  481. }
  482. private long getPackedSizeFromSelfOrAlternate(WindowCursor curs,
  483. AnyObjectId id, Set<AlternateHandle.Id> skips) {
  484. long len = getPackedObjectSize(curs, id);
  485. if (0 <= len) {
  486. return len;
  487. }
  488. skips = addMe(skips);
  489. for (AlternateHandle alt : myAlternates()) {
  490. if (!skips.contains(alt.getId())) {
  491. len = alt.db.getPackedSizeFromSelfOrAlternate(curs, id, skips);
  492. if (0 <= len) {
  493. return len;
  494. }
  495. }
  496. }
  497. return -1;
  498. }
  499. private long getLooseSizeFromSelfOrAlternate(WindowCursor curs,
  500. AnyObjectId id, Set<AlternateHandle.Id> skips) throws IOException {
  501. long len = getLooseObjectSize(curs, id);
  502. if (0 <= len) {
  503. return len;
  504. }
  505. skips = addMe(skips);
  506. for (AlternateHandle alt : myAlternates()) {
  507. if (!skips.contains(alt.getId())) {
  508. len = alt.db.getLooseSizeFromSelfOrAlternate(curs, id, skips);
  509. if (0 <= len) {
  510. return len;
  511. }
  512. }
  513. }
  514. return -1;
  515. }
  516. private long getPackedObjectSize(WindowCursor curs, AnyObjectId id) {
  517. PackList pList;
  518. do {
  519. SEARCH: for (;;) {
  520. pList = packList.get();
  521. for (PackFile p : pList.packs) {
  522. try {
  523. long len = p.getObjectSize(curs, id);
  524. p.resetTransientErrorCount();
  525. if (0 <= len)
  526. return len;
  527. } catch (PackMismatchException e) {
  528. // Pack was modified; refresh the entire pack list.
  529. if (searchPacksAgain(pList))
  530. continue SEARCH;
  531. } catch (IOException e) {
  532. handlePackError(e, p);
  533. }
  534. }
  535. break SEARCH;
  536. }
  537. } while (searchPacksAgain(pList));
  538. return -1;
  539. }
  540. private long getLooseObjectSize(WindowCursor curs, AnyObjectId id)
  541. throws IOException {
  542. File f = fileFor(id);
  543. try (FileInputStream in = new FileInputStream(f)) {
  544. unpackedObjectCache.add(id);
  545. return UnpackedObject.getSize(in, id, curs);
  546. } catch (FileNotFoundException noFile) {
  547. if (f.exists()) {
  548. throw noFile;
  549. }
  550. unpackedObjectCache.remove(id);
  551. return -1;
  552. }
  553. }
  554. @Override
  555. void selectObjectRepresentation(PackWriter packer, ObjectToPack otp,
  556. WindowCursor curs) throws IOException {
  557. selectObjectRepresentation(packer, otp, curs, null);
  558. }
  559. private void selectObjectRepresentation(PackWriter packer, ObjectToPack otp,
  560. WindowCursor curs, Set<AlternateHandle.Id> skips) throws IOException {
  561. PackList pList = packList.get();
  562. SEARCH: for (;;) {
  563. for (PackFile p : pList.packs) {
  564. try {
  565. LocalObjectRepresentation rep = p.representation(curs, otp);
  566. p.resetTransientErrorCount();
  567. if (rep != null)
  568. packer.select(otp, rep);
  569. } catch (PackMismatchException e) {
  570. // Pack was modified; refresh the entire pack list.
  571. //
  572. pList = scanPacks(pList);
  573. continue SEARCH;
  574. } catch (IOException e) {
  575. handlePackError(e, p);
  576. }
  577. }
  578. break SEARCH;
  579. }
  580. skips = addMe(skips);
  581. for (AlternateHandle h : myAlternates()) {
  582. if (!skips.contains(h.getId())) {
  583. h.db.selectObjectRepresentation(packer, otp, curs, skips);
  584. }
  585. }
  586. }
  587. private void handlePackError(IOException e, PackFile p) {
  588. String warnTmpl = null;
  589. int transientErrorCount = 0;
  590. String errTmpl = JGitText.get().exceptionWhileReadingPack;
  591. if ((e instanceof CorruptObjectException)
  592. || (e instanceof PackInvalidException)) {
  593. warnTmpl = JGitText.get().corruptPack;
  594. // Assume the pack is corrupted, and remove it from the list.
  595. removePack(p);
  596. } else if (e instanceof FileNotFoundException) {
  597. if (p.getPackFile().exists()) {
  598. errTmpl = JGitText.get().packInaccessible;
  599. transientErrorCount = p.incrementTransientErrorCount();
  600. } else {
  601. warnTmpl = JGitText.get().packWasDeleted;
  602. removePack(p);
  603. }
  604. } else if (FileUtils.isStaleFileHandleInCausalChain(e)) {
  605. warnTmpl = JGitText.get().packHandleIsStale;
  606. removePack(p);
  607. } else {
  608. transientErrorCount = p.incrementTransientErrorCount();
  609. }
  610. if (warnTmpl != null) {
  611. if (LOG.isDebugEnabled()) {
  612. LOG.debug(MessageFormat.format(warnTmpl,
  613. p.getPackFile().getAbsolutePath()), e);
  614. } else {
  615. LOG.warn(MessageFormat.format(warnTmpl,
  616. p.getPackFile().getAbsolutePath()));
  617. }
  618. } else {
  619. if (doLogExponentialBackoff(transientErrorCount)) {
  620. // Don't remove the pack from the list, as the error may be
  621. // transient.
  622. LOG.error(MessageFormat.format(errTmpl,
  623. p.getPackFile().getAbsolutePath()),
  624. Integer.valueOf(transientErrorCount), e);
  625. }
  626. }
  627. }
  628. /**
  629. * @param n
  630. * count of consecutive failures
  631. * @return @{code true} if i is a power of 2
  632. */
  633. private boolean doLogExponentialBackoff(int n) {
  634. return (n & (n - 1)) == 0;
  635. }
  636. @Override
  637. InsertLooseObjectResult insertUnpackedObject(File tmp, ObjectId id,
  638. boolean createDuplicate) throws IOException {
  639. // If the object is already in the repository, remove temporary file.
  640. //
  641. if (unpackedObjectCache.isUnpacked(id)) {
  642. FileUtils.delete(tmp, FileUtils.RETRY);
  643. return InsertLooseObjectResult.EXISTS_LOOSE;
  644. }
  645. if (!createDuplicate && has(id)) {
  646. FileUtils.delete(tmp, FileUtils.RETRY);
  647. return InsertLooseObjectResult.EXISTS_PACKED;
  648. }
  649. final File dst = fileFor(id);
  650. if (dst.exists()) {
  651. // We want to be extra careful and avoid replacing an object
  652. // that already exists. We can't be sure renameTo() would
  653. // fail on all platforms if dst exists, so we check first.
  654. //
  655. FileUtils.delete(tmp, FileUtils.RETRY);
  656. return InsertLooseObjectResult.EXISTS_LOOSE;
  657. }
  658. try {
  659. Files.move(FileUtils.toPath(tmp), FileUtils.toPath(dst),
  660. StandardCopyOption.ATOMIC_MOVE);
  661. dst.setReadOnly();
  662. unpackedObjectCache.add(id);
  663. return InsertLooseObjectResult.INSERTED;
  664. } catch (AtomicMoveNotSupportedException e) {
  665. LOG.error(e.getMessage(), e);
  666. } catch (IOException e) {
  667. // ignore
  668. }
  669. // Maybe the directory doesn't exist yet as the object
  670. // directories are always lazily created. Note that we
  671. // try the rename first as the directory likely does exist.
  672. //
  673. FileUtils.mkdir(dst.getParentFile(), true);
  674. try {
  675. Files.move(FileUtils.toPath(tmp), FileUtils.toPath(dst),
  676. StandardCopyOption.ATOMIC_MOVE);
  677. dst.setReadOnly();
  678. unpackedObjectCache.add(id);
  679. return InsertLooseObjectResult.INSERTED;
  680. } catch (AtomicMoveNotSupportedException e) {
  681. LOG.error(e.getMessage(), e);
  682. } catch (IOException e) {
  683. LOG.debug(e.getMessage(), e);
  684. }
  685. if (!createDuplicate && has(id)) {
  686. FileUtils.delete(tmp, FileUtils.RETRY);
  687. return InsertLooseObjectResult.EXISTS_PACKED;
  688. }
  689. // The object failed to be renamed into its proper
  690. // location and it doesn't exist in the repository
  691. // either. We really don't know what went wrong, so
  692. // fail.
  693. //
  694. FileUtils.delete(tmp, FileUtils.RETRY);
  695. return InsertLooseObjectResult.FAILURE;
  696. }
  697. private boolean searchPacksAgain(PackList old) {
  698. // Whether to trust the pack folder's modification time. If set
  699. // to false we will always scan the .git/objects/pack folder to
  700. // check for new pack files. If set to true (default) we use the
  701. // lastmodified attribute of the folder and assume that no new
  702. // pack files can be in this folder if his modification time has
  703. // not changed.
  704. boolean trustFolderStat = config.getBoolean(
  705. ConfigConstants.CONFIG_CORE_SECTION,
  706. ConfigConstants.CONFIG_KEY_TRUSTFOLDERSTAT, true);
  707. return ((!trustFolderStat) || old.snapshot.isModified(packDirectory))
  708. && old != scanPacks(old);
  709. }
  710. @Override
  711. Config getConfig() {
  712. return config;
  713. }
  714. @Override
  715. FS getFS() {
  716. return fs;
  717. }
  718. @Override
  719. Set<ObjectId> getShallowCommits() throws IOException {
  720. if (shallowFile == null || !shallowFile.isFile())
  721. return Collections.emptySet();
  722. if (shallowFileSnapshot == null
  723. || shallowFileSnapshot.isModified(shallowFile)) {
  724. shallowCommitsIds = new HashSet<>();
  725. try (BufferedReader reader = open(shallowFile)) {
  726. String line;
  727. while ((line = reader.readLine()) != null) {
  728. try {
  729. shallowCommitsIds.add(ObjectId.fromString(line));
  730. } catch (IllegalArgumentException ex) {
  731. throw new IOException(MessageFormat
  732. .format(JGitText.get().badShallowLine, line));
  733. }
  734. }
  735. }
  736. shallowFileSnapshot = FileSnapshot.save(shallowFile);
  737. }
  738. return shallowCommitsIds;
  739. }
  740. private void insertPack(PackFile pf) {
  741. PackList o, n;
  742. do {
  743. o = packList.get();
  744. // If the pack in question is already present in the list
  745. // (picked up by a concurrent thread that did a scan?) we
  746. // do not want to insert it a second time.
  747. //
  748. final PackFile[] oldList = o.packs;
  749. final String name = pf.getPackFile().getName();
  750. for (PackFile p : oldList) {
  751. if (name.equals(p.getPackFile().getName()))
  752. return;
  753. }
  754. final PackFile[] newList = new PackFile[1 + oldList.length];
  755. newList[0] = pf;
  756. System.arraycopy(oldList, 0, newList, 1, oldList.length);
  757. n = new PackList(o.snapshot, newList);
  758. } while (!packList.compareAndSet(o, n));
  759. }
  760. private void removePack(PackFile deadPack) {
  761. PackList o, n;
  762. do {
  763. o = packList.get();
  764. final PackFile[] oldList = o.packs;
  765. final int j = indexOf(oldList, deadPack);
  766. if (j < 0)
  767. break;
  768. final PackFile[] newList = new PackFile[oldList.length - 1];
  769. System.arraycopy(oldList, 0, newList, 0, j);
  770. System.arraycopy(oldList, j + 1, newList, j, newList.length - j);
  771. n = new PackList(o.snapshot, newList);
  772. } while (!packList.compareAndSet(o, n));
  773. deadPack.close();
  774. }
  775. private static int indexOf(PackFile[] list, PackFile pack) {
  776. for (int i = 0; i < list.length; i++) {
  777. if (list[i] == pack)
  778. return i;
  779. }
  780. return -1;
  781. }
  782. private PackList scanPacks(PackList original) {
  783. synchronized (packList) {
  784. PackList o, n;
  785. do {
  786. o = packList.get();
  787. if (o != original) {
  788. // Another thread did the scan for us, while we
  789. // were blocked on the monitor above.
  790. //
  791. return o;
  792. }
  793. n = scanPacksImpl(o);
  794. if (n == o)
  795. return n;
  796. } while (!packList.compareAndSet(o, n));
  797. return n;
  798. }
  799. }
  800. private PackList scanPacksImpl(PackList old) {
  801. final Map<String, PackFile> forReuse = reuseMap(old);
  802. final FileSnapshot snapshot = FileSnapshot.save(packDirectory);
  803. final Set<String> names = listPackDirectory();
  804. final List<PackFile> list = new ArrayList<>(names.size() >> 2);
  805. boolean foundNew = false;
  806. for (String indexName : names) {
  807. // Must match "pack-[0-9a-f]{40}.idx" to be an index.
  808. //
  809. if (indexName.length() != 49 || !indexName.endsWith(".idx")) //$NON-NLS-1$
  810. continue;
  811. final String base = indexName.substring(0, indexName.length() - 3);
  812. int extensions = 0;
  813. for (PackExt ext : PackExt.values()) {
  814. if (names.contains(base + ext.getExtension()))
  815. extensions |= ext.getBit();
  816. }
  817. if ((extensions & PACK.getBit()) == 0) {
  818. // Sometimes C Git's HTTP fetch transport leaves a
  819. // .idx file behind and does not download the .pack.
  820. // We have to skip over such useless indexes.
  821. //
  822. continue;
  823. }
  824. final String packName = base + PACK.getExtension();
  825. final PackFile oldPack = forReuse.remove(packName);
  826. if (oldPack != null) {
  827. list.add(oldPack);
  828. continue;
  829. }
  830. final File packFile = new File(packDirectory, packName);
  831. list.add(new PackFile(packFile, extensions));
  832. foundNew = true;
  833. }
  834. // If we did not discover any new files, the modification time was not
  835. // changed, and we did not remove any files, then the set of files is
  836. // the same as the set we were given. Instead of building a new object
  837. // return the same collection.
  838. //
  839. if (!foundNew && forReuse.isEmpty() && snapshot.equals(old.snapshot)) {
  840. old.snapshot.setClean(snapshot);
  841. return old;
  842. }
  843. for (PackFile p : forReuse.values()) {
  844. p.close();
  845. }
  846. if (list.isEmpty())
  847. return new PackList(snapshot, NO_PACKS.packs);
  848. final PackFile[] r = list.toArray(new PackFile[list.size()]);
  849. Arrays.sort(r, PackFile.SORT);
  850. return new PackList(snapshot, r);
  851. }
  852. private static Map<String, PackFile> reuseMap(PackList old) {
  853. final Map<String, PackFile> forReuse = new HashMap<>();
  854. for (PackFile p : old.packs) {
  855. if (p.invalid()) {
  856. // The pack instance is corrupted, and cannot be safely used
  857. // again. Do not include it in our reuse map.
  858. //
  859. p.close();
  860. continue;
  861. }
  862. final PackFile prior = forReuse.put(p.getPackFile().getName(), p);
  863. if (prior != null) {
  864. // This should never occur. It should be impossible for us
  865. // to have two pack files with the same name, as all of them
  866. // came out of the same directory. If it does, we promised to
  867. // close any PackFiles we did not reuse, so close the second,
  868. // readers are likely to be actively using the first.
  869. //
  870. forReuse.put(prior.getPackFile().getName(), prior);
  871. p.close();
  872. }
  873. }
  874. return forReuse;
  875. }
  876. private Set<String> listPackDirectory() {
  877. final String[] nameList = packDirectory.list();
  878. if (nameList == null)
  879. return Collections.emptySet();
  880. final Set<String> nameSet = new HashSet<>(nameList.length << 1);
  881. for (String name : nameList) {
  882. if (name.startsWith("pack-")) //$NON-NLS-1$
  883. nameSet.add(name);
  884. }
  885. return nameSet;
  886. }
  887. void closeAllPackHandles(File packFile) {
  888. // if the packfile already exists (because we are rewriting a
  889. // packfile for the same set of objects maybe with different
  890. // PackConfig) then make sure we get rid of all handles on the file.
  891. // Windows will not allow for rename otherwise.
  892. if (packFile.exists()) {
  893. for (PackFile p : getPacks()) {
  894. if (packFile.getPath().equals(p.getPackFile().getPath())) {
  895. p.close();
  896. break;
  897. }
  898. }
  899. }
  900. }
  901. AlternateHandle[] myAlternates() {
  902. AlternateHandle[] alt = alternates.get();
  903. if (alt == null) {
  904. synchronized (alternates) {
  905. alt = alternates.get();
  906. if (alt == null) {
  907. try {
  908. alt = loadAlternates();
  909. } catch (IOException e) {
  910. alt = new AlternateHandle[0];
  911. }
  912. alternates.set(alt);
  913. }
  914. }
  915. }
  916. return alt;
  917. }
  918. Set<AlternateHandle.Id> addMe(Set<AlternateHandle.Id> skips) {
  919. if (skips == null) {
  920. skips = new HashSet<>();
  921. }
  922. skips.add(handle.getId());
  923. return skips;
  924. }
  925. private AlternateHandle[] loadAlternates() throws IOException {
  926. final List<AlternateHandle> l = new ArrayList<>(4);
  927. try (BufferedReader br = open(alternatesFile)) {
  928. String line;
  929. while ((line = br.readLine()) != null) {
  930. l.add(openAlternate(line));
  931. }
  932. }
  933. return l.toArray(new AlternateHandle[l.size()]);
  934. }
  935. private static BufferedReader open(File f)
  936. throws FileNotFoundException {
  937. return new BufferedReader(new FileReader(f));
  938. }
  939. private AlternateHandle openAlternate(String location)
  940. throws IOException {
  941. final File objdir = fs.resolve(objects, location);
  942. return openAlternate(objdir);
  943. }
  944. private AlternateHandle openAlternate(File objdir) throws IOException {
  945. final File parent = objdir.getParentFile();
  946. if (FileKey.isGitRepository(parent, fs)) {
  947. FileKey key = FileKey.exact(parent, fs);
  948. FileRepository db = (FileRepository) RepositoryCache.open(key);
  949. return new AlternateRepository(db);
  950. }
  951. ObjectDirectory db = new ObjectDirectory(config, objdir, null, fs, null);
  952. return new AlternateHandle(db);
  953. }
  954. /**
  955. * {@inheritDoc}
  956. * <p>
  957. * Compute the location of a loose object file.
  958. */
  959. @Override
  960. public File fileFor(AnyObjectId objectId) {
  961. String n = objectId.name();
  962. String d = n.substring(0, 2);
  963. String f = n.substring(2);
  964. return new File(new File(getDirectory(), d), f);
  965. }
  966. private static final class PackList {
  967. /** State just before reading the pack directory. */
  968. final FileSnapshot snapshot;
  969. /** All known packs, sorted by {@link PackFile#SORT}. */
  970. final PackFile[] packs;
  971. PackList(FileSnapshot monitor, PackFile[] packs) {
  972. this.snapshot = monitor;
  973. this.packs = packs;
  974. }
  975. }
  976. static class AlternateHandle {
  977. static class Id {
  978. String alternateId;
  979. public Id(File object) {
  980. try {
  981. this.alternateId = object.getCanonicalPath();
  982. } catch (Exception e) {
  983. alternateId = null;
  984. }
  985. }
  986. @Override
  987. public boolean equals(Object o) {
  988. if (o == this) {
  989. return true;
  990. }
  991. if (o == null || !(o instanceof Id)) {
  992. return false;
  993. }
  994. Id aId = (Id) o;
  995. return Objects.equals(alternateId, aId.alternateId);
  996. }
  997. @Override
  998. public int hashCode() {
  999. if (alternateId == null) {
  1000. return 1;
  1001. }
  1002. return alternateId.hashCode();
  1003. }
  1004. }
  1005. final ObjectDirectory db;
  1006. AlternateHandle(ObjectDirectory db) {
  1007. this.db = db;
  1008. }
  1009. void close() {
  1010. db.close();
  1011. }
  1012. public Id getId(){
  1013. return db.getAlternateId();
  1014. }
  1015. }
  1016. static class AlternateRepository extends AlternateHandle {
  1017. final FileRepository repository;
  1018. AlternateRepository(FileRepository r) {
  1019. super(r.getObjectDatabase());
  1020. repository = r;
  1021. }
  1022. @Override
  1023. void close() {
  1024. repository.close();
  1025. }
  1026. }
  1027. /** {@inheritDoc} */
  1028. @Override
  1029. public ObjectDatabase newCachedDatabase() {
  1030. return newCachedFileObjectDatabase();
  1031. }
  1032. CachedObjectDirectory newCachedFileObjectDatabase() {
  1033. return new CachedObjectDirectory(this);
  1034. }
  1035. AlternateHandle.Id getAlternateId() {
  1036. return new AlternateHandle.Id(objects);
  1037. }
  1038. }