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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162
  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 java.nio.charset.StandardCharsets.UTF_8;
  45. import static org.eclipse.jgit.internal.storage.pack.PackExt.INDEX;
  46. import static org.eclipse.jgit.internal.storage.pack.PackExt.PACK;
  47. import java.io.BufferedReader;
  48. import java.io.File;
  49. import java.io.FileInputStream;
  50. import java.io.FileNotFoundException;
  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 FS fs;
  121. private final AtomicReference<AlternateHandle[]> alternates;
  122. private final UnpackedObjectCache unpackedObjectCache;
  123. private final File shallowFile;
  124. private FileSnapshot shallowFileSnapshot = FileSnapshot.DIRTY;
  125. private Set<ObjectId> shallowCommitsIds;
  126. final AtomicReference<PackList> packList;
  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. LOG.warn(MessageFormat.format(
  321. JGitText.get().unableToReadPackfile,
  322. p.getPackFile().getAbsolutePath()), e);
  323. removePack(p);
  324. }
  325. }
  326. } while (searchPacksAgain(pList));
  327. return false;
  328. }
  329. @Override
  330. void resolve(Set<ObjectId> matches, AbbreviatedObjectId id)
  331. throws IOException {
  332. resolve(matches, id, null);
  333. }
  334. private void resolve(Set<ObjectId> matches, AbbreviatedObjectId id,
  335. Set<AlternateHandle.Id> skips)
  336. throws IOException {
  337. // Go through the packs once. If we didn't find any resolutions
  338. // scan for new packs and check once more.
  339. int oldSize = matches.size();
  340. PackList pList;
  341. do {
  342. pList = packList.get();
  343. for (PackFile p : pList.packs) {
  344. try {
  345. p.resolve(matches, id, RESOLVE_ABBREV_LIMIT);
  346. p.resetTransientErrorCount();
  347. } catch (IOException e) {
  348. handlePackError(e, p);
  349. }
  350. if (matches.size() > RESOLVE_ABBREV_LIMIT)
  351. return;
  352. }
  353. } while (matches.size() == oldSize && searchPacksAgain(pList));
  354. String fanOut = id.name().substring(0, 2);
  355. String[] entries = new File(getDirectory(), fanOut).list();
  356. if (entries != null) {
  357. for (String e : entries) {
  358. if (e.length() != Constants.OBJECT_ID_STRING_LENGTH - 2)
  359. continue;
  360. try {
  361. ObjectId entId = ObjectId.fromString(fanOut + e);
  362. if (id.prefixCompare(entId) == 0)
  363. matches.add(entId);
  364. } catch (IllegalArgumentException notId) {
  365. continue;
  366. }
  367. if (matches.size() > RESOLVE_ABBREV_LIMIT)
  368. return;
  369. }
  370. }
  371. skips = addMe(skips);
  372. for (AlternateHandle alt : myAlternates()) {
  373. if (!skips.contains(alt.getId())) {
  374. alt.db.resolve(matches, id, skips);
  375. if (matches.size() > RESOLVE_ABBREV_LIMIT) {
  376. return;
  377. }
  378. }
  379. }
  380. }
  381. @Override
  382. ObjectLoader openObject(WindowCursor curs, AnyObjectId objectId)
  383. throws IOException {
  384. if (unpackedObjectCache.isUnpacked(objectId)) {
  385. ObjectLoader ldr = openLooseObject(curs, objectId);
  386. if (ldr != null) {
  387. return ldr;
  388. }
  389. }
  390. ObjectLoader ldr = openPackedFromSelfOrAlternate(curs, objectId, null);
  391. if (ldr != null) {
  392. return ldr;
  393. }
  394. return openLooseFromSelfOrAlternate(curs, objectId, null);
  395. }
  396. private ObjectLoader openPackedFromSelfOrAlternate(WindowCursor curs,
  397. AnyObjectId objectId, Set<AlternateHandle.Id> skips) {
  398. ObjectLoader ldr = openPackedObject(curs, objectId);
  399. if (ldr != null) {
  400. return ldr;
  401. }
  402. skips = addMe(skips);
  403. for (AlternateHandle alt : myAlternates()) {
  404. if (!skips.contains(alt.getId())) {
  405. ldr = alt.db.openPackedFromSelfOrAlternate(curs, objectId, skips);
  406. if (ldr != null) {
  407. return ldr;
  408. }
  409. }
  410. }
  411. return null;
  412. }
  413. private ObjectLoader openLooseFromSelfOrAlternate(WindowCursor curs,
  414. AnyObjectId objectId, Set<AlternateHandle.Id> skips)
  415. throws IOException {
  416. ObjectLoader ldr = openLooseObject(curs, objectId);
  417. if (ldr != null) {
  418. return ldr;
  419. }
  420. skips = addMe(skips);
  421. for (AlternateHandle alt : myAlternates()) {
  422. if (!skips.contains(alt.getId())) {
  423. ldr = alt.db.openLooseFromSelfOrAlternate(curs, objectId, skips);
  424. if (ldr != null) {
  425. return ldr;
  426. }
  427. }
  428. }
  429. return null;
  430. }
  431. ObjectLoader openPackedObject(WindowCursor curs, AnyObjectId objectId) {
  432. PackList pList;
  433. do {
  434. SEARCH: for (;;) {
  435. pList = packList.get();
  436. for (PackFile p : pList.packs) {
  437. try {
  438. ObjectLoader ldr = p.get(curs, objectId);
  439. p.resetTransientErrorCount();
  440. if (ldr != null)
  441. return ldr;
  442. } catch (PackMismatchException e) {
  443. // Pack was modified; refresh the entire pack list.
  444. if (searchPacksAgain(pList))
  445. continue SEARCH;
  446. } catch (IOException e) {
  447. handlePackError(e, p);
  448. }
  449. }
  450. break SEARCH;
  451. }
  452. } while (searchPacksAgain(pList));
  453. return null;
  454. }
  455. @Override
  456. ObjectLoader openLooseObject(WindowCursor curs, AnyObjectId id)
  457. throws IOException {
  458. File path = fileFor(id);
  459. try (FileInputStream in = new FileInputStream(path)) {
  460. unpackedObjectCache.add(id);
  461. return UnpackedObject.open(in, path, id, curs);
  462. } catch (FileNotFoundException noFile) {
  463. if (path.exists()) {
  464. throw noFile;
  465. }
  466. unpackedObjectCache.remove(id);
  467. return null;
  468. }
  469. }
  470. @Override
  471. long getObjectSize(WindowCursor curs, AnyObjectId id)
  472. throws IOException {
  473. if (unpackedObjectCache.isUnpacked(id)) {
  474. long len = getLooseObjectSize(curs, id);
  475. if (0 <= len) {
  476. return len;
  477. }
  478. }
  479. long len = getPackedSizeFromSelfOrAlternate(curs, id, null);
  480. if (0 <= len) {
  481. return len;
  482. }
  483. return getLooseSizeFromSelfOrAlternate(curs, id, null);
  484. }
  485. private long getPackedSizeFromSelfOrAlternate(WindowCursor curs,
  486. AnyObjectId id, Set<AlternateHandle.Id> skips) {
  487. long len = getPackedObjectSize(curs, id);
  488. if (0 <= len) {
  489. return len;
  490. }
  491. skips = addMe(skips);
  492. for (AlternateHandle alt : myAlternates()) {
  493. if (!skips.contains(alt.getId())) {
  494. len = alt.db.getPackedSizeFromSelfOrAlternate(curs, id, skips);
  495. if (0 <= len) {
  496. return len;
  497. }
  498. }
  499. }
  500. return -1;
  501. }
  502. private long getLooseSizeFromSelfOrAlternate(WindowCursor curs,
  503. AnyObjectId id, Set<AlternateHandle.Id> skips) throws IOException {
  504. long len = getLooseObjectSize(curs, id);
  505. if (0 <= len) {
  506. return len;
  507. }
  508. skips = addMe(skips);
  509. for (AlternateHandle alt : myAlternates()) {
  510. if (!skips.contains(alt.getId())) {
  511. len = alt.db.getLooseSizeFromSelfOrAlternate(curs, id, skips);
  512. if (0 <= len) {
  513. return len;
  514. }
  515. }
  516. }
  517. return -1;
  518. }
  519. private long getPackedObjectSize(WindowCursor curs, AnyObjectId id) {
  520. PackList pList;
  521. do {
  522. SEARCH: for (;;) {
  523. pList = packList.get();
  524. for (PackFile p : pList.packs) {
  525. try {
  526. long len = p.getObjectSize(curs, id);
  527. p.resetTransientErrorCount();
  528. if (0 <= len)
  529. return len;
  530. } catch (PackMismatchException e) {
  531. // Pack was modified; refresh the entire pack list.
  532. if (searchPacksAgain(pList))
  533. continue SEARCH;
  534. } catch (IOException e) {
  535. handlePackError(e, p);
  536. }
  537. }
  538. break SEARCH;
  539. }
  540. } while (searchPacksAgain(pList));
  541. return -1;
  542. }
  543. private long getLooseObjectSize(WindowCursor curs, AnyObjectId id)
  544. throws IOException {
  545. File f = fileFor(id);
  546. try (FileInputStream in = new FileInputStream(f)) {
  547. unpackedObjectCache.add(id);
  548. return UnpackedObject.getSize(in, id, curs);
  549. } catch (FileNotFoundException noFile) {
  550. if (f.exists()) {
  551. throw noFile;
  552. }
  553. unpackedObjectCache.remove(id);
  554. return -1;
  555. }
  556. }
  557. @Override
  558. void selectObjectRepresentation(PackWriter packer, ObjectToPack otp,
  559. WindowCursor curs) throws IOException {
  560. selectObjectRepresentation(packer, otp, curs, null);
  561. }
  562. private void selectObjectRepresentation(PackWriter packer, ObjectToPack otp,
  563. WindowCursor curs, Set<AlternateHandle.Id> skips) throws IOException {
  564. PackList pList = packList.get();
  565. SEARCH: for (;;) {
  566. for (PackFile p : pList.packs) {
  567. try {
  568. LocalObjectRepresentation rep = p.representation(curs, otp);
  569. p.resetTransientErrorCount();
  570. if (rep != null)
  571. packer.select(otp, rep);
  572. } catch (PackMismatchException e) {
  573. // Pack was modified; refresh the entire pack list.
  574. //
  575. pList = scanPacks(pList);
  576. continue SEARCH;
  577. } catch (IOException e) {
  578. handlePackError(e, p);
  579. }
  580. }
  581. break SEARCH;
  582. }
  583. skips = addMe(skips);
  584. for (AlternateHandle h : myAlternates()) {
  585. if (!skips.contains(h.getId())) {
  586. h.db.selectObjectRepresentation(packer, otp, curs, skips);
  587. }
  588. }
  589. }
  590. private void handlePackError(IOException e, PackFile p) {
  591. String warnTmpl = null;
  592. int transientErrorCount = 0;
  593. String errTmpl = JGitText.get().exceptionWhileReadingPack;
  594. if ((e instanceof CorruptObjectException)
  595. || (e instanceof PackInvalidException)) {
  596. warnTmpl = JGitText.get().corruptPack;
  597. LOG.warn(MessageFormat.format(warnTmpl,
  598. p.getPackFile().getAbsolutePath()), e);
  599. // Assume the pack is corrupted, and remove it from the list.
  600. removePack(p);
  601. } else if (e instanceof FileNotFoundException) {
  602. if (p.getPackFile().exists()) {
  603. errTmpl = JGitText.get().packInaccessible;
  604. transientErrorCount = p.incrementTransientErrorCount();
  605. } else {
  606. warnTmpl = JGitText.get().packWasDeleted;
  607. removePack(p);
  608. }
  609. } else if (FileUtils.isStaleFileHandleInCausalChain(e)) {
  610. warnTmpl = JGitText.get().packHandleIsStale;
  611. removePack(p);
  612. } else {
  613. transientErrorCount = p.incrementTransientErrorCount();
  614. }
  615. if (warnTmpl != null) {
  616. LOG.warn(MessageFormat.format(warnTmpl,
  617. p.getPackFile().getAbsolutePath()), e);
  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. 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 File packFile = new File(packDirectory, packName);
  826. final PackFile oldPack = forReuse.get(packName);
  827. if (oldPack != null
  828. && !oldPack.getFileSnapshot().isModified(packFile)) {
  829. forReuse.remove(packName);
  830. list.add(oldPack);
  831. continue;
  832. }
  833. list.add(new PackFile(packFile, extensions));
  834. foundNew = true;
  835. }
  836. // If we did not discover any new files, the modification time was not
  837. // changed, and we did not remove any files, then the set of files is
  838. // the same as the set we were given. Instead of building a new object
  839. // return the same collection.
  840. //
  841. if (!foundNew && forReuse.isEmpty() && snapshot.equals(old.snapshot)) {
  842. old.snapshot.setClean(snapshot);
  843. return old;
  844. }
  845. for (PackFile p : forReuse.values()) {
  846. p.close();
  847. }
  848. if (list.isEmpty())
  849. return new PackList(snapshot, NO_PACKS.packs);
  850. final PackFile[] r = list.toArray(new PackFile[0]);
  851. Arrays.sort(r, PackFile.SORT);
  852. return new PackList(snapshot, r);
  853. }
  854. private static Map<String, PackFile> reuseMap(PackList old) {
  855. final Map<String, PackFile> forReuse = new HashMap<>();
  856. for (PackFile p : old.packs) {
  857. if (p.invalid()) {
  858. // The pack instance is corrupted, and cannot be safely used
  859. // again. Do not include it in our reuse map.
  860. //
  861. p.close();
  862. continue;
  863. }
  864. final PackFile prior = forReuse.put(p.getPackFile().getName(), p);
  865. if (prior != null) {
  866. // This should never occur. It should be impossible for us
  867. // to have two pack files with the same name, as all of them
  868. // came out of the same directory. If it does, we promised to
  869. // close any PackFiles we did not reuse, so close the second,
  870. // readers are likely to be actively using the first.
  871. //
  872. forReuse.put(prior.getPackFile().getName(), prior);
  873. p.close();
  874. }
  875. }
  876. return forReuse;
  877. }
  878. private Set<String> listPackDirectory() {
  879. final String[] nameList = packDirectory.list();
  880. if (nameList == null)
  881. return Collections.emptySet();
  882. final Set<String> nameSet = new HashSet<>(nameList.length << 1);
  883. for (String name : nameList) {
  884. if (name.startsWith("pack-")) //$NON-NLS-1$
  885. nameSet.add(name);
  886. }
  887. return nameSet;
  888. }
  889. void closeAllPackHandles(File packFile) {
  890. // if the packfile already exists (because we are rewriting a
  891. // packfile for the same set of objects maybe with different
  892. // PackConfig) then make sure we get rid of all handles on the file.
  893. // Windows will not allow for rename otherwise.
  894. if (packFile.exists()) {
  895. for (PackFile p : getPacks()) {
  896. if (packFile.getPath().equals(p.getPackFile().getPath())) {
  897. p.close();
  898. break;
  899. }
  900. }
  901. }
  902. }
  903. AlternateHandle[] myAlternates() {
  904. AlternateHandle[] alt = alternates.get();
  905. if (alt == null) {
  906. synchronized (alternates) {
  907. alt = alternates.get();
  908. if (alt == null) {
  909. try {
  910. alt = loadAlternates();
  911. } catch (IOException e) {
  912. alt = new AlternateHandle[0];
  913. }
  914. alternates.set(alt);
  915. }
  916. }
  917. }
  918. return alt;
  919. }
  920. Set<AlternateHandle.Id> addMe(Set<AlternateHandle.Id> skips) {
  921. if (skips == null) {
  922. skips = new HashSet<>();
  923. }
  924. skips.add(handle.getId());
  925. return skips;
  926. }
  927. private AlternateHandle[] loadAlternates() throws IOException {
  928. final List<AlternateHandle> l = new ArrayList<>(4);
  929. try (BufferedReader br = open(alternatesFile)) {
  930. String line;
  931. while ((line = br.readLine()) != null) {
  932. l.add(openAlternate(line));
  933. }
  934. }
  935. return l.toArray(new AlternateHandle[0]);
  936. }
  937. private static BufferedReader open(File f)
  938. throws IOException, FileNotFoundException {
  939. return Files.newBufferedReader(f.toPath(), UTF_8);
  940. }
  941. private AlternateHandle openAlternate(String location)
  942. throws IOException {
  943. final File objdir = fs.resolve(objects, location);
  944. return openAlternate(objdir);
  945. }
  946. private AlternateHandle openAlternate(File objdir) throws IOException {
  947. final File parent = objdir.getParentFile();
  948. if (FileKey.isGitRepository(parent, fs)) {
  949. FileKey key = FileKey.exact(parent, fs);
  950. FileRepository db = (FileRepository) RepositoryCache.open(key);
  951. return new AlternateRepository(db);
  952. }
  953. ObjectDirectory db = new ObjectDirectory(config, objdir, null, fs, null);
  954. return new AlternateHandle(db);
  955. }
  956. /**
  957. * {@inheritDoc}
  958. * <p>
  959. * Compute the location of a loose object file.
  960. */
  961. @Override
  962. public File fileFor(AnyObjectId objectId) {
  963. String n = objectId.name();
  964. String d = n.substring(0, 2);
  965. String f = n.substring(2);
  966. return new File(new File(getDirectory(), d), f);
  967. }
  968. static final class PackList {
  969. /** State just before reading the pack directory. */
  970. final FileSnapshot snapshot;
  971. /** All known packs, sorted by {@link PackFile#SORT}. */
  972. final PackFile[] packs;
  973. PackList(FileSnapshot monitor, PackFile[] packs) {
  974. this.snapshot = monitor;
  975. this.packs = packs;
  976. }
  977. }
  978. static class AlternateHandle {
  979. static class Id {
  980. String alternateId;
  981. public Id(File object) {
  982. try {
  983. this.alternateId = object.getCanonicalPath();
  984. } catch (Exception e) {
  985. alternateId = null;
  986. }
  987. }
  988. @Override
  989. public boolean equals(Object o) {
  990. if (o == this) {
  991. return true;
  992. }
  993. if (o == null || !(o instanceof Id)) {
  994. return false;
  995. }
  996. Id aId = (Id) o;
  997. return Objects.equals(alternateId, aId.alternateId);
  998. }
  999. @Override
  1000. public int hashCode() {
  1001. if (alternateId == null) {
  1002. return 1;
  1003. }
  1004. return alternateId.hashCode();
  1005. }
  1006. }
  1007. final ObjectDirectory db;
  1008. AlternateHandle(ObjectDirectory db) {
  1009. this.db = db;
  1010. }
  1011. void close() {
  1012. db.close();
  1013. }
  1014. public Id getId(){
  1015. return db.getAlternateId();
  1016. }
  1017. }
  1018. static class AlternateRepository extends AlternateHandle {
  1019. final FileRepository repository;
  1020. AlternateRepository(FileRepository r) {
  1021. super(r.getObjectDatabase());
  1022. repository = r;
  1023. }
  1024. @Override
  1025. void close() {
  1026. repository.close();
  1027. }
  1028. }
  1029. /** {@inheritDoc} */
  1030. @Override
  1031. public ObjectDatabase newCachedDatabase() {
  1032. return newCachedFileObjectDatabase();
  1033. }
  1034. CachedObjectDirectory newCachedFileObjectDatabase() {
  1035. return new CachedObjectDirectory(this);
  1036. }
  1037. AlternateHandle.Id getAlternateId() {
  1038. return new AlternateHandle.Id(objects);
  1039. }
  1040. }