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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664
  1. /*
  2. * Copyright (C) 2009, Google Inc. and others
  3. *
  4. * This program and the accompanying materials are made available under the
  5. * terms of the Eclipse Distribution License v. 1.0 which is available at
  6. * https://www.eclipse.org/org/documents/edl-v10.php.
  7. *
  8. * SPDX-License-Identifier: BSD-3-Clause
  9. */
  10. package org.eclipse.jgit.internal.storage.file;
  11. import static java.nio.charset.StandardCharsets.UTF_8;
  12. import static org.eclipse.jgit.internal.storage.pack.PackExt.INDEX;
  13. import static org.eclipse.jgit.internal.storage.pack.PackExt.PACK;
  14. import java.io.BufferedReader;
  15. import java.io.File;
  16. import java.io.FileNotFoundException;
  17. import java.io.IOException;
  18. import java.nio.file.Files;
  19. import java.text.MessageFormat;
  20. import java.util.ArrayList;
  21. import java.util.Collection;
  22. import java.util.Collections;
  23. import java.util.HashSet;
  24. import java.util.List;
  25. import java.util.Objects;
  26. import java.util.Set;
  27. import java.util.concurrent.atomic.AtomicReference;
  28. import org.eclipse.jgit.internal.JGitText;
  29. import org.eclipse.jgit.internal.storage.pack.ObjectToPack;
  30. import org.eclipse.jgit.internal.storage.pack.PackExt;
  31. import org.eclipse.jgit.internal.storage.pack.PackWriter;
  32. import org.eclipse.jgit.lib.AbbreviatedObjectId;
  33. import org.eclipse.jgit.lib.AnyObjectId;
  34. import org.eclipse.jgit.lib.Config;
  35. import org.eclipse.jgit.lib.Constants;
  36. import org.eclipse.jgit.lib.ObjectDatabase;
  37. import org.eclipse.jgit.lib.ObjectId;
  38. import org.eclipse.jgit.lib.ObjectLoader;
  39. import org.eclipse.jgit.lib.RepositoryCache;
  40. import org.eclipse.jgit.lib.RepositoryCache.FileKey;
  41. import org.eclipse.jgit.util.FS;
  42. import org.eclipse.jgit.util.FileUtils;
  43. /**
  44. * Traditional file system based {@link org.eclipse.jgit.lib.ObjectDatabase}.
  45. * <p>
  46. * This is the classical object database representation for a Git repository,
  47. * where objects are stored loose by hashing them into directories by their
  48. * {@link org.eclipse.jgit.lib.ObjectId}, or are stored in compressed containers
  49. * known as {@link org.eclipse.jgit.internal.storage.file.Pack}s.
  50. * <p>
  51. * Optionally an object database can reference one or more alternates; other
  52. * ObjectDatabase instances that are searched in addition to the current
  53. * database.
  54. * <p>
  55. * Databases are divided into two halves: a half that is considered to be fast
  56. * to search (the {@code PackFile}s), and a half that is considered to be slow
  57. * to search (loose objects). When alternates are present the fast half is fully
  58. * searched (recursively through all alternates) before the slow half is
  59. * considered.
  60. */
  61. public class ObjectDirectory extends FileObjectDatabase {
  62. /** Maximum number of candidates offered as resolutions of abbreviation. */
  63. private static final int RESOLVE_ABBREV_LIMIT = 256;
  64. private final AlternateHandle handle = new AlternateHandle(this);
  65. private final Config config;
  66. private final File objects;
  67. private final File infoDirectory;
  68. private final LooseObjects loose;
  69. private final PackDirectory packed;
  70. private final File preservedDirectory;
  71. private final File alternatesFile;
  72. private final FS fs;
  73. private final AtomicReference<AlternateHandle[]> alternates;
  74. private final File shallowFile;
  75. private FileSnapshot shallowFileSnapshot = FileSnapshot.DIRTY;
  76. private Set<ObjectId> shallowCommitsIds;
  77. /**
  78. * Initialize a reference to an on-disk object directory.
  79. *
  80. * @param cfg
  81. * configuration this directory consults for write settings.
  82. * @param dir
  83. * the location of the <code>objects</code> directory.
  84. * @param alternatePaths
  85. * a list of alternate object directories
  86. * @param fs
  87. * the file system abstraction which will be necessary to perform
  88. * certain file system operations.
  89. * @param shallowFile
  90. * file which contains IDs of shallow commits, null if shallow
  91. * commits handling should be turned off
  92. * @throws java.io.IOException
  93. * an alternate object cannot be opened.
  94. */
  95. public ObjectDirectory(final Config cfg, final File dir,
  96. File[] alternatePaths, FS fs, File shallowFile) throws IOException {
  97. config = cfg;
  98. objects = dir;
  99. infoDirectory = new File(objects, "info"); //$NON-NLS-1$
  100. File packDirectory = new File(objects, "pack"); //$NON-NLS-1$
  101. preservedDirectory = new File(packDirectory, "preserved"); //$NON-NLS-1$
  102. alternatesFile = new File(objects, Constants.INFO_ALTERNATES);
  103. loose = new LooseObjects(objects);
  104. packed = new PackDirectory(config, packDirectory);
  105. this.fs = fs;
  106. this.shallowFile = shallowFile;
  107. alternates = new AtomicReference<>();
  108. if (alternatePaths != null) {
  109. AlternateHandle[] alt;
  110. alt = new AlternateHandle[alternatePaths.length];
  111. for (int i = 0; i < alternatePaths.length; i++)
  112. alt[i] = openAlternate(alternatePaths[i]);
  113. alternates.set(alt);
  114. }
  115. }
  116. /** {@inheritDoc} */
  117. @Override
  118. public final File getDirectory() {
  119. return loose.getDirectory();
  120. }
  121. /**
  122. * <p>Getter for the field <code>packDirectory</code>.</p>
  123. *
  124. * @return the location of the <code>pack</code> directory.
  125. */
  126. public final File getPackDirectory() {
  127. return packed.getDirectory();
  128. }
  129. /**
  130. * <p>Getter for the field <code>preservedDirectory</code>.</p>
  131. *
  132. * @return the location of the <code>preserved</code> directory.
  133. */
  134. public final File getPreservedDirectory() {
  135. return preservedDirectory;
  136. }
  137. /** {@inheritDoc} */
  138. @Override
  139. public boolean exists() {
  140. return fs.exists(objects);
  141. }
  142. /** {@inheritDoc} */
  143. @Override
  144. public void create() throws IOException {
  145. loose.create();
  146. FileUtils.mkdir(infoDirectory);
  147. packed.create();
  148. }
  149. /** {@inheritDoc} */
  150. @Override
  151. public ObjectDirectoryInserter newInserter() {
  152. return new ObjectDirectoryInserter(this, config);
  153. }
  154. /**
  155. * Create a new inserter that inserts all objects as pack files, not loose
  156. * objects.
  157. *
  158. * @return new inserter.
  159. */
  160. public PackInserter newPackInserter() {
  161. return new PackInserter(this);
  162. }
  163. /** {@inheritDoc} */
  164. @Override
  165. public void close() {
  166. loose.close();
  167. packed.close();
  168. // Fully close all loaded alternates and clear the alternate list.
  169. AlternateHandle[] alt = alternates.get();
  170. if (alt != null && alternates.compareAndSet(alt, null)) {
  171. for(AlternateHandle od : alt)
  172. od.close();
  173. }
  174. }
  175. /** {@inheritDoc} */
  176. @Override
  177. public Collection<Pack> getPacks() {
  178. return packed.getPacks();
  179. }
  180. /**
  181. * {@inheritDoc}
  182. * <p>
  183. * Add a single existing pack to the list of available pack files.
  184. */
  185. @Override
  186. public Pack openPack(File pack)
  187. throws IOException {
  188. final String p = pack.getName();
  189. if (p.length() != 50 || !p.startsWith("pack-") || !p.endsWith(".pack")) //$NON-NLS-1$ //$NON-NLS-2$
  190. throw new IOException(MessageFormat.format(JGitText.get().notAValidPack, pack));
  191. // The pack and index are assumed to exist. The existence of other
  192. // extensions needs to be explicitly checked.
  193. //
  194. int extensions = PACK.getBit() | INDEX.getBit();
  195. final String base = p.substring(0, p.length() - 4);
  196. for (PackExt ext : PackExt.values()) {
  197. if ((extensions & ext.getBit()) == 0) {
  198. final String name = base + ext.getExtension();
  199. if (new File(pack.getParentFile(), name).exists())
  200. extensions |= ext.getBit();
  201. }
  202. }
  203. Pack res = new Pack(pack, extensions);
  204. packed.insert(res);
  205. return res;
  206. }
  207. /** {@inheritDoc} */
  208. @Override
  209. public String toString() {
  210. return "ObjectDirectory[" + getDirectory() + "]"; //$NON-NLS-1$ //$NON-NLS-2$
  211. }
  212. /** {@inheritDoc} */
  213. @Override
  214. public boolean has(AnyObjectId objectId) {
  215. return loose.hasCached(objectId)
  216. || hasPackedInSelfOrAlternate(objectId, null)
  217. || hasLooseInSelfOrAlternate(objectId, null);
  218. }
  219. private boolean hasPackedInSelfOrAlternate(AnyObjectId objectId,
  220. Set<AlternateHandle.Id> skips) {
  221. if (hasPackedObject(objectId)) {
  222. return true;
  223. }
  224. skips = addMe(skips);
  225. for (AlternateHandle alt : myAlternates()) {
  226. if (!skips.contains(alt.getId())) {
  227. if (alt.db.hasPackedInSelfOrAlternate(objectId, skips)) {
  228. return true;
  229. }
  230. }
  231. }
  232. return false;
  233. }
  234. private boolean hasLooseInSelfOrAlternate(AnyObjectId objectId,
  235. Set<AlternateHandle.Id> skips) {
  236. if (loose.has(objectId)) {
  237. return true;
  238. }
  239. skips = addMe(skips);
  240. for (AlternateHandle alt : myAlternates()) {
  241. if (!skips.contains(alt.getId())) {
  242. if (alt.db.hasLooseInSelfOrAlternate(objectId, skips)) {
  243. return true;
  244. }
  245. }
  246. }
  247. return false;
  248. }
  249. boolean hasPackedObject(AnyObjectId objectId) {
  250. return packed.has(objectId);
  251. }
  252. @Override
  253. void resolve(Set<ObjectId> matches, AbbreviatedObjectId id)
  254. throws IOException {
  255. resolve(matches, id, null);
  256. }
  257. private void resolve(Set<ObjectId> matches, AbbreviatedObjectId id,
  258. Set<AlternateHandle.Id> skips)
  259. throws IOException {
  260. if (!packed.resolve(matches, id, RESOLVE_ABBREV_LIMIT))
  261. return;
  262. if (!loose.resolve(matches, id, RESOLVE_ABBREV_LIMIT))
  263. return;
  264. skips = addMe(skips);
  265. for (AlternateHandle alt : myAlternates()) {
  266. if (!skips.contains(alt.getId())) {
  267. alt.db.resolve(matches, id, skips);
  268. if (matches.size() > RESOLVE_ABBREV_LIMIT) {
  269. return;
  270. }
  271. }
  272. }
  273. }
  274. @Override
  275. ObjectLoader openObject(WindowCursor curs, AnyObjectId objectId)
  276. throws IOException {
  277. if (loose.hasCached(objectId)) {
  278. ObjectLoader ldr = openLooseObject(curs, objectId);
  279. if (ldr != null) {
  280. return ldr;
  281. }
  282. }
  283. ObjectLoader ldr = openPackedFromSelfOrAlternate(curs, objectId, null);
  284. if (ldr != null) {
  285. return ldr;
  286. }
  287. return openLooseFromSelfOrAlternate(curs, objectId, null);
  288. }
  289. private ObjectLoader openPackedFromSelfOrAlternate(WindowCursor curs,
  290. AnyObjectId objectId, Set<AlternateHandle.Id> skips) {
  291. ObjectLoader ldr = openPackedObject(curs, objectId);
  292. if (ldr != null) {
  293. return ldr;
  294. }
  295. skips = addMe(skips);
  296. for (AlternateHandle alt : myAlternates()) {
  297. if (!skips.contains(alt.getId())) {
  298. ldr = alt.db.openPackedFromSelfOrAlternate(curs, objectId, skips);
  299. if (ldr != null) {
  300. return ldr;
  301. }
  302. }
  303. }
  304. return null;
  305. }
  306. private ObjectLoader openLooseFromSelfOrAlternate(WindowCursor curs,
  307. AnyObjectId objectId, Set<AlternateHandle.Id> skips)
  308. throws IOException {
  309. ObjectLoader ldr = openLooseObject(curs, objectId);
  310. if (ldr != null) {
  311. return ldr;
  312. }
  313. skips = addMe(skips);
  314. for (AlternateHandle alt : myAlternates()) {
  315. if (!skips.contains(alt.getId())) {
  316. ldr = alt.db.openLooseFromSelfOrAlternate(curs, objectId, skips);
  317. if (ldr != null) {
  318. return ldr;
  319. }
  320. }
  321. }
  322. return null;
  323. }
  324. ObjectLoader openPackedObject(WindowCursor curs, AnyObjectId objectId) {
  325. return packed.open(curs, objectId);
  326. }
  327. @Override
  328. ObjectLoader openLooseObject(WindowCursor curs, AnyObjectId id)
  329. throws IOException {
  330. return loose.open(curs, id);
  331. }
  332. @Override
  333. long getObjectSize(WindowCursor curs, AnyObjectId id)
  334. throws IOException {
  335. if (loose.hasCached(id)) {
  336. long len = loose.getSize(curs, id);
  337. if (0 <= len) {
  338. return len;
  339. }
  340. }
  341. long len = getPackedSizeFromSelfOrAlternate(curs, id, null);
  342. if (0 <= len) {
  343. return len;
  344. }
  345. return getLooseSizeFromSelfOrAlternate(curs, id, null);
  346. }
  347. private long getPackedSizeFromSelfOrAlternate(WindowCursor curs,
  348. AnyObjectId id, Set<AlternateHandle.Id> skips) {
  349. long len = packed.getSize(curs, id);
  350. if (0 <= len) {
  351. return len;
  352. }
  353. skips = addMe(skips);
  354. for (AlternateHandle alt : myAlternates()) {
  355. if (!skips.contains(alt.getId())) {
  356. len = alt.db.getPackedSizeFromSelfOrAlternate(curs, id, skips);
  357. if (0 <= len) {
  358. return len;
  359. }
  360. }
  361. }
  362. return -1;
  363. }
  364. private long getLooseSizeFromSelfOrAlternate(WindowCursor curs,
  365. AnyObjectId id, Set<AlternateHandle.Id> skips) throws IOException {
  366. long len = loose.getSize(curs, id);
  367. if (0 <= len) {
  368. return len;
  369. }
  370. skips = addMe(skips);
  371. for (AlternateHandle alt : myAlternates()) {
  372. if (!skips.contains(alt.getId())) {
  373. len = alt.db.getLooseSizeFromSelfOrAlternate(curs, id, skips);
  374. if (0 <= len) {
  375. return len;
  376. }
  377. }
  378. }
  379. return -1;
  380. }
  381. @Override
  382. void selectObjectRepresentation(PackWriter packer, ObjectToPack otp,
  383. WindowCursor curs) throws IOException {
  384. selectObjectRepresentation(packer, otp, curs, null);
  385. }
  386. private void selectObjectRepresentation(PackWriter packer, ObjectToPack otp,
  387. WindowCursor curs, Set<AlternateHandle.Id> skips) throws IOException {
  388. packed.selectRepresentation(packer, otp, curs);
  389. skips = addMe(skips);
  390. for (AlternateHandle h : myAlternates()) {
  391. if (!skips.contains(h.getId())) {
  392. h.db.selectObjectRepresentation(packer, otp, curs, skips);
  393. }
  394. }
  395. }
  396. @Override
  397. InsertLooseObjectResult insertUnpackedObject(File tmp, ObjectId id,
  398. boolean createDuplicate) throws IOException {
  399. // If the object is already in the repository, remove temporary file.
  400. //
  401. if (loose.hasCached(id)) {
  402. FileUtils.delete(tmp, FileUtils.RETRY);
  403. return InsertLooseObjectResult.EXISTS_LOOSE;
  404. }
  405. if (!createDuplicate && has(id)) {
  406. FileUtils.delete(tmp, FileUtils.RETRY);
  407. return InsertLooseObjectResult.EXISTS_PACKED;
  408. }
  409. return loose.insert(tmp, id);
  410. }
  411. @Override
  412. Config getConfig() {
  413. return config;
  414. }
  415. @Override
  416. FS getFS() {
  417. return fs;
  418. }
  419. @Override
  420. Set<ObjectId> getShallowCommits() throws IOException {
  421. if (shallowFile == null || !shallowFile.isFile())
  422. return Collections.emptySet();
  423. if (shallowFileSnapshot == null
  424. || shallowFileSnapshot.isModified(shallowFile)) {
  425. shallowCommitsIds = new HashSet<>();
  426. try (BufferedReader reader = open(shallowFile)) {
  427. String line;
  428. while ((line = reader.readLine()) != null) {
  429. try {
  430. shallowCommitsIds.add(ObjectId.fromString(line));
  431. } catch (IllegalArgumentException ex) {
  432. throw new IOException(MessageFormat
  433. .format(JGitText.get().badShallowLine, line),
  434. ex);
  435. }
  436. }
  437. }
  438. shallowFileSnapshot = FileSnapshot.save(shallowFile);
  439. }
  440. return shallowCommitsIds;
  441. }
  442. void closeAllPackHandles(File packFile) {
  443. // if the packfile already exists (because we are rewriting a
  444. // packfile for the same set of objects maybe with different
  445. // PackConfig) then make sure we get rid of all handles on the file.
  446. // Windows will not allow for rename otherwise.
  447. if (packFile.exists()) {
  448. for (Pack p : packed.getPacks()) {
  449. if (packFile.getPath().equals(p.getPackFile().getPath())) {
  450. p.close();
  451. break;
  452. }
  453. }
  454. }
  455. }
  456. AlternateHandle[] myAlternates() {
  457. AlternateHandle[] alt = alternates.get();
  458. if (alt == null) {
  459. synchronized (alternates) {
  460. alt = alternates.get();
  461. if (alt == null) {
  462. try {
  463. alt = loadAlternates();
  464. } catch (IOException e) {
  465. alt = new AlternateHandle[0];
  466. }
  467. alternates.set(alt);
  468. }
  469. }
  470. }
  471. return alt;
  472. }
  473. Set<AlternateHandle.Id> addMe(Set<AlternateHandle.Id> skips) {
  474. if (skips == null) {
  475. skips = new HashSet<>();
  476. }
  477. skips.add(handle.getId());
  478. return skips;
  479. }
  480. private AlternateHandle[] loadAlternates() throws IOException {
  481. final List<AlternateHandle> l = new ArrayList<>(4);
  482. try (BufferedReader br = open(alternatesFile)) {
  483. String line;
  484. while ((line = br.readLine()) != null) {
  485. l.add(openAlternate(line));
  486. }
  487. }
  488. return l.toArray(new AlternateHandle[0]);
  489. }
  490. private static BufferedReader open(File f)
  491. throws IOException, FileNotFoundException {
  492. return Files.newBufferedReader(f.toPath(), UTF_8);
  493. }
  494. private AlternateHandle openAlternate(String location)
  495. throws IOException {
  496. final File objdir = fs.resolve(objects, location);
  497. return openAlternate(objdir);
  498. }
  499. private AlternateHandle openAlternate(File objdir) throws IOException {
  500. final File parent = objdir.getParentFile();
  501. if (FileKey.isGitRepository(parent, fs)) {
  502. FileKey key = FileKey.exact(parent, fs);
  503. FileRepository db = (FileRepository) RepositoryCache.open(key);
  504. return new AlternateRepository(db);
  505. }
  506. ObjectDirectory db = new ObjectDirectory(config, objdir, null, fs, null);
  507. return new AlternateHandle(db);
  508. }
  509. /**
  510. * Compute the location of a loose object file.
  511. */
  512. @Override
  513. public File fileFor(AnyObjectId objectId) {
  514. return loose.fileFor(objectId);
  515. }
  516. static class AlternateHandle {
  517. static class Id {
  518. String alternateId;
  519. public Id(File object) {
  520. try {
  521. this.alternateId = object.getCanonicalPath();
  522. } catch (Exception e) {
  523. alternateId = null;
  524. }
  525. }
  526. @Override
  527. public boolean equals(Object o) {
  528. if (o == this) {
  529. return true;
  530. }
  531. if (o == null || !(o instanceof Id)) {
  532. return false;
  533. }
  534. Id aId = (Id) o;
  535. return Objects.equals(alternateId, aId.alternateId);
  536. }
  537. @Override
  538. public int hashCode() {
  539. if (alternateId == null) {
  540. return 1;
  541. }
  542. return alternateId.hashCode();
  543. }
  544. }
  545. final ObjectDirectory db;
  546. AlternateHandle(ObjectDirectory db) {
  547. this.db = db;
  548. }
  549. void close() {
  550. db.close();
  551. }
  552. public Id getId(){
  553. return db.getAlternateId();
  554. }
  555. }
  556. static class AlternateRepository extends AlternateHandle {
  557. final FileRepository repository;
  558. AlternateRepository(FileRepository r) {
  559. super(r.getObjectDatabase());
  560. repository = r;
  561. }
  562. @Override
  563. void close() {
  564. repository.close();
  565. }
  566. }
  567. /** {@inheritDoc} */
  568. @Override
  569. public ObjectDatabase newCachedDatabase() {
  570. return newCachedFileObjectDatabase();
  571. }
  572. CachedObjectDirectory newCachedFileObjectDatabase() {
  573. return new CachedObjectDirectory(this);
  574. }
  575. AlternateHandle.Id getAlternateId() {
  576. return new AlternateHandle.Id(objects);
  577. }
  578. }