您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

ObjectDirectory.java 33KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170
  1. /*
  2. * Copyright (C) 2009, Google Inc.
  3. * and other copyright owners as documented in the project's IP log.
  4. *
  5. * This program and the accompanying materials are made available
  6. * under the terms of the Eclipse Distribution License v1.0 which
  7. * accompanies this distribution, is reproduced below, and is
  8. * available at http://www.eclipse.org/org/documents/edl-v10.php
  9. *
  10. * All rights reserved.
  11. *
  12. * Redistribution and use in source and binary forms, with or
  13. * without modification, are permitted provided that the following
  14. * conditions are met:
  15. *
  16. * - Redistributions of source code must retain the above copyright
  17. * notice, this list of conditions and the following disclaimer.
  18. *
  19. * - Redistributions in binary form must reproduce the above
  20. * copyright notice, this list of conditions and the following
  21. * disclaimer in the documentation and/or other materials provided
  22. * with the distribution.
  23. *
  24. * - Neither the name of the Eclipse Foundation, Inc. nor the
  25. * names of its contributors may be used to endorse or promote
  26. * products derived from this software without specific prior
  27. * written permission.
  28. *
  29. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  30. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  31. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  32. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  33. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  34. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  35. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  36. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  37. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  38. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  39. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  40. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  41. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  42. */
  43. package org.eclipse.jgit.internal.storage.file;
  44. import static org.eclipse.jgit.internal.storage.pack.PackExt.INDEX;
  45. import static org.eclipse.jgit.internal.storage.pack.PackExt.PACK;
  46. import java.io.BufferedReader;
  47. import java.io.File;
  48. import java.io.FileInputStream;
  49. import java.io.FileNotFoundException;
  50. import java.io.FileReader;
  51. import java.io.IOException;
  52. import java.nio.file.AtomicMoveNotSupportedException;
  53. import java.nio.file.Files;
  54. import java.nio.file.StandardCopyOption;
  55. import java.text.MessageFormat;
  56. import java.util.ArrayList;
  57. import java.util.Arrays;
  58. import java.util.Collection;
  59. import java.util.Collections;
  60. import java.util.HashMap;
  61. import java.util.HashSet;
  62. import java.util.List;
  63. import java.util.Map;
  64. import java.util.Objects;
  65. import java.util.Set;
  66. import java.util.concurrent.atomic.AtomicReference;
  67. import org.eclipse.jgit.errors.CorruptObjectException;
  68. import org.eclipse.jgit.errors.PackInvalidException;
  69. import org.eclipse.jgit.errors.PackMismatchException;
  70. import org.eclipse.jgit.internal.JGitText;
  71. import org.eclipse.jgit.internal.storage.pack.ObjectToPack;
  72. import org.eclipse.jgit.internal.storage.pack.PackExt;
  73. import org.eclipse.jgit.internal.storage.pack.PackWriter;
  74. import org.eclipse.jgit.lib.AbbreviatedObjectId;
  75. import org.eclipse.jgit.lib.AnyObjectId;
  76. import org.eclipse.jgit.lib.Config;
  77. import org.eclipse.jgit.lib.ConfigConstants;
  78. import org.eclipse.jgit.lib.Constants;
  79. import org.eclipse.jgit.lib.ObjectDatabase;
  80. import org.eclipse.jgit.lib.ObjectId;
  81. import org.eclipse.jgit.lib.ObjectLoader;
  82. import org.eclipse.jgit.lib.RepositoryCache;
  83. import org.eclipse.jgit.lib.RepositoryCache.FileKey;
  84. import org.eclipse.jgit.util.FS;
  85. import org.eclipse.jgit.util.FileUtils;
  86. import org.slf4j.Logger;
  87. import org.slf4j.LoggerFactory;
  88. /**
  89. * Traditional file system based {@link 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 ObjectId}, or are stored in compressed containers known as
  94. * {@link PackFile}s.
  95. * <p>
  96. * Optionally an object database can reference one or more alternates; other
  97. * ObjectDatabase instances that are searched in addition to the current
  98. * database.
  99. * <p>
  100. * Databases are divided into two halves: a half that is considered to be fast
  101. * to search (the {@code PackFile}s), and a half that is considered to be slow
  102. * to search (loose objects). When alternates are present the fast half is fully
  103. * searched (recursively through all alternates) before the slow half is
  104. * considered.
  105. */
  106. public class ObjectDirectory extends FileObjectDatabase {
  107. private final static Logger LOG = LoggerFactory
  108. .getLogger(ObjectDirectory.class);
  109. private static final PackList NO_PACKS = new PackList(
  110. FileSnapshot.DIRTY, new PackFile[0]);
  111. /** Maximum number of candidates offered as resolutions of abbreviation. */
  112. private static final int RESOLVE_ABBREV_LIMIT = 256;
  113. private final AlternateHandle handle = new AlternateHandle(this);
  114. private final Config config;
  115. private final File objects;
  116. private final File infoDirectory;
  117. private final File packDirectory;
  118. private final File preservedDirectory;
  119. private final File alternatesFile;
  120. private final AtomicReference<PackList> packList;
  121. private final FS fs;
  122. private final AtomicReference<AlternateHandle[]> alternates;
  123. private final UnpackedObjectCache unpackedObjectCache;
  124. private final File shallowFile;
  125. private FileSnapshot shallowFileSnapshot = FileSnapshot.DIRTY;
  126. private Set<ObjectId> shallowCommitsIds;
  127. /**
  128. * Initialize a reference to an on-disk object directory.
  129. *
  130. * @param cfg
  131. * configuration this directory consults for write settings.
  132. * @param dir
  133. * the location of the <code>objects</code> directory.
  134. * @param alternatePaths
  135. * a list of alternate object directories
  136. * @param fs
  137. * the file system abstraction which will be necessary to perform
  138. * certain file system operations.
  139. * @param shallowFile
  140. * file which contains IDs of shallow commits, null if shallow
  141. * commits handling should be turned off
  142. * @throws 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. /**
  167. * @return the location of the <code>objects</code> directory.
  168. */
  169. @Override
  170. public final File getDirectory() {
  171. return objects;
  172. }
  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. * @return the location of the <code>preserved</code> directory.
  182. */
  183. public final File getPreservedDirectory() {
  184. return preservedDirectory;
  185. }
  186. @Override
  187. public boolean exists() {
  188. return fs.exists(objects);
  189. }
  190. @Override
  191. public void create() throws IOException {
  192. FileUtils.mkdirs(objects);
  193. FileUtils.mkdir(infoDirectory);
  194. FileUtils.mkdir(packDirectory);
  195. }
  196. @Override
  197. public ObjectDirectoryInserter newInserter() {
  198. return new ObjectDirectoryInserter(this, config);
  199. }
  200. /**
  201. * Create a new inserter that inserts all objects as pack files, not loose
  202. * objects.
  203. *
  204. * @return new inserter.
  205. */
  206. public PackInserter newPackInserter() {
  207. return new PackInserter(this);
  208. }
  209. @Override
  210. public void close() {
  211. unpackedObjectCache.clear();
  212. final PackList packs = packList.get();
  213. if (packs != NO_PACKS && packList.compareAndSet(packs, NO_PACKS)) {
  214. for (PackFile p : packs.packs)
  215. p.close();
  216. }
  217. // Fully close all loaded alternates and clear the alternate list.
  218. AlternateHandle[] alt = alternates.get();
  219. if (alt != null && alternates.compareAndSet(alt, null)) {
  220. for(final AlternateHandle od : alt)
  221. od.close();
  222. }
  223. }
  224. /**
  225. * @return unmodifiable collection of all known pack files local to this
  226. * directory. Most recent packs are presented first. Packs most
  227. * likely to contain more recent objects appear before packs
  228. * containing objects referenced by commits further back in the
  229. * history of the repository.
  230. */
  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. * Add a single existing pack to the list of available pack files.
  241. *
  242. * @param pack
  243. * path of the pack file to open.
  244. * @return the pack that was opened and added to the database.
  245. * @throws IOException
  246. * index file could not be opened, read, or is not recognized as
  247. * a Git pack file index.
  248. */
  249. @Override
  250. public PackFile openPack(final File pack)
  251. throws IOException {
  252. final String p = pack.getName();
  253. if (p.length() != 50 || !p.startsWith("pack-") || !p.endsWith(".pack")) //$NON-NLS-1$ //$NON-NLS-2$
  254. throw new IOException(MessageFormat.format(JGitText.get().notAValidPack, pack));
  255. // The pack and index are assumed to exist. The existence of other
  256. // extensions needs to be explicitly checked.
  257. //
  258. int extensions = PACK.getBit() | INDEX.getBit();
  259. final String base = p.substring(0, p.length() - 4);
  260. for (PackExt ext : PackExt.values()) {
  261. if ((extensions & ext.getBit()) == 0) {
  262. final String name = base + ext.getExtension();
  263. if (new File(pack.getParentFile(), name).exists())
  264. extensions |= ext.getBit();
  265. }
  266. }
  267. PackFile res = new PackFile(pack, extensions);
  268. insertPack(res);
  269. return res;
  270. }
  271. @Override
  272. public String toString() {
  273. return "ObjectDirectory[" + getDirectory() + "]"; //$NON-NLS-1$ //$NON-NLS-2$
  274. }
  275. @Override
  276. public boolean has(AnyObjectId objectId) {
  277. return unpackedObjectCache.isUnpacked(objectId)
  278. || hasPackedInSelfOrAlternate(objectId, null)
  279. || hasLooseInSelfOrAlternate(objectId, null);
  280. }
  281. private boolean hasPackedInSelfOrAlternate(AnyObjectId objectId,
  282. Set<AlternateHandle.Id> skips) {
  283. if (hasPackedObject(objectId)) {
  284. return true;
  285. }
  286. skips = addMe(skips);
  287. for (AlternateHandle alt : myAlternates()) {
  288. if (!skips.contains(alt.getId())) {
  289. if (alt.db.hasPackedInSelfOrAlternate(objectId, skips)) {
  290. return true;
  291. }
  292. }
  293. }
  294. return false;
  295. }
  296. private boolean hasLooseInSelfOrAlternate(AnyObjectId objectId,
  297. Set<AlternateHandle.Id> skips) {
  298. if (fileFor(objectId).exists()) {
  299. return true;
  300. }
  301. skips = addMe(skips);
  302. for (AlternateHandle alt : myAlternates()) {
  303. if (!skips.contains(alt.getId())) {
  304. if (alt.db.hasLooseInSelfOrAlternate(objectId, skips)) {
  305. return true;
  306. }
  307. }
  308. }
  309. return false;
  310. }
  311. boolean hasPackedObject(AnyObjectId objectId) {
  312. PackList pList;
  313. do {
  314. pList = packList.get();
  315. for (PackFile p : pList.packs) {
  316. try {
  317. if (p.hasObject(objectId))
  318. return true;
  319. } catch (IOException e) {
  320. // The hasObject call should have only touched the index,
  321. // so any failure here indicates the index is unreadable
  322. // by this process, and the pack is likewise not readable.
  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 (final 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. // Assume the pack is corrupted, and remove it from the list.
  598. removePack(p);
  599. } else if (e instanceof FileNotFoundException) {
  600. if (p.getPackFile().exists()) {
  601. errTmpl = JGitText.get().packInaccessible;
  602. transientErrorCount = p.incrementTransientErrorCount();
  603. } else {
  604. warnTmpl = JGitText.get().packWasDeleted;
  605. removePack(p);
  606. }
  607. } else if (FileUtils.isStaleFileHandleInCausalChain(e)) {
  608. warnTmpl = JGitText.get().packHandleIsStale;
  609. removePack(p);
  610. } else {
  611. transientErrorCount = p.incrementTransientErrorCount();
  612. }
  613. if (warnTmpl != null) {
  614. if (LOG.isDebugEnabled()) {
  615. LOG.debug(MessageFormat.format(warnTmpl,
  616. p.getPackFile().getAbsolutePath()), e);
  617. } else {
  618. LOG.warn(MessageFormat.format(warnTmpl,
  619. p.getPackFile().getAbsolutePath()));
  620. }
  621. } else {
  622. if (doLogExponentialBackoff(transientErrorCount)) {
  623. // Don't remove the pack from the list, as the error may be
  624. // transient.
  625. LOG.error(MessageFormat.format(errTmpl,
  626. p.getPackFile().getAbsolutePath()),
  627. Integer.valueOf(transientErrorCount), e);
  628. }
  629. }
  630. }
  631. /**
  632. * @param n
  633. * count of consecutive failures
  634. * @return @{code true} if i is a power of 2
  635. */
  636. private boolean doLogExponentialBackoff(int n) {
  637. return (n & (n - 1)) == 0;
  638. }
  639. @Override
  640. InsertLooseObjectResult insertUnpackedObject(File tmp, ObjectId id,
  641. boolean createDuplicate) throws IOException {
  642. // If the object is already in the repository, remove temporary file.
  643. //
  644. if (unpackedObjectCache.isUnpacked(id)) {
  645. FileUtils.delete(tmp, FileUtils.RETRY);
  646. return InsertLooseObjectResult.EXISTS_LOOSE;
  647. }
  648. if (!createDuplicate && has(id)) {
  649. FileUtils.delete(tmp, FileUtils.RETRY);
  650. return InsertLooseObjectResult.EXISTS_PACKED;
  651. }
  652. final File dst = fileFor(id);
  653. if (dst.exists()) {
  654. // We want to be extra careful and avoid replacing an object
  655. // that already exists. We can't be sure renameTo() would
  656. // fail on all platforms if dst exists, so we check first.
  657. //
  658. FileUtils.delete(tmp, FileUtils.RETRY);
  659. return InsertLooseObjectResult.EXISTS_LOOSE;
  660. }
  661. try {
  662. Files.move(FileUtils.toPath(tmp), FileUtils.toPath(dst),
  663. StandardCopyOption.ATOMIC_MOVE);
  664. dst.setReadOnly();
  665. unpackedObjectCache.add(id);
  666. return InsertLooseObjectResult.INSERTED;
  667. } catch (AtomicMoveNotSupportedException e) {
  668. LOG.error(e.getMessage(), e);
  669. } catch (IOException e) {
  670. // ignore
  671. }
  672. // Maybe the directory doesn't exist yet as the object
  673. // directories are always lazily created. Note that we
  674. // try the rename first as the directory likely does exist.
  675. //
  676. FileUtils.mkdir(dst.getParentFile(), true);
  677. try {
  678. Files.move(FileUtils.toPath(tmp), FileUtils.toPath(dst),
  679. StandardCopyOption.ATOMIC_MOVE);
  680. dst.setReadOnly();
  681. unpackedObjectCache.add(id);
  682. return InsertLooseObjectResult.INSERTED;
  683. } catch (AtomicMoveNotSupportedException e) {
  684. LOG.error(e.getMessage(), e);
  685. } catch (IOException e) {
  686. LOG.debug(e.getMessage(), e);
  687. }
  688. if (!createDuplicate && has(id)) {
  689. FileUtils.delete(tmp, FileUtils.RETRY);
  690. return InsertLooseObjectResult.EXISTS_PACKED;
  691. }
  692. // The object failed to be renamed into its proper
  693. // location and it doesn't exist in the repository
  694. // either. We really don't know what went wrong, so
  695. // fail.
  696. //
  697. FileUtils.delete(tmp, FileUtils.RETRY);
  698. return InsertLooseObjectResult.FAILURE;
  699. }
  700. private boolean searchPacksAgain(PackList old) {
  701. // Whether to trust the pack folder's modification time. If set
  702. // to false we will always scan the .git/objects/pack folder to
  703. // check for new pack files. If set to true (default) we use the
  704. // lastmodified attribute of the folder and assume that no new
  705. // pack files can be in this folder if his modification time has
  706. // not changed.
  707. boolean trustFolderStat = config.getBoolean(
  708. ConfigConstants.CONFIG_CORE_SECTION,
  709. ConfigConstants.CONFIG_KEY_TRUSTFOLDERSTAT, true);
  710. return ((!trustFolderStat) || old.snapshot.isModified(packDirectory))
  711. && old != scanPacks(old);
  712. }
  713. @Override
  714. Config getConfig() {
  715. return config;
  716. }
  717. @Override
  718. FS getFS() {
  719. return fs;
  720. }
  721. @Override
  722. Set<ObjectId> getShallowCommits() throws IOException {
  723. if (shallowFile == null || !shallowFile.isFile())
  724. return Collections.emptySet();
  725. if (shallowFileSnapshot == null
  726. || shallowFileSnapshot.isModified(shallowFile)) {
  727. shallowCommitsIds = new HashSet<>();
  728. final BufferedReader reader = open(shallowFile);
  729. try {
  730. String line;
  731. while ((line = reader.readLine()) != null) {
  732. try {
  733. shallowCommitsIds.add(ObjectId.fromString(line));
  734. } catch (IllegalArgumentException ex) {
  735. throw new IOException(MessageFormat
  736. .format(JGitText.get().badShallowLine, line));
  737. }
  738. }
  739. } finally {
  740. reader.close();
  741. }
  742. shallowFileSnapshot = FileSnapshot.save(shallowFile);
  743. }
  744. return shallowCommitsIds;
  745. }
  746. private void insertPack(final PackFile pf) {
  747. PackList o, n;
  748. do {
  749. o = packList.get();
  750. // If the pack in question is already present in the list
  751. // (picked up by a concurrent thread that did a scan?) we
  752. // do not want to insert it a second time.
  753. //
  754. final PackFile[] oldList = o.packs;
  755. final String name = pf.getPackFile().getName();
  756. for (PackFile p : oldList) {
  757. if (name.equals(p.getPackFile().getName()))
  758. return;
  759. }
  760. final PackFile[] newList = new PackFile[1 + oldList.length];
  761. newList[0] = pf;
  762. System.arraycopy(oldList, 0, newList, 1, oldList.length);
  763. n = new PackList(o.snapshot, newList);
  764. } while (!packList.compareAndSet(o, n));
  765. }
  766. private void removePack(final PackFile deadPack) {
  767. PackList o, n;
  768. do {
  769. o = packList.get();
  770. final PackFile[] oldList = o.packs;
  771. final int j = indexOf(oldList, deadPack);
  772. if (j < 0)
  773. break;
  774. final PackFile[] newList = new PackFile[oldList.length - 1];
  775. System.arraycopy(oldList, 0, newList, 0, j);
  776. System.arraycopy(oldList, j + 1, newList, j, newList.length - j);
  777. n = new PackList(o.snapshot, newList);
  778. } while (!packList.compareAndSet(o, n));
  779. deadPack.close();
  780. }
  781. private static int indexOf(final PackFile[] list, final PackFile pack) {
  782. for (int i = 0; i < list.length; i++) {
  783. if (list[i] == pack)
  784. return i;
  785. }
  786. return -1;
  787. }
  788. private PackList scanPacks(final PackList original) {
  789. synchronized (packList) {
  790. PackList o, n;
  791. do {
  792. o = packList.get();
  793. if (o != original) {
  794. // Another thread did the scan for us, while we
  795. // were blocked on the monitor above.
  796. //
  797. return o;
  798. }
  799. n = scanPacksImpl(o);
  800. if (n == o)
  801. return n;
  802. } while (!packList.compareAndSet(o, n));
  803. return n;
  804. }
  805. }
  806. private PackList scanPacksImpl(final PackList old) {
  807. final Map<String, PackFile> forReuse = reuseMap(old);
  808. final FileSnapshot snapshot = FileSnapshot.save(packDirectory);
  809. final Set<String> names = listPackDirectory();
  810. final List<PackFile> list = new ArrayList<>(names.size() >> 2);
  811. boolean foundNew = false;
  812. for (final String indexName : names) {
  813. // Must match "pack-[0-9a-f]{40}.idx" to be an index.
  814. //
  815. if (indexName.length() != 49 || !indexName.endsWith(".idx")) //$NON-NLS-1$
  816. continue;
  817. final String base = indexName.substring(0, indexName.length() - 3);
  818. int extensions = 0;
  819. for (PackExt ext : PackExt.values()) {
  820. if (names.contains(base + ext.getExtension()))
  821. extensions |= ext.getBit();
  822. }
  823. if ((extensions & PACK.getBit()) == 0) {
  824. // Sometimes C Git's HTTP fetch transport leaves a
  825. // .idx file behind and does not download the .pack.
  826. // We have to skip over such useless indexes.
  827. //
  828. continue;
  829. }
  830. final String packName = base + PACK.getExtension();
  831. final PackFile oldPack = forReuse.remove(packName);
  832. if (oldPack != null) {
  833. list.add(oldPack);
  834. continue;
  835. }
  836. final File packFile = new File(packDirectory, packName);
  837. list.add(new PackFile(packFile, extensions));
  838. foundNew = true;
  839. }
  840. // If we did not discover any new files, the modification time was not
  841. // changed, and we did not remove any files, then the set of files is
  842. // the same as the set we were given. Instead of building a new object
  843. // return the same collection.
  844. //
  845. if (!foundNew && forReuse.isEmpty() && snapshot.equals(old.snapshot)) {
  846. old.snapshot.setClean(snapshot);
  847. return old;
  848. }
  849. for (final PackFile p : forReuse.values()) {
  850. p.close();
  851. }
  852. if (list.isEmpty())
  853. return new PackList(snapshot, NO_PACKS.packs);
  854. final PackFile[] r = list.toArray(new PackFile[list.size()]);
  855. Arrays.sort(r, PackFile.SORT);
  856. return new PackList(snapshot, r);
  857. }
  858. private static Map<String, PackFile> reuseMap(final PackList old) {
  859. final Map<String, PackFile> forReuse = new HashMap<>();
  860. for (final PackFile p : old.packs) {
  861. if (p.invalid()) {
  862. // The pack instance is corrupted, and cannot be safely used
  863. // again. Do not include it in our reuse map.
  864. //
  865. p.close();
  866. continue;
  867. }
  868. final PackFile prior = forReuse.put(p.getPackFile().getName(), p);
  869. if (prior != null) {
  870. // This should never occur. It should be impossible for us
  871. // to have two pack files with the same name, as all of them
  872. // came out of the same directory. If it does, we promised to
  873. // close any PackFiles we did not reuse, so close the second,
  874. // readers are likely to be actively using the first.
  875. //
  876. forReuse.put(prior.getPackFile().getName(), prior);
  877. p.close();
  878. }
  879. }
  880. return forReuse;
  881. }
  882. private Set<String> listPackDirectory() {
  883. final String[] nameList = packDirectory.list();
  884. if (nameList == null)
  885. return Collections.emptySet();
  886. final Set<String> nameSet = new HashSet<>(nameList.length << 1);
  887. for (final String name : nameList) {
  888. if (name.startsWith("pack-")) //$NON-NLS-1$
  889. nameSet.add(name);
  890. }
  891. return nameSet;
  892. }
  893. void closeAllPackHandles(File packFile) {
  894. // if the packfile already exists (because we are rewriting a
  895. // packfile for the same set of objects maybe with different
  896. // PackConfig) then make sure we get rid of all handles on the file.
  897. // Windows will not allow for rename otherwise.
  898. if (packFile.exists()) {
  899. for (PackFile p : getPacks()) {
  900. if (packFile.getPath().equals(p.getPackFile().getPath())) {
  901. p.close();
  902. break;
  903. }
  904. }
  905. }
  906. }
  907. AlternateHandle[] myAlternates() {
  908. AlternateHandle[] alt = alternates.get();
  909. if (alt == null) {
  910. synchronized (alternates) {
  911. alt = alternates.get();
  912. if (alt == null) {
  913. try {
  914. alt = loadAlternates();
  915. } catch (IOException e) {
  916. alt = new AlternateHandle[0];
  917. }
  918. alternates.set(alt);
  919. }
  920. }
  921. }
  922. return alt;
  923. }
  924. Set<AlternateHandle.Id> addMe(Set<AlternateHandle.Id> skips) {
  925. if (skips == null) {
  926. skips = new HashSet<>();
  927. }
  928. skips.add(handle.getId());
  929. return skips;
  930. }
  931. private AlternateHandle[] loadAlternates() throws IOException {
  932. final List<AlternateHandle> l = new ArrayList<>(4);
  933. final BufferedReader br = open(alternatesFile);
  934. try {
  935. String line;
  936. while ((line = br.readLine()) != null) {
  937. l.add(openAlternate(line));
  938. }
  939. } finally {
  940. br.close();
  941. }
  942. return l.toArray(new AlternateHandle[l.size()]);
  943. }
  944. private static BufferedReader open(final File f)
  945. throws FileNotFoundException {
  946. return new BufferedReader(new FileReader(f));
  947. }
  948. private AlternateHandle openAlternate(final String location)
  949. throws IOException {
  950. final File objdir = fs.resolve(objects, location);
  951. return openAlternate(objdir);
  952. }
  953. private AlternateHandle openAlternate(File objdir) throws IOException {
  954. final File parent = objdir.getParentFile();
  955. if (FileKey.isGitRepository(parent, fs)) {
  956. FileKey key = FileKey.exact(parent, fs);
  957. FileRepository db = (FileRepository) RepositoryCache.open(key);
  958. return new AlternateRepository(db);
  959. }
  960. ObjectDirectory db = new ObjectDirectory(config, objdir, null, fs, null);
  961. return new AlternateHandle(db);
  962. }
  963. /**
  964. * Compute the location of a loose object file.
  965. *
  966. * @param objectId
  967. * identity of the loose object to map to the directory.
  968. * @return location of the object, if it were to exist as a loose object.
  969. */
  970. @Override
  971. public File fileFor(AnyObjectId objectId) {
  972. String n = objectId.name();
  973. String d = n.substring(0, 2);
  974. String f = n.substring(2);
  975. return new File(new File(getDirectory(), d), f);
  976. }
  977. private static final class PackList {
  978. /** State just before reading the pack directory. */
  979. final FileSnapshot snapshot;
  980. /** All known packs, sorted by {@link PackFile#SORT}. */
  981. final PackFile[] packs;
  982. PackList(final FileSnapshot monitor, final PackFile[] packs) {
  983. this.snapshot = monitor;
  984. this.packs = packs;
  985. }
  986. }
  987. static class AlternateHandle {
  988. static class Id {
  989. String alternateId;
  990. public Id(File object) {
  991. try {
  992. this.alternateId = object.getCanonicalPath();
  993. } catch (Exception e) {
  994. alternateId = null;
  995. }
  996. }
  997. @Override
  998. public boolean equals(Object o) {
  999. if (o == this) {
  1000. return true;
  1001. }
  1002. if (o == null || !(o instanceof Id)) {
  1003. return false;
  1004. }
  1005. Id aId = (Id) o;
  1006. return Objects.equals(alternateId, aId.alternateId);
  1007. }
  1008. @Override
  1009. public int hashCode() {
  1010. if (alternateId == null) {
  1011. return 1;
  1012. }
  1013. return alternateId.hashCode();
  1014. }
  1015. }
  1016. final ObjectDirectory db;
  1017. AlternateHandle(ObjectDirectory db) {
  1018. this.db = db;
  1019. }
  1020. void close() {
  1021. db.close();
  1022. }
  1023. public Id getId(){
  1024. return db.getAlternateId();
  1025. }
  1026. }
  1027. static class AlternateRepository extends AlternateHandle {
  1028. final FileRepository repository;
  1029. AlternateRepository(FileRepository r) {
  1030. super(r.getObjectDatabase());
  1031. repository = r;
  1032. }
  1033. @Override
  1034. void close() {
  1035. repository.close();
  1036. }
  1037. }
  1038. @Override
  1039. public ObjectDatabase newCachedDatabase() {
  1040. return newCachedFileObjectDatabase();
  1041. }
  1042. CachedObjectDirectory newCachedFileObjectDatabase() {
  1043. return new CachedObjectDirectory(this);
  1044. }
  1045. AlternateHandle.Id getAlternateId() {
  1046. return new AlternateHandle.Id(objects);
  1047. }
  1048. }