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

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