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.

BasePackFetchConnection.java 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  1. /*
  2. * Copyright (C) 2008-2010, Google Inc.
  3. * Copyright (C) 2008, Robin Rosenberg <robin.rosenberg@dewire.com>
  4. * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org>
  5. * and other copyright owners as documented in the project's IP log.
  6. *
  7. * This program and the accompanying materials are made available
  8. * under the terms of the Eclipse Distribution License v1.0 which
  9. * accompanies this distribution, is reproduced below, and is
  10. * available at http://www.eclipse.org/org/documents/edl-v10.php
  11. *
  12. * All rights reserved.
  13. *
  14. * Redistribution and use in source and binary forms, with or
  15. * without modification, are permitted provided that the following
  16. * conditions are met:
  17. *
  18. * - Redistributions of source code must retain the above copyright
  19. * notice, this list of conditions and the following disclaimer.
  20. *
  21. * - Redistributions in binary form must reproduce the above
  22. * copyright notice, this list of conditions and the following
  23. * disclaimer in the documentation and/or other materials provided
  24. * with the distribution.
  25. *
  26. * - Neither the name of the Eclipse Foundation, Inc. nor the
  27. * names of its contributors may be used to endorse or promote
  28. * products derived from this software without specific prior
  29. * written permission.
  30. *
  31. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  32. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  33. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  34. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  35. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  36. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  37. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  38. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  39. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  40. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  41. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  42. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  43. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  44. */
  45. package org.eclipse.jgit.transport;
  46. import java.io.IOException;
  47. import java.io.InputStream;
  48. import java.util.Collection;
  49. import java.util.Collections;
  50. import java.util.Date;
  51. import java.util.Set;
  52. import org.eclipse.jgit.errors.PackProtocolException;
  53. import org.eclipse.jgit.errors.TransportException;
  54. import org.eclipse.jgit.lib.AnyObjectId;
  55. import org.eclipse.jgit.lib.Config;
  56. import org.eclipse.jgit.lib.Constants;
  57. import org.eclipse.jgit.lib.MutableObjectId;
  58. import org.eclipse.jgit.lib.ObjectId;
  59. import org.eclipse.jgit.lib.PackLock;
  60. import org.eclipse.jgit.lib.ProgressMonitor;
  61. import org.eclipse.jgit.lib.Ref;
  62. import org.eclipse.jgit.lib.Config.SectionParser;
  63. import org.eclipse.jgit.revwalk.RevCommit;
  64. import org.eclipse.jgit.revwalk.RevCommitList;
  65. import org.eclipse.jgit.revwalk.RevFlag;
  66. import org.eclipse.jgit.revwalk.RevObject;
  67. import org.eclipse.jgit.revwalk.RevSort;
  68. import org.eclipse.jgit.revwalk.RevWalk;
  69. import org.eclipse.jgit.revwalk.filter.CommitTimeRevFilter;
  70. import org.eclipse.jgit.revwalk.filter.RevFilter;
  71. import org.eclipse.jgit.transport.PacketLineIn.AckNackResult;
  72. import org.eclipse.jgit.util.TemporaryBuffer;
  73. /**
  74. * Fetch implementation using the native Git pack transfer service.
  75. * <p>
  76. * This is the canonical implementation for transferring objects from the remote
  77. * repository to the local repository by talking to the 'git-upload-pack'
  78. * service. Objects are packed on the remote side into a pack file and then sent
  79. * down the pipe to us.
  80. * <p>
  81. * This connection requires only a bi-directional pipe or socket, and thus is
  82. * easily wrapped up into a local process pipe, anonymous TCP socket, or a
  83. * command executed through an SSH tunnel.
  84. * <p>
  85. * If {@link BasePackConnection#statelessRPC} is {@code true}, this connection
  86. * can be tunneled over a request-response style RPC system like HTTP. The RPC
  87. * call boundary is determined by this class switching from writing to the
  88. * OutputStream to reading from the InputStream.
  89. * <p>
  90. * Concrete implementations should just call
  91. * {@link #init(java.io.InputStream, java.io.OutputStream)} and
  92. * {@link #readAdvertisedRefs()} methods in constructor or before any use. They
  93. * should also handle resources releasing in {@link #close()} method if needed.
  94. */
  95. abstract class BasePackFetchConnection extends BasePackConnection implements
  96. FetchConnection {
  97. /**
  98. * Maximum number of 'have' lines to send before giving up.
  99. * <p>
  100. * During {@link #negotiate(ProgressMonitor)} we send at most this many
  101. * commits to the remote peer as 'have' lines without an ACK response before
  102. * we give up.
  103. */
  104. private static final int MAX_HAVES = 256;
  105. /**
  106. * Amount of data the client sends before starting to read.
  107. * <p>
  108. * Any output stream given to the client must be able to buffer this many
  109. * bytes before the client will stop writing and start reading from the
  110. * input stream. If the output stream blocks before this many bytes are in
  111. * the send queue, the system will deadlock.
  112. */
  113. protected static final int MIN_CLIENT_BUFFER = 2 * 32 * 46 + 8;
  114. static final String OPTION_INCLUDE_TAG = "include-tag";
  115. static final String OPTION_MULTI_ACK = "multi_ack";
  116. static final String OPTION_MULTI_ACK_DETAILED = "multi_ack_detailed";
  117. static final String OPTION_THIN_PACK = "thin-pack";
  118. static final String OPTION_SIDE_BAND = "side-band";
  119. static final String OPTION_SIDE_BAND_64K = "side-band-64k";
  120. static final String OPTION_OFS_DELTA = "ofs-delta";
  121. static final String OPTION_SHALLOW = "shallow";
  122. static final String OPTION_NO_PROGRESS = "no-progress";
  123. static enum MultiAck {
  124. OFF, CONTINUE, DETAILED;
  125. }
  126. private final RevWalk walk;
  127. /** All commits that are immediately reachable by a local ref. */
  128. private RevCommitList<RevCommit> reachableCommits;
  129. /** Marks an object as having all its dependencies. */
  130. final RevFlag REACHABLE;
  131. /** Marks a commit known to both sides of the connection. */
  132. final RevFlag COMMON;
  133. /** Like {@link #COMMON} but means its also in {@link #pckState}. */
  134. private final RevFlag STATE;
  135. /** Marks a commit listed in the advertised refs. */
  136. final RevFlag ADVERTISED;
  137. private MultiAck multiAck = MultiAck.OFF;
  138. private boolean thinPack;
  139. private boolean sideband;
  140. private boolean includeTags;
  141. private boolean allowOfsDelta;
  142. private String lockMessage;
  143. private PackLock packLock;
  144. /** RPC state, if {@link BasePackConnection#statelessRPC} is true. */
  145. private TemporaryBuffer.Heap state;
  146. private PacketLineOut pckState;
  147. BasePackFetchConnection(final PackTransport packTransport) {
  148. super(packTransport);
  149. final FetchConfig cfg = local.getConfig().get(FetchConfig.KEY);
  150. includeTags = transport.getTagOpt() != TagOpt.NO_TAGS;
  151. thinPack = transport.isFetchThin();
  152. allowOfsDelta = cfg.allowOfsDelta;
  153. walk = new RevWalk(local);
  154. reachableCommits = new RevCommitList<RevCommit>();
  155. REACHABLE = walk.newFlag("REACHABLE");
  156. COMMON = walk.newFlag("COMMON");
  157. STATE = walk.newFlag("STATE");
  158. ADVERTISED = walk.newFlag("ADVERTISED");
  159. walk.carry(COMMON);
  160. walk.carry(REACHABLE);
  161. walk.carry(ADVERTISED);
  162. }
  163. private static class FetchConfig {
  164. static final SectionParser<FetchConfig> KEY = new SectionParser<FetchConfig>() {
  165. public FetchConfig parse(final Config cfg) {
  166. return new FetchConfig(cfg);
  167. }
  168. };
  169. final boolean allowOfsDelta;
  170. FetchConfig(final Config c) {
  171. allowOfsDelta = c.getBoolean("repack", "usedeltabaseoffset", true);
  172. }
  173. }
  174. public final void fetch(final ProgressMonitor monitor,
  175. final Collection<Ref> want, final Set<ObjectId> have)
  176. throws TransportException {
  177. markStartedOperation();
  178. doFetch(monitor, want, have);
  179. }
  180. public boolean didFetchIncludeTags() {
  181. return false;
  182. }
  183. public boolean didFetchTestConnectivity() {
  184. return false;
  185. }
  186. public void setPackLockMessage(final String message) {
  187. lockMessage = message;
  188. }
  189. public Collection<PackLock> getPackLocks() {
  190. if (packLock != null)
  191. return Collections.singleton(packLock);
  192. return Collections.<PackLock> emptyList();
  193. }
  194. protected void doFetch(final ProgressMonitor monitor,
  195. final Collection<Ref> want, final Set<ObjectId> have)
  196. throws TransportException {
  197. try {
  198. markRefsAdvertised();
  199. markReachable(have, maxTimeWanted(want));
  200. if (statelessRPC) {
  201. state = new TemporaryBuffer.Heap(Integer.MAX_VALUE);
  202. pckState = new PacketLineOut(state);
  203. }
  204. if (sendWants(want)) {
  205. negotiate(monitor);
  206. walk.dispose();
  207. reachableCommits = null;
  208. state = null;
  209. pckState = null;
  210. receivePack(monitor);
  211. }
  212. } catch (CancelledException ce) {
  213. close();
  214. return; // Caller should test (or just know) this themselves.
  215. } catch (IOException err) {
  216. close();
  217. throw new TransportException(err.getMessage(), err);
  218. } catch (RuntimeException err) {
  219. close();
  220. throw new TransportException(err.getMessage(), err);
  221. }
  222. }
  223. private int maxTimeWanted(final Collection<Ref> wants) {
  224. int maxTime = 0;
  225. for (final Ref r : wants) {
  226. try {
  227. final RevObject obj = walk.parseAny(r.getObjectId());
  228. if (obj instanceof RevCommit) {
  229. final int cTime = ((RevCommit) obj).getCommitTime();
  230. if (maxTime < cTime)
  231. maxTime = cTime;
  232. }
  233. } catch (IOException error) {
  234. // We don't have it, but we want to fetch (thus fixing error).
  235. }
  236. }
  237. return maxTime;
  238. }
  239. private void markReachable(final Set<ObjectId> have, final int maxTime)
  240. throws IOException {
  241. for (final Ref r : local.getAllRefs().values()) {
  242. try {
  243. final RevCommit o = walk.parseCommit(r.getObjectId());
  244. o.add(REACHABLE);
  245. reachableCommits.add(o);
  246. } catch (IOException readError) {
  247. // If we cannot read the value of the ref skip it.
  248. }
  249. }
  250. for (final ObjectId id : have) {
  251. try {
  252. final RevCommit o = walk.parseCommit(id);
  253. o.add(REACHABLE);
  254. reachableCommits.add(o);
  255. } catch (IOException readError) {
  256. // If we cannot read the value of the ref skip it.
  257. }
  258. }
  259. if (maxTime > 0) {
  260. // Mark reachable commits until we reach maxTime. These may
  261. // wind up later matching up against things we want and we
  262. // can avoid asking for something we already happen to have.
  263. //
  264. final Date maxWhen = new Date(maxTime * 1000L);
  265. walk.sort(RevSort.COMMIT_TIME_DESC);
  266. walk.markStart(reachableCommits);
  267. walk.setRevFilter(CommitTimeRevFilter.after(maxWhen));
  268. for (;;) {
  269. final RevCommit c = walk.next();
  270. if (c == null)
  271. break;
  272. if (c.has(ADVERTISED) && !c.has(COMMON)) {
  273. // This is actually going to be a common commit, but
  274. // our peer doesn't know that fact yet.
  275. //
  276. c.add(COMMON);
  277. c.carry(COMMON);
  278. reachableCommits.add(c);
  279. }
  280. }
  281. }
  282. }
  283. private boolean sendWants(final Collection<Ref> want) throws IOException {
  284. final PacketLineOut p = statelessRPC ? pckState : pckOut;
  285. boolean first = true;
  286. for (final Ref r : want) {
  287. try {
  288. if (walk.parseAny(r.getObjectId()).has(REACHABLE)) {
  289. // We already have this object. Asking for it is
  290. // not a very good idea.
  291. //
  292. continue;
  293. }
  294. } catch (IOException err) {
  295. // Its OK, we don't have it, but we want to fix that
  296. // by fetching the object from the other side.
  297. }
  298. final StringBuilder line = new StringBuilder(46);
  299. line.append("want ");
  300. line.append(r.getObjectId().name());
  301. if (first) {
  302. line.append(enableCapabilities());
  303. first = false;
  304. }
  305. line.append('\n');
  306. p.writeString(line.toString());
  307. }
  308. if (first)
  309. return false;
  310. p.end();
  311. outNeedsEnd = false;
  312. return true;
  313. }
  314. private String enableCapabilities() throws TransportException {
  315. final StringBuilder line = new StringBuilder();
  316. if (includeTags)
  317. includeTags = wantCapability(line, OPTION_INCLUDE_TAG);
  318. if (allowOfsDelta)
  319. wantCapability(line, OPTION_OFS_DELTA);
  320. if (wantCapability(line, OPTION_MULTI_ACK_DETAILED))
  321. multiAck = MultiAck.DETAILED;
  322. else if (wantCapability(line, OPTION_MULTI_ACK))
  323. multiAck = MultiAck.CONTINUE;
  324. else
  325. multiAck = MultiAck.OFF;
  326. if (thinPack)
  327. thinPack = wantCapability(line, OPTION_THIN_PACK);
  328. if (wantCapability(line, OPTION_SIDE_BAND_64K))
  329. sideband = true;
  330. else if (wantCapability(line, OPTION_SIDE_BAND))
  331. sideband = true;
  332. if (statelessRPC && multiAck != MultiAck.DETAILED) {
  333. // Our stateless RPC implementation relies upon the detailed
  334. // ACK status to tell us common objects for reuse in future
  335. // requests. If its not enabled, we can't talk to the peer.
  336. //
  337. throw new PackProtocolException(uri, "stateless RPC requires "
  338. + OPTION_MULTI_ACK_DETAILED + " to be enabled");
  339. }
  340. return line.toString();
  341. }
  342. private void negotiate(final ProgressMonitor monitor) throws IOException,
  343. CancelledException {
  344. final MutableObjectId ackId = new MutableObjectId();
  345. int resultsPending = 0;
  346. int havesSent = 0;
  347. int havesSinceLastContinue = 0;
  348. boolean receivedContinue = false;
  349. boolean receivedAck = false;
  350. if (statelessRPC)
  351. state.writeTo(out, null);
  352. negotiateBegin();
  353. SEND_HAVES: for (;;) {
  354. final RevCommit c = walk.next();
  355. if (c == null)
  356. break SEND_HAVES;
  357. pckOut.writeString("have " + c.getId().name() + "\n");
  358. havesSent++;
  359. havesSinceLastContinue++;
  360. if ((31 & havesSent) != 0) {
  361. // We group the have lines into blocks of 32, each marked
  362. // with a flush (aka end). This one is within a block so
  363. // continue with another have line.
  364. //
  365. continue;
  366. }
  367. if (monitor.isCancelled())
  368. throw new CancelledException();
  369. pckOut.end();
  370. resultsPending++; // Each end will cause a result to come back.
  371. if (havesSent == 32 && !statelessRPC) {
  372. // On the first block we race ahead and try to send
  373. // more of the second block while waiting for the
  374. // remote to respond to our first block request.
  375. // This keeps us one block ahead of the peer.
  376. //
  377. continue;
  378. }
  379. READ_RESULT: for (;;) {
  380. final AckNackResult anr = pckIn.readACK(ackId);
  381. switch (anr) {
  382. case NAK:
  383. // More have lines are necessary to compute the
  384. // pack on the remote side. Keep doing that.
  385. //
  386. resultsPending--;
  387. break READ_RESULT;
  388. case ACK:
  389. // The remote side is happy and knows exactly what
  390. // to send us. There is no further negotiation and
  391. // we can break out immediately.
  392. //
  393. multiAck = MultiAck.OFF;
  394. resultsPending = 0;
  395. receivedAck = true;
  396. if (statelessRPC)
  397. state.writeTo(out, null);
  398. break SEND_HAVES;
  399. case ACK_CONTINUE:
  400. case ACK_COMMON:
  401. case ACK_READY:
  402. // The server knows this commit (ackId). We don't
  403. // need to send any further along its ancestry, but
  404. // we need to continue to talk about other parts of
  405. // our local history.
  406. //
  407. markCommon(walk.parseAny(ackId), anr);
  408. receivedAck = true;
  409. receivedContinue = true;
  410. havesSinceLastContinue = 0;
  411. break;
  412. }
  413. if (monitor.isCancelled())
  414. throw new CancelledException();
  415. }
  416. if (statelessRPC)
  417. state.writeTo(out, null);
  418. if (receivedContinue && havesSinceLastContinue > MAX_HAVES) {
  419. // Our history must be really different from the remote's.
  420. // We just sent a whole slew of have lines, and it did not
  421. // recognize any of them. Avoid sending our entire history
  422. // to them by giving up early.
  423. //
  424. break SEND_HAVES;
  425. }
  426. }
  427. // Tell the remote side we have run out of things to talk about.
  428. //
  429. if (monitor.isCancelled())
  430. throw new CancelledException();
  431. // When statelessRPC is true we should always leave SEND_HAVES
  432. // loop above while in the middle of a request. This allows us
  433. // to just write done immediately.
  434. //
  435. pckOut.writeString("done\n");
  436. pckOut.flush();
  437. if (!receivedAck) {
  438. // Apparently if we have never received an ACK earlier
  439. // there is one more result expected from the done we
  440. // just sent to the remote.
  441. //
  442. multiAck = MultiAck.OFF;
  443. resultsPending++;
  444. }
  445. READ_RESULT: while (resultsPending > 0 || multiAck != MultiAck.OFF) {
  446. final AckNackResult anr = pckIn.readACK(ackId);
  447. resultsPending--;
  448. switch (anr) {
  449. case NAK:
  450. // A NAK is a response to an end we queued earlier
  451. // we eat it and look for another ACK/NAK message.
  452. //
  453. break;
  454. case ACK:
  455. // A solitary ACK at this point means the remote won't
  456. // speak anymore, but is going to send us a pack now.
  457. //
  458. break READ_RESULT;
  459. case ACK_CONTINUE:
  460. case ACK_COMMON:
  461. case ACK_READY:
  462. // We will expect a normal ACK to break out of the loop.
  463. //
  464. multiAck = MultiAck.CONTINUE;
  465. break;
  466. }
  467. if (monitor.isCancelled())
  468. throw new CancelledException();
  469. }
  470. }
  471. private void negotiateBegin() throws IOException {
  472. walk.resetRetain(REACHABLE, ADVERTISED);
  473. walk.markStart(reachableCommits);
  474. walk.sort(RevSort.COMMIT_TIME_DESC);
  475. walk.setRevFilter(new RevFilter() {
  476. @Override
  477. public RevFilter clone() {
  478. return this;
  479. }
  480. @Override
  481. public boolean include(final RevWalk walker, final RevCommit c) {
  482. final boolean remoteKnowsIsCommon = c.has(COMMON);
  483. if (c.has(ADVERTISED)) {
  484. // Remote advertised this, and we have it, hence common.
  485. // Whether or not the remote knows that fact is tested
  486. // before we added the flag. If the remote doesn't know
  487. // we have to still send them this object.
  488. //
  489. c.add(COMMON);
  490. }
  491. return !remoteKnowsIsCommon;
  492. }
  493. });
  494. }
  495. private void markRefsAdvertised() {
  496. for (final Ref r : getRefs()) {
  497. markAdvertised(r.getObjectId());
  498. if (r.getPeeledObjectId() != null)
  499. markAdvertised(r.getPeeledObjectId());
  500. }
  501. }
  502. private void markAdvertised(final AnyObjectId id) {
  503. try {
  504. walk.parseAny(id).add(ADVERTISED);
  505. } catch (IOException readError) {
  506. // We probably just do not have this object locally.
  507. }
  508. }
  509. private void markCommon(final RevObject obj, final AckNackResult anr)
  510. throws IOException {
  511. if (statelessRPC && anr == AckNackResult.ACK_COMMON && !obj.has(STATE)) {
  512. StringBuilder s;
  513. s = new StringBuilder(6 + Constants.OBJECT_ID_STRING_LENGTH);
  514. s.append("have "); //$NON-NLS-1$
  515. s.append(obj.name());
  516. s.append('\n');
  517. pckState.writeString(s.toString());
  518. obj.add(STATE);
  519. }
  520. obj.add(COMMON);
  521. if (obj instanceof RevCommit)
  522. ((RevCommit) obj).carry(COMMON);
  523. }
  524. private void receivePack(final ProgressMonitor monitor) throws IOException {
  525. final IndexPack ip;
  526. InputStream input = in;
  527. if (sideband)
  528. input = new SideBandInputStream(input, monitor, getMessageWriter());
  529. ip = IndexPack.create(local, input);
  530. ip.setFixThin(thinPack);
  531. ip.setObjectChecking(transport.isCheckFetchedObjects());
  532. ip.index(monitor);
  533. packLock = ip.renameAndOpenPack(lockMessage);
  534. }
  535. private static class CancelledException extends Exception {
  536. private static final long serialVersionUID = 1L;
  537. }
  538. }