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

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