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.

WalkFetchConnection.java 26KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867
  1. /*
  2. * Copyright (C) 2008, Robin Rosenberg <robin.rosenberg@dewire.com>
  3. * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org>
  4. * and other copyright owners as documented in the project's IP log.
  5. *
  6. * This program and the accompanying materials are made available
  7. * under the terms of the Eclipse Distribution License v1.0 which
  8. * accompanies this distribution, is reproduced below, and is
  9. * available at http://www.eclipse.org/org/documents/edl-v10.php
  10. *
  11. * All rights reserved.
  12. *
  13. * Redistribution and use in source and binary forms, with or
  14. * without modification, are permitted provided that the following
  15. * conditions are met:
  16. *
  17. * - Redistributions of source code must retain the above copyright
  18. * notice, this list of conditions and the following disclaimer.
  19. *
  20. * - Redistributions in binary form must reproduce the above
  21. * copyright notice, this list of conditions and the following
  22. * disclaimer in the documentation and/or other materials provided
  23. * with the distribution.
  24. *
  25. * - Neither the name of the Eclipse Foundation, Inc. nor the
  26. * names of its contributors may be used to endorse or promote
  27. * products derived from this software without specific prior
  28. * written permission.
  29. *
  30. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  31. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  32. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  33. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  34. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  35. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  36. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  37. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  38. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  39. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  40. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  41. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  42. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  43. */
  44. package org.eclipse.jgit.transport;
  45. import java.io.File;
  46. import java.io.FileNotFoundException;
  47. import java.io.FileOutputStream;
  48. import java.io.IOException;
  49. import java.text.MessageFormat;
  50. import java.util.ArrayList;
  51. import java.util.Collection;
  52. import java.util.HashMap;
  53. import java.util.HashSet;
  54. import java.util.Iterator;
  55. import java.util.LinkedList;
  56. import java.util.List;
  57. import java.util.Set;
  58. import org.eclipse.jgit.JGitText;
  59. import org.eclipse.jgit.errors.CompoundException;
  60. import org.eclipse.jgit.errors.CorruptObjectException;
  61. import org.eclipse.jgit.errors.MissingObjectException;
  62. import org.eclipse.jgit.errors.TransportException;
  63. import org.eclipse.jgit.lib.AnyObjectId;
  64. import org.eclipse.jgit.lib.Constants;
  65. import org.eclipse.jgit.lib.FileMode;
  66. import org.eclipse.jgit.lib.MutableObjectId;
  67. import org.eclipse.jgit.lib.ObjectChecker;
  68. import org.eclipse.jgit.lib.ObjectId;
  69. import org.eclipse.jgit.lib.ObjectInserter;
  70. import org.eclipse.jgit.lib.ObjectLoader;
  71. import org.eclipse.jgit.lib.ObjectReader;
  72. import org.eclipse.jgit.lib.ProgressMonitor;
  73. import org.eclipse.jgit.lib.Ref;
  74. import org.eclipse.jgit.lib.Repository;
  75. import org.eclipse.jgit.revwalk.DateRevQueue;
  76. import org.eclipse.jgit.revwalk.RevCommit;
  77. import org.eclipse.jgit.revwalk.RevFlag;
  78. import org.eclipse.jgit.revwalk.RevObject;
  79. import org.eclipse.jgit.revwalk.RevTag;
  80. import org.eclipse.jgit.revwalk.RevTree;
  81. import org.eclipse.jgit.revwalk.RevWalk;
  82. import org.eclipse.jgit.storage.file.ObjectDirectory;
  83. import org.eclipse.jgit.storage.file.PackIndex;
  84. import org.eclipse.jgit.storage.file.PackLock;
  85. import org.eclipse.jgit.storage.file.UnpackedObject;
  86. import org.eclipse.jgit.treewalk.TreeWalk;
  87. /**
  88. * Generic fetch support for dumb transport protocols.
  89. * <p>
  90. * Since there are no Git-specific smarts on the remote side of the connection
  91. * the client side must determine which objects it needs to copy in order to
  92. * completely fetch the requested refs and their history. The generic walk
  93. * support in this class parses each individual object (once it has been copied
  94. * to the local repository) and examines the list of objects that must also be
  95. * copied to create a complete history. Objects which are already available
  96. * locally are retained (and not copied), saving bandwidth for incremental
  97. * fetches. Pack files are copied from the remote repository only as a last
  98. * resort, as the entire pack must be copied locally in order to access any
  99. * single object.
  100. * <p>
  101. * This fetch connection does not actually perform the object data transfer.
  102. * Instead it delegates the transfer to a {@link WalkRemoteObjectDatabase},
  103. * which knows how to read individual files from the remote repository and
  104. * supply the data as a standard Java InputStream.
  105. *
  106. * @see WalkRemoteObjectDatabase
  107. */
  108. class WalkFetchConnection extends BaseFetchConnection {
  109. /** The repository this transport fetches into, or pushes out of. */
  110. private final Repository local;
  111. /** If not null the validator for received objects. */
  112. private final ObjectChecker objCheck;
  113. /**
  114. * List of all remote repositories we may need to get objects out of.
  115. * <p>
  116. * The first repository in the list is the one we were asked to fetch from;
  117. * the remaining repositories point to the alternate locations we can fetch
  118. * objects through.
  119. */
  120. private final List<WalkRemoteObjectDatabase> remotes;
  121. /** Most recently used item in {@link #remotes}. */
  122. private int lastRemoteIdx;
  123. private final RevWalk revWalk;
  124. private final TreeWalk treeWalk;
  125. /** Objects whose direct dependents we know we have (or will have). */
  126. private final RevFlag COMPLETE;
  127. /** Objects that have already entered {@link #workQueue}. */
  128. private final RevFlag IN_WORK_QUEUE;
  129. /** Commits that have already entered {@link #localCommitQueue}. */
  130. private final RevFlag LOCALLY_SEEN;
  131. /** Commits already reachable from all local refs. */
  132. private final DateRevQueue localCommitQueue;
  133. /** Objects we need to copy from the remote repository. */
  134. private LinkedList<ObjectId> workQueue;
  135. /** Databases we have not yet obtained the list of packs from. */
  136. private final LinkedList<WalkRemoteObjectDatabase> noPacksYet;
  137. /** Databases we have not yet obtained the alternates from. */
  138. private final LinkedList<WalkRemoteObjectDatabase> noAlternatesYet;
  139. /** Packs we have discovered, but have not yet fetched locally. */
  140. private final LinkedList<RemotePack> unfetchedPacks;
  141. /**
  142. * Packs whose indexes we have looked at in {@link #unfetchedPacks}.
  143. * <p>
  144. * We try to avoid getting duplicate copies of the same pack through
  145. * multiple alternates by only looking at packs whose names are not yet in
  146. * this collection.
  147. */
  148. private final Set<String> packsConsidered;
  149. private final MutableObjectId idBuffer = new MutableObjectId();
  150. /**
  151. * Errors received while trying to obtain an object.
  152. * <p>
  153. * If the fetch winds up failing because we cannot locate a specific object
  154. * then we need to report all errors related to that object back to the
  155. * caller as there may be cascading failures.
  156. */
  157. private final HashMap<ObjectId, List<Throwable>> fetchErrors;
  158. private String lockMessage;
  159. private final List<PackLock> packLocks;
  160. /** Inserter to write objects onto {@link #local}. */
  161. private final ObjectInserter inserter;
  162. /** Inserter to read objects from {@link #local}. */
  163. private final ObjectReader reader;
  164. WalkFetchConnection(final WalkTransport t, final WalkRemoteObjectDatabase w) {
  165. Transport wt = (Transport)t;
  166. local = wt.local;
  167. objCheck = wt.isCheckFetchedObjects() ? new ObjectChecker() : null;
  168. inserter = local.newObjectInserter();
  169. reader = local.newObjectReader();
  170. remotes = new ArrayList<WalkRemoteObjectDatabase>();
  171. remotes.add(w);
  172. unfetchedPacks = new LinkedList<RemotePack>();
  173. packsConsidered = new HashSet<String>();
  174. noPacksYet = new LinkedList<WalkRemoteObjectDatabase>();
  175. noPacksYet.add(w);
  176. noAlternatesYet = new LinkedList<WalkRemoteObjectDatabase>();
  177. noAlternatesYet.add(w);
  178. fetchErrors = new HashMap<ObjectId, List<Throwable>>();
  179. packLocks = new ArrayList<PackLock>(4);
  180. revWalk = new RevWalk(reader);
  181. revWalk.setRetainBody(false);
  182. treeWalk = new TreeWalk(reader);
  183. COMPLETE = revWalk.newFlag("COMPLETE");
  184. IN_WORK_QUEUE = revWalk.newFlag("IN_WORK_QUEUE");
  185. LOCALLY_SEEN = revWalk.newFlag("LOCALLY_SEEN");
  186. localCommitQueue = new DateRevQueue();
  187. workQueue = new LinkedList<ObjectId>();
  188. }
  189. public boolean didFetchTestConnectivity() {
  190. return true;
  191. }
  192. @Override
  193. protected void doFetch(final ProgressMonitor monitor,
  194. final Collection<Ref> want, final Set<ObjectId> have)
  195. throws TransportException {
  196. markLocalRefsComplete(have);
  197. queueWants(want);
  198. while (!monitor.isCancelled() && !workQueue.isEmpty()) {
  199. final ObjectId id = workQueue.removeFirst();
  200. if (!(id instanceof RevObject) || !((RevObject) id).has(COMPLETE))
  201. downloadObject(monitor, id);
  202. process(id);
  203. }
  204. }
  205. public Collection<PackLock> getPackLocks() {
  206. return packLocks;
  207. }
  208. public void setPackLockMessage(final String message) {
  209. lockMessage = message;
  210. }
  211. @Override
  212. public void close() {
  213. inserter.release();
  214. reader.release();
  215. for (final RemotePack p : unfetchedPacks) {
  216. if (p.tmpIdx != null)
  217. p.tmpIdx.delete();
  218. }
  219. for (final WalkRemoteObjectDatabase r : remotes)
  220. r.close();
  221. }
  222. private void queueWants(final Collection<Ref> want)
  223. throws TransportException {
  224. final HashSet<ObjectId> inWorkQueue = new HashSet<ObjectId>();
  225. for (final Ref r : want) {
  226. final ObjectId id = r.getObjectId();
  227. try {
  228. final RevObject obj = revWalk.parseAny(id);
  229. if (obj.has(COMPLETE))
  230. continue;
  231. if (inWorkQueue.add(id)) {
  232. obj.add(IN_WORK_QUEUE);
  233. workQueue.add(obj);
  234. }
  235. } catch (MissingObjectException e) {
  236. if (inWorkQueue.add(id))
  237. workQueue.add(id);
  238. } catch (IOException e) {
  239. throw new TransportException(MessageFormat.format(JGitText.get().cannotRead, id.name()), e);
  240. }
  241. }
  242. }
  243. private void process(final ObjectId id) throws TransportException {
  244. final RevObject obj;
  245. try {
  246. if (id instanceof RevObject) {
  247. obj = (RevObject) id;
  248. if (obj.has(COMPLETE))
  249. return;
  250. revWalk.parseHeaders(obj);
  251. } else {
  252. obj = revWalk.parseAny(id);
  253. if (obj.has(COMPLETE))
  254. return;
  255. }
  256. } catch (IOException e) {
  257. throw new TransportException(MessageFormat.format(JGitText.get().cannotRead, id.name()), e);
  258. }
  259. switch (obj.getType()) {
  260. case Constants.OBJ_BLOB:
  261. processBlob(obj);
  262. break;
  263. case Constants.OBJ_TREE:
  264. processTree(obj);
  265. break;
  266. case Constants.OBJ_COMMIT:
  267. processCommit(obj);
  268. break;
  269. case Constants.OBJ_TAG:
  270. processTag(obj);
  271. break;
  272. default:
  273. throw new TransportException(MessageFormat.format(JGitText.get().unknownObjectType, id.name()));
  274. }
  275. // If we had any prior errors fetching this object they are
  276. // now resolved, as the object was parsed successfully.
  277. //
  278. fetchErrors.remove(id);
  279. }
  280. private void processBlob(final RevObject obj) throws TransportException {
  281. try {
  282. if (reader.has(obj, Constants.OBJ_BLOB))
  283. obj.add(COMPLETE);
  284. else
  285. throw new TransportException(MessageFormat.format(JGitText
  286. .get().cannotReadBlob, obj.name()),
  287. new MissingObjectException(obj, Constants.TYPE_BLOB));
  288. } catch (IOException error) {
  289. throw new TransportException(MessageFormat.format(
  290. JGitText.get().cannotReadBlob, obj.name()), error);
  291. }
  292. }
  293. private void processTree(final RevObject obj) throws TransportException {
  294. try {
  295. treeWalk.reset(obj);
  296. while (treeWalk.next()) {
  297. final FileMode mode = treeWalk.getFileMode(0);
  298. final int sType = mode.getObjectType();
  299. switch (sType) {
  300. case Constants.OBJ_BLOB:
  301. case Constants.OBJ_TREE:
  302. treeWalk.getObjectId(idBuffer, 0);
  303. needs(revWalk.lookupAny(idBuffer, sType));
  304. continue;
  305. default:
  306. if (FileMode.GITLINK.equals(mode))
  307. continue;
  308. treeWalk.getObjectId(idBuffer, 0);
  309. throw new CorruptObjectException(MessageFormat.format(JGitText.get().invalidModeFor
  310. , mode, idBuffer.name(), treeWalk.getPathString(), obj.getId().name()));
  311. }
  312. }
  313. } catch (IOException ioe) {
  314. throw new TransportException(MessageFormat.format(JGitText.get().cannotReadTree, obj.name()), ioe);
  315. }
  316. obj.add(COMPLETE);
  317. }
  318. private void processCommit(final RevObject obj) throws TransportException {
  319. final RevCommit commit = (RevCommit) obj;
  320. markLocalCommitsComplete(commit.getCommitTime());
  321. needs(commit.getTree());
  322. for (final RevCommit p : commit.getParents())
  323. needs(p);
  324. obj.add(COMPLETE);
  325. }
  326. private void processTag(final RevObject obj) {
  327. final RevTag tag = (RevTag) obj;
  328. needs(tag.getObject());
  329. obj.add(COMPLETE);
  330. }
  331. private void needs(final RevObject obj) {
  332. if (obj.has(COMPLETE))
  333. return;
  334. if (!obj.has(IN_WORK_QUEUE)) {
  335. obj.add(IN_WORK_QUEUE);
  336. workQueue.add(obj);
  337. }
  338. }
  339. private void downloadObject(final ProgressMonitor pm, final AnyObjectId id)
  340. throws TransportException {
  341. if (alreadyHave(id))
  342. return;
  343. for (;;) {
  344. // Try a pack file we know about, but don't have yet. Odds are
  345. // that if it has this object, it has others related to it so
  346. // getting the pack is a good bet.
  347. //
  348. if (downloadPackedObject(pm, id))
  349. return;
  350. // Search for a loose object over all alternates, starting
  351. // from the one we last successfully located an object through.
  352. //
  353. final String idStr = id.name();
  354. final String subdir = idStr.substring(0, 2);
  355. final String file = idStr.substring(2);
  356. final String looseName = subdir + "/" + file;
  357. for (int i = lastRemoteIdx; i < remotes.size(); i++) {
  358. if (downloadLooseObject(id, looseName, remotes.get(i))) {
  359. lastRemoteIdx = i;
  360. return;
  361. }
  362. }
  363. for (int i = 0; i < lastRemoteIdx; i++) {
  364. if (downloadLooseObject(id, looseName, remotes.get(i))) {
  365. lastRemoteIdx = i;
  366. return;
  367. }
  368. }
  369. // Try to obtain more pack information and search those.
  370. //
  371. while (!noPacksYet.isEmpty()) {
  372. final WalkRemoteObjectDatabase wrr = noPacksYet.removeFirst();
  373. final Collection<String> packNameList;
  374. try {
  375. pm.beginTask("Listing packs", ProgressMonitor.UNKNOWN);
  376. packNameList = wrr.getPackNames();
  377. } catch (IOException e) {
  378. // Try another repository.
  379. //
  380. recordError(id, e);
  381. continue;
  382. } finally {
  383. pm.endTask();
  384. }
  385. if (packNameList == null || packNameList.isEmpty())
  386. continue;
  387. for (final String packName : packNameList) {
  388. if (packsConsidered.add(packName))
  389. unfetchedPacks.add(new RemotePack(wrr, packName));
  390. }
  391. if (downloadPackedObject(pm, id))
  392. return;
  393. }
  394. // Try to expand the first alternate we haven't expanded yet.
  395. //
  396. Collection<WalkRemoteObjectDatabase> al = expandOneAlternate(id, pm);
  397. if (al != null && !al.isEmpty()) {
  398. for (final WalkRemoteObjectDatabase alt : al) {
  399. remotes.add(alt);
  400. noPacksYet.add(alt);
  401. noAlternatesYet.add(alt);
  402. }
  403. continue;
  404. }
  405. // We could not obtain the object. There may be reasons why.
  406. //
  407. List<Throwable> failures = fetchErrors.get(id);
  408. final TransportException te;
  409. te = new TransportException(MessageFormat.format(JGitText.get().cannotGet, id.name()));
  410. if (failures != null && !failures.isEmpty()) {
  411. if (failures.size() == 1)
  412. te.initCause(failures.get(0));
  413. else
  414. te.initCause(new CompoundException(failures));
  415. }
  416. throw te;
  417. }
  418. }
  419. private boolean alreadyHave(final AnyObjectId id) throws TransportException {
  420. try {
  421. return reader.has(id);
  422. } catch (IOException error) {
  423. throw new TransportException(MessageFormat.format(
  424. JGitText.get().cannotReadObject, id.name()), error);
  425. }
  426. }
  427. private boolean downloadPackedObject(final ProgressMonitor monitor,
  428. final AnyObjectId id) throws TransportException {
  429. // Search for the object in a remote pack whose index we have,
  430. // but whose pack we do not yet have.
  431. //
  432. final Iterator<RemotePack> packItr = unfetchedPacks.iterator();
  433. while (packItr.hasNext() && !monitor.isCancelled()) {
  434. final RemotePack pack = packItr.next();
  435. try {
  436. pack.openIndex(monitor);
  437. } catch (IOException err) {
  438. // If the index won't open its either not found or
  439. // its a format we don't recognize. In either case
  440. // we may still be able to obtain the object from
  441. // another source, so don't consider it a failure.
  442. //
  443. recordError(id, err);
  444. packItr.remove();
  445. continue;
  446. }
  447. if (monitor.isCancelled()) {
  448. // If we were cancelled while the index was opening
  449. // the open may have aborted. We can't search an
  450. // unopen index.
  451. //
  452. return false;
  453. }
  454. if (!pack.index.hasObject(id)) {
  455. // Not in this pack? Try another.
  456. //
  457. continue;
  458. }
  459. // It should be in the associated pack. Download that
  460. // and attach it to the local repository so we can use
  461. // all of the contained objects.
  462. //
  463. try {
  464. pack.downloadPack(monitor);
  465. } catch (IOException err) {
  466. // If the pack failed to download, index correctly,
  467. // or open in the local repository we may still be
  468. // able to obtain this object from another pack or
  469. // an alternate.
  470. //
  471. recordError(id, err);
  472. continue;
  473. } finally {
  474. // If the pack was good its in the local repository
  475. // and Repository.hasObject(id) will succeed in the
  476. // future, so we do not need this data anymore. If
  477. // it failed the index and pack are unusable and we
  478. // shouldn't consult them again.
  479. //
  480. if (pack.tmpIdx != null)
  481. pack.tmpIdx.delete();
  482. packItr.remove();
  483. }
  484. if (!alreadyHave(id)) {
  485. // What the hell? This pack claimed to have
  486. // the object, but after indexing we didn't
  487. // actually find it in the pack.
  488. //
  489. recordError(id, new FileNotFoundException(MessageFormat.format(
  490. JGitText.get().objectNotFoundIn, id.name(), pack.packName)));
  491. continue;
  492. }
  493. // Complete any other objects that we can.
  494. //
  495. final Iterator<ObjectId> pending = swapFetchQueue();
  496. while (pending.hasNext()) {
  497. final ObjectId p = pending.next();
  498. if (pack.index.hasObject(p)) {
  499. pending.remove();
  500. process(p);
  501. } else {
  502. workQueue.add(p);
  503. }
  504. }
  505. return true;
  506. }
  507. return false;
  508. }
  509. private Iterator<ObjectId> swapFetchQueue() {
  510. final Iterator<ObjectId> r = workQueue.iterator();
  511. workQueue = new LinkedList<ObjectId>();
  512. return r;
  513. }
  514. private boolean downloadLooseObject(final AnyObjectId id,
  515. final String looseName, final WalkRemoteObjectDatabase remote)
  516. throws TransportException {
  517. try {
  518. final byte[] compressed = remote.open(looseName).toArray();
  519. verifyAndInsertLooseObject(id, compressed);
  520. return true;
  521. } catch (FileNotFoundException e) {
  522. // Not available in a loose format from this alternate?
  523. // Try another strategy to get the object.
  524. //
  525. recordError(id, e);
  526. return false;
  527. } catch (IOException e) {
  528. throw new TransportException(MessageFormat.format(JGitText.get().cannotDownload, id.name()), e);
  529. }
  530. }
  531. private void verifyAndInsertLooseObject(final AnyObjectId id,
  532. final byte[] compressed) throws IOException {
  533. final ObjectLoader uol;
  534. try {
  535. uol = UnpackedObject.parse(compressed, id);
  536. } catch (CorruptObjectException parsingError) {
  537. // Some HTTP servers send back a "200 OK" status with an HTML
  538. // page that explains the requested file could not be found.
  539. // These servers are most certainly misconfigured, but many
  540. // of them exist in the world, and many of those are hosting
  541. // Git repositories.
  542. //
  543. // Since an HTML page is unlikely to hash to one of our loose
  544. // objects we treat this condition as a FileNotFoundException
  545. // and attempt to recover by getting the object from another
  546. // source.
  547. //
  548. final FileNotFoundException e;
  549. e = new FileNotFoundException(id.name());
  550. e.initCause(parsingError);
  551. throw e;
  552. }
  553. final int type = uol.getType();
  554. final byte[] raw = uol.getCachedBytes();
  555. if (objCheck != null) {
  556. try {
  557. objCheck.check(type, raw);
  558. } catch (CorruptObjectException e) {
  559. throw new TransportException(MessageFormat.format(JGitText.get().transportExceptionInvalid
  560. , Constants.typeString(type), id.name(), e.getMessage()));
  561. }
  562. }
  563. ObjectId act = inserter.insert(type, raw);
  564. if (!AnyObjectId.equals(id, act)) {
  565. throw new TransportException(MessageFormat.format(JGitText.get().incorrectHashFor
  566. , id.name(), act.name(), Constants.typeString(type), compressed.length));
  567. }
  568. inserter.flush();
  569. }
  570. private Collection<WalkRemoteObjectDatabase> expandOneAlternate(
  571. final AnyObjectId id, final ProgressMonitor pm) {
  572. while (!noAlternatesYet.isEmpty()) {
  573. final WalkRemoteObjectDatabase wrr = noAlternatesYet.removeFirst();
  574. try {
  575. pm.beginTask(JGitText.get().listingAlternates, ProgressMonitor.UNKNOWN);
  576. Collection<WalkRemoteObjectDatabase> altList = wrr
  577. .getAlternates();
  578. if (altList != null && !altList.isEmpty())
  579. return altList;
  580. } catch (IOException e) {
  581. // Try another repository.
  582. //
  583. recordError(id, e);
  584. } finally {
  585. pm.endTask();
  586. }
  587. }
  588. return null;
  589. }
  590. private void markLocalRefsComplete(final Set<ObjectId> have) throws TransportException {
  591. for (final Ref r : local.getAllRefs().values()) {
  592. try {
  593. markLocalObjComplete(revWalk.parseAny(r.getObjectId()));
  594. } catch (IOException readError) {
  595. throw new TransportException(MessageFormat.format(JGitText.get().localRefIsMissingObjects, r.getName()), readError);
  596. }
  597. }
  598. for (final ObjectId id : have) {
  599. try {
  600. markLocalObjComplete(revWalk.parseAny(id));
  601. } catch (IOException readError) {
  602. throw new TransportException(MessageFormat.format(JGitText.get().transportExceptionMissingAssumed, id.name()), readError);
  603. }
  604. }
  605. }
  606. private void markLocalObjComplete(RevObject obj) throws IOException {
  607. while (obj.getType() == Constants.OBJ_TAG) {
  608. obj.add(COMPLETE);
  609. obj = ((RevTag) obj).getObject();
  610. revWalk.parseHeaders(obj);
  611. }
  612. switch (obj.getType()) {
  613. case Constants.OBJ_BLOB:
  614. obj.add(COMPLETE);
  615. break;
  616. case Constants.OBJ_COMMIT:
  617. pushLocalCommit((RevCommit) obj);
  618. break;
  619. case Constants.OBJ_TREE:
  620. markTreeComplete((RevTree) obj);
  621. break;
  622. }
  623. }
  624. private void markLocalCommitsComplete(final int until)
  625. throws TransportException {
  626. try {
  627. for (;;) {
  628. final RevCommit c = localCommitQueue.peek();
  629. if (c == null || c.getCommitTime() < until)
  630. return;
  631. localCommitQueue.next();
  632. markTreeComplete(c.getTree());
  633. for (final RevCommit p : c.getParents())
  634. pushLocalCommit(p);
  635. }
  636. } catch (IOException err) {
  637. throw new TransportException(JGitText.get().localObjectsIncomplete, err);
  638. }
  639. }
  640. private void pushLocalCommit(final RevCommit p)
  641. throws MissingObjectException, IOException {
  642. if (p.has(LOCALLY_SEEN))
  643. return;
  644. revWalk.parseHeaders(p);
  645. p.add(LOCALLY_SEEN);
  646. p.add(COMPLETE);
  647. p.carry(COMPLETE);
  648. localCommitQueue.add(p);
  649. }
  650. private void markTreeComplete(final RevTree tree) throws IOException {
  651. if (tree.has(COMPLETE))
  652. return;
  653. tree.add(COMPLETE);
  654. treeWalk.reset(tree);
  655. while (treeWalk.next()) {
  656. final FileMode mode = treeWalk.getFileMode(0);
  657. final int sType = mode.getObjectType();
  658. switch (sType) {
  659. case Constants.OBJ_BLOB:
  660. treeWalk.getObjectId(idBuffer, 0);
  661. revWalk.lookupAny(idBuffer, sType).add(COMPLETE);
  662. continue;
  663. case Constants.OBJ_TREE: {
  664. treeWalk.getObjectId(idBuffer, 0);
  665. final RevObject o = revWalk.lookupAny(idBuffer, sType);
  666. if (!o.has(COMPLETE)) {
  667. o.add(COMPLETE);
  668. treeWalk.enterSubtree();
  669. }
  670. continue;
  671. }
  672. default:
  673. if (FileMode.GITLINK.equals(mode))
  674. continue;
  675. treeWalk.getObjectId(idBuffer, 0);
  676. throw new CorruptObjectException(MessageFormat.format(JGitText.get().corruptObjectInvalidMode3
  677. , mode, idBuffer.name(), treeWalk.getPathString(), tree.name()));
  678. }
  679. }
  680. }
  681. private void recordError(final AnyObjectId id, final Throwable what) {
  682. final ObjectId objId = id.copy();
  683. List<Throwable> errors = fetchErrors.get(objId);
  684. if (errors == null) {
  685. errors = new ArrayList<Throwable>(2);
  686. fetchErrors.put(objId, errors);
  687. }
  688. errors.add(what);
  689. }
  690. private class RemotePack {
  691. final WalkRemoteObjectDatabase connection;
  692. final String packName;
  693. final String idxName;
  694. File tmpIdx;
  695. PackIndex index;
  696. RemotePack(final WalkRemoteObjectDatabase c, final String pn) {
  697. connection = c;
  698. packName = pn;
  699. idxName = packName.substring(0, packName.length() - 5) + ".idx";
  700. String tn = idxName;
  701. if (tn.startsWith("pack-"))
  702. tn = tn.substring(5);
  703. if (tn.endsWith(".idx"))
  704. tn = tn.substring(0, tn.length() - 4);
  705. if (local.getObjectDatabase() instanceof ObjectDirectory) {
  706. tmpIdx = new File(((ObjectDirectory) local.getObjectDatabase())
  707. .getDirectory(), "walk-" + tn + ".walkidx");
  708. }
  709. }
  710. void openIndex(final ProgressMonitor pm) throws IOException {
  711. if (index != null)
  712. return;
  713. if (tmpIdx == null)
  714. tmpIdx = File.createTempFile("jgit-walk-", ".idx");
  715. else if (tmpIdx.isFile()) {
  716. try {
  717. index = PackIndex.open(tmpIdx);
  718. return;
  719. } catch (FileNotFoundException err) {
  720. // Fall through and get the file.
  721. }
  722. }
  723. final WalkRemoteObjectDatabase.FileStream s;
  724. s = connection.open("pack/" + idxName);
  725. pm.beginTask("Get " + idxName.substring(0, 12) + "..idx",
  726. s.length < 0 ? ProgressMonitor.UNKNOWN
  727. : (int) (s.length / 1024));
  728. try {
  729. final FileOutputStream fos = new FileOutputStream(tmpIdx);
  730. try {
  731. final byte[] buf = new byte[2048];
  732. int cnt;
  733. while (!pm.isCancelled() && (cnt = s.in.read(buf)) >= 0) {
  734. fos.write(buf, 0, cnt);
  735. pm.update(cnt / 1024);
  736. }
  737. } finally {
  738. fos.close();
  739. }
  740. } catch (IOException err) {
  741. tmpIdx.delete();
  742. throw err;
  743. } finally {
  744. s.in.close();
  745. }
  746. pm.endTask();
  747. if (pm.isCancelled()) {
  748. tmpIdx.delete();
  749. return;
  750. }
  751. try {
  752. index = PackIndex.open(tmpIdx);
  753. } catch (IOException e) {
  754. tmpIdx.delete();
  755. throw e;
  756. }
  757. }
  758. void downloadPack(final ProgressMonitor monitor) throws IOException {
  759. final WalkRemoteObjectDatabase.FileStream s;
  760. final IndexPack ip;
  761. s = connection.open("pack/" + packName);
  762. ip = IndexPack.create(local, s.in);
  763. ip.setFixThin(false);
  764. ip.setObjectChecker(objCheck);
  765. ip.index(monitor);
  766. final PackLock keep = ip.renameAndOpenPack(lockMessage);
  767. if (keep != null)
  768. packLocks.add(keep);
  769. }
  770. }
  771. }