Big refactor: *Connection hierarchy
[egit/zawir.git] / org.spearce.jgit / src / org / spearce / jgit / transport / BasePackFetchConnection.java
blob04a91bf5ead51b5f59c2094664800d335921cea5
1 /*
2 * Copyright (C) 2008, Robin Rosenberg <robin.rosenberg@dewire.com>
3 * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org>
5 * All rights reserved.
7 * Redistribution and use in source and binary forms, with or
8 * without modification, are permitted provided that the following
9 * conditions are met:
11 * - Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
14 * - Redistributions in binary form must reproduce the above
15 * copyright notice, this list of conditions and the following
16 * disclaimer in the documentation and/or other materials provided
17 * with the distribution.
19 * - Neither the name of the Git Development Community nor the
20 * names of its contributors may be used to endorse or promote
21 * products derived from this software without specific prior
22 * written permission.
24 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
25 * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
26 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
27 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
29 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
30 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
31 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
32 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
33 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
34 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
35 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
36 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39 package org.spearce.jgit.transport;
41 import java.io.IOException;
42 import java.util.Collection;
43 import java.util.Date;
45 import org.spearce.jgit.errors.TransportException;
46 import org.spearce.jgit.lib.AnyObjectId;
47 import org.spearce.jgit.lib.MutableObjectId;
48 import org.spearce.jgit.lib.ProgressMonitor;
49 import org.spearce.jgit.lib.Ref;
50 import org.spearce.jgit.revwalk.RevCommit;
51 import org.spearce.jgit.revwalk.RevCommitList;
52 import org.spearce.jgit.revwalk.RevFlag;
53 import org.spearce.jgit.revwalk.RevObject;
54 import org.spearce.jgit.revwalk.RevSort;
55 import org.spearce.jgit.revwalk.RevWalk;
56 import org.spearce.jgit.revwalk.filter.CommitTimeRevFilter;
57 import org.spearce.jgit.revwalk.filter.RevFilter;
59 /**
60 * Fetch implementation using the native Git pack transfer service.
61 * <p>
62 * This is the canonical implementation for transferring objects from the remote
63 * repository to the local repository by talking to the 'git-upload-pack'
64 * service. Objects are packed on the remote side into a pack file and then sent
65 * down the pipe to us.
66 * <p>
67 * This connection requires only a bi-directional pipe or socket, and thus is
68 * easily wrapped up into a local process pipe, anonymous TCP socket, or a
69 * command executed through an SSH tunnel.
70 * <p>
71 * Concrete implementations should just call
72 * {@link #init(java.io.InputStream, java.io.OutputStream)} and
73 * {@link #readAdvertisedRefs()} methods in constructor or before any use. They
74 * should also handle resources releasing in {@link #close()} method if needed.
76 abstract class BasePackFetchConnection extends BasePackConnection implements
77 FetchConnection {
78 /**
79 * Maximum number of 'have' lines to send before giving up.
80 * <p>
81 * During {@link #negotiate(ProgressMonitor)} we send at most this many
82 * commits to the remote peer as 'have' lines without an ACK response before
83 * we give up.
85 private static final int MAX_HAVES = 256;
87 static final String OPTION_INCLUDE_TAG = "include-tag";
89 static final String OPTION_MULTI_ACK = "multi_ack";
91 static final String OPTION_THIN_PACK = "thin-pack";
93 static final String OPTION_SIDE_BAND = "side-band";
95 static final String OPTION_SIDE_BAND_64K = "side-band-64k";
97 static final String OPTION_OFS_DELTA = "ofs-delta";
99 static final String OPTION_SHALLOW = "shallow";
101 private final RevWalk walk;
103 /** All commits that are immediately reachable by a local ref. */
104 private RevCommitList<RevCommit> reachableCommits;
106 /** Marks an object as having all its dependencies. */
107 final RevFlag REACHABLE;
109 /** Marks a commit known to both sides of the connection. */
110 final RevFlag COMMON;
112 /** Marks a commit listed in the advertised refs. */
113 final RevFlag ADVERTISED;
115 private boolean multiAck;
117 private boolean thinPack;
119 private boolean sideband;
121 private boolean includeTags;
123 BasePackFetchConnection(final PackTransport packTransport) {
124 super(packTransport);
125 includeTags = packTransport.getTagOpt() != TagOpt.NO_TAGS;
126 thinPack = packTransport.isFetchThin();
128 walk = new RevWalk(local);
129 reachableCommits = new RevCommitList<RevCommit>();
130 REACHABLE = walk.newFlag("REACHABLE");
131 COMMON = walk.newFlag("COMMON");
132 ADVERTISED = walk.newFlag("ADVERTISED");
134 walk.carry(COMMON);
135 walk.carry(REACHABLE);
136 walk.carry(ADVERTISED);
139 public final void fetch(final ProgressMonitor monitor,
140 final Collection<Ref> want) throws TransportException {
141 markStartedOperation();
142 doFetch(monitor, want);
145 public boolean didFetchIncludeTags() {
146 return false;
149 protected void doFetch(final ProgressMonitor monitor,
150 final Collection<Ref> want) throws TransportException {
151 try {
152 markRefsAdvertised();
153 markReachable(maxTimeWanted(want));
155 if (sendWants(want)) {
156 negotiate(monitor);
158 walk.dispose();
159 reachableCommits = null;
161 receivePack(monitor);
163 } catch (CancelledException ce) {
164 close();
165 return; // Caller should test (or just know) this themselves.
166 } catch (IOException err) {
167 close();
168 throw new TransportException(err.getMessage(), err);
169 } catch (RuntimeException err) {
170 close();
171 throw new TransportException(err.getMessage(), err);
175 private int maxTimeWanted(final Collection<Ref> wants) {
176 int maxTime = 0;
177 for (final Ref r : wants) {
178 try {
179 final RevObject obj = walk.parseAny(r.getObjectId());
180 if (obj instanceof RevCommit) {
181 final int cTime = ((RevCommit) obj).getCommitTime();
182 if (maxTime < cTime)
183 maxTime = cTime;
185 } catch (IOException error) {
186 // We don't have it, but we want to fetch (thus fixing error).
189 return maxTime;
192 private void markReachable(final int maxTime) throws IOException {
193 for (final Ref r : local.getAllRefs().values()) {
194 try {
195 final RevCommit o = walk.parseCommit(r.getObjectId());
196 o.add(REACHABLE);
197 reachableCommits.add(o);
198 } catch (IOException readError) {
199 // If we cannot read the value of the ref skip it.
200 } catch (ClassCastException cce) {
201 // Not a commit type.
205 if (maxTime > 0) {
206 // Mark reachable commits until we reach maxTime. These may
207 // wind up later matching up against things we want and we
208 // can avoid asking for something we already happen to have.
210 final Date maxWhen = new Date(maxTime * 1000L);
211 walk.sort(RevSort.COMMIT_TIME_DESC);
212 walk.markStart(reachableCommits);
213 walk.setRevFilter(CommitTimeRevFilter.after(maxWhen));
214 for (;;) {
215 final RevCommit c = walk.next();
216 if (c == null)
217 break;
218 if (c.has(ADVERTISED) && !c.has(COMMON)) {
219 // This is actually going to be a common commit, but
220 // our peer doesn't know that fact yet.
222 c.add(COMMON);
223 c.carry(COMMON);
224 reachableCommits.add(c);
230 private boolean sendWants(final Collection<Ref> want) throws IOException {
231 boolean first = true;
232 for (final Ref r : want) {
233 try {
234 if (walk.parseAny(r.getObjectId()).has(REACHABLE)) {
235 // We already have this object. Asking for it is
236 // not a very good idea.
238 continue;
240 } catch (IOException err) {
241 // Its OK, we don't have it, but we want to fix that
242 // by fetching the object from the other side.
245 final StringBuilder line = new StringBuilder(46);
246 line.append("want ");
247 line.append(r.getObjectId());
248 if (first) {
249 line.append(enableCapabilities());
250 first = false;
252 line.append('\n');
253 pckOut.writeString(line.toString());
255 pckOut.end();
256 return !first;
259 private String enableCapabilities() {
260 final StringBuilder line = new StringBuilder();
261 if (includeTags)
262 includeTags = wantCapability(line, OPTION_INCLUDE_TAG);
263 wantCapability(line, OPTION_OFS_DELTA);
264 multiAck = wantCapability(line, OPTION_MULTI_ACK);
265 if (thinPack)
266 thinPack = wantCapability(line, OPTION_THIN_PACK);
267 if (wantCapability(line, OPTION_SIDE_BAND_64K))
268 sideband = true;
269 else if (wantCapability(line, OPTION_SIDE_BAND))
270 sideband = true;
271 return line.toString();
274 private void negotiate(final ProgressMonitor monitor) throws IOException,
275 CancelledException {
276 final MutableObjectId ackId = new MutableObjectId();
277 int resultsPending = 0;
278 int havesSent = 0;
279 int havesSinceLastContinue = 0;
280 boolean receivedContinue = false;
281 boolean receivedAck = false;
282 boolean sendHaves = true;
284 negotiateBegin();
285 while (sendHaves) {
286 final RevCommit c = walk.next();
287 if (c == null)
288 break;
290 pckOut.writeString("have " + c.getId() + "\n");
291 havesSent++;
292 havesSinceLastContinue++;
294 if ((31 & havesSent) != 0) {
295 // We group the have lines into blocks of 32, each marked
296 // with a flush (aka end). This one is within a block so
297 // continue with another have line.
299 continue;
302 if (monitor.isCancelled())
303 throw new CancelledException();
305 pckOut.end();
306 resultsPending++; // Each end will cause a result to come back.
308 if (havesSent == 32) {
309 // On the first block we race ahead and try to send
310 // more of the second block while waiting for the
311 // remote to respond to our first block request.
312 // This keeps us one block ahead of the peer.
314 continue;
317 while (resultsPending > 0) {
318 final PacketLineIn.AckNackResult anr;
320 anr = pckIn.readACK(ackId);
321 resultsPending--;
322 if (anr == PacketLineIn.AckNackResult.NAK) {
323 // More have lines are necessary to compute the
324 // pack on the remote side. Keep doing that.
326 break;
329 if (anr == PacketLineIn.AckNackResult.ACK) {
330 // The remote side is happy and knows exactly what
331 // to send us. There is no further negotiation and
332 // we can break out immediately.
334 multiAck = false;
335 resultsPending = 0;
336 receivedAck = true;
337 sendHaves = false;
338 break;
341 if (anr == PacketLineIn.AckNackResult.ACK_CONTINUE) {
342 // The server knows this commit (ackId). We don't
343 // need to send any further along its ancestry, but
344 // we need to continue to talk about other parts of
345 // our local history.
347 markCommon(walk.parseAny(ackId));
348 receivedAck = true;
349 receivedContinue = true;
350 havesSinceLastContinue = 0;
353 if (monitor.isCancelled())
354 throw new CancelledException();
357 if (receivedContinue && havesSinceLastContinue > MAX_HAVES) {
358 // Our history must be really different from the remote's.
359 // We just sent a whole slew of have lines, and it did not
360 // recognize any of them. Avoid sending our entire history
361 // to them by giving up early.
363 break;
367 // Tell the remote side we have run out of things to talk about.
369 if (monitor.isCancelled())
370 throw new CancelledException();
371 pckOut.writeString("done\n");
372 pckOut.flush();
374 if (!receivedAck) {
375 // Apparently if we have never received an ACK earlier
376 // there is one more result expected from the done we
377 // just sent to the remote.
379 multiAck = false;
380 resultsPending++;
383 while (resultsPending > 0 || multiAck) {
384 final PacketLineIn.AckNackResult anr;
386 anr = pckIn.readACK(ackId);
387 resultsPending--;
389 if (anr == PacketLineIn.AckNackResult.ACK)
390 break; // commit negotiation is finished.
392 if (anr == PacketLineIn.AckNackResult.ACK_CONTINUE) {
393 // There must be a normal ACK following this.
395 multiAck = true;
398 if (monitor.isCancelled())
399 throw new CancelledException();
403 private void negotiateBegin() throws IOException {
404 walk.resetRetain(REACHABLE, ADVERTISED);
405 walk.markStart(reachableCommits);
406 walk.sort(RevSort.COMMIT_TIME_DESC);
407 walk.setRevFilter(new RevFilter() {
408 @Override
409 public RevFilter clone() {
410 return this;
413 @Override
414 public boolean include(final RevWalk walker, final RevCommit c) {
415 final boolean remoteKnowsIsCommon = c.has(COMMON);
416 if (c.has(ADVERTISED)) {
417 // Remote advertised this, and we have it, hence common.
418 // Whether or not the remote knows that fact is tested
419 // before we added the flag. If the remote doesn't know
420 // we have to still send them this object.
422 c.add(COMMON);
424 return !remoteKnowsIsCommon;
429 private void markRefsAdvertised() {
430 for (final Ref r : getRefs()) {
431 markAdvertised(r.getObjectId());
432 if (r.getPeeledObjectId() != null)
433 markAdvertised(r.getPeeledObjectId());
437 private void markAdvertised(final AnyObjectId id) {
438 try {
439 walk.parseAny(id).add(ADVERTISED);
440 } catch (IOException readError) {
441 // We probably just do not have this object locally.
445 private void markCommon(final RevObject obj) {
446 obj.add(COMMON);
447 if (obj instanceof RevCommit)
448 ((RevCommit) obj).carry(COMMON);
451 private void receivePack(final ProgressMonitor monitor) throws IOException {
452 final IndexPack ip;
454 ip = IndexPack.create(local, sideband ? pckIn.sideband(monitor) : in);
455 ip.setFixThin(thinPack);
456 ip.index(monitor);
457 ip.renameAndOpenPack();
460 private static class CancelledException extends Exception {
461 private static final long serialVersionUID = 1L;