View Javadoc
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  
45  package org.eclipse.jgit.transport;
46  
47  import static org.eclipse.jgit.transport.ReceiveCommand.Result.NOT_ATTEMPTED;
48  import static org.eclipse.jgit.transport.ReceiveCommand.Result.OK;
49  import static org.eclipse.jgit.transport.ReceiveCommand.Result.REJECTED_NONFASTFORWARD;
50  import static org.eclipse.jgit.transport.ReceiveCommand.Type.UPDATE_NONFASTFORWARD;
51  
52  import java.io.File;
53  import java.io.IOException;
54  import java.io.OutputStreamWriter;
55  import java.io.Writer;
56  import java.text.MessageFormat;
57  import java.util.ArrayList;
58  import java.util.Collection;
59  import java.util.Collections;
60  import java.util.HashMap;
61  import java.util.HashSet;
62  import java.util.Iterator;
63  import java.util.Map;
64  import java.util.Set;
65  import java.util.concurrent.TimeUnit;
66  
67  import org.eclipse.jgit.errors.MissingObjectException;
68  import org.eclipse.jgit.errors.NotSupportedException;
69  import org.eclipse.jgit.errors.TransportException;
70  import org.eclipse.jgit.internal.JGitText;
71  import org.eclipse.jgit.internal.storage.file.LockFile;
72  import org.eclipse.jgit.internal.storage.file.PackLock;
73  import org.eclipse.jgit.lib.BatchRefUpdate;
74  import org.eclipse.jgit.lib.BatchingProgressMonitor;
75  import org.eclipse.jgit.lib.Constants;
76  import org.eclipse.jgit.lib.ObjectId;
77  import org.eclipse.jgit.lib.ProgressMonitor;
78  import org.eclipse.jgit.lib.Ref;
79  import org.eclipse.jgit.lib.RefDatabase;
80  import org.eclipse.jgit.revwalk.ObjectWalk;
81  import org.eclipse.jgit.revwalk.RevWalk;
82  
83  class FetchProcess {
84  	/** Transport we will fetch over. */
85  	private final Transport transport;
86  
87  	/** List of things we want to fetch from the remote repository. */
88  	private final Collection<RefSpec> toFetch;
89  
90  	/** Set of refs we will actually wind up asking to obtain. */
91  	private final HashMap<ObjectId, Ref> askFor = new HashMap<ObjectId, Ref>();
92  
93  	/** Objects we know we have locally. */
94  	private final HashSet<ObjectId> have = new HashSet<ObjectId>();
95  
96  	/** Updates to local tracking branches (if any). */
97  	private final ArrayList<TrackingRefUpdate> localUpdates = new ArrayList<TrackingRefUpdate>();
98  
99  	/** Records to be recorded into FETCH_HEAD. */
100 	private final ArrayList<FetchHeadRecord> fetchHeadUpdates = new ArrayList<FetchHeadRecord>();
101 
102 	private final ArrayList<PackLock> packLocks = new ArrayList<PackLock>();
103 
104 	private FetchConnection conn;
105 
106 	private Map<String, Ref> localRefs;
107 
108 	FetchProcess(final Transport t, final Collection<RefSpec> f) {
109 		transport = t;
110 		toFetch = f;
111 	}
112 
113 	void execute(final ProgressMonitor monitor, final FetchResult result)
114 			throws NotSupportedException, TransportException {
115 		askFor.clear();
116 		localUpdates.clear();
117 		fetchHeadUpdates.clear();
118 		packLocks.clear();
119 		localRefs = null;
120 
121 		try {
122 			executeImp(monitor, result);
123 		} finally {
124 			try {
125 			for (final PackLock lock : packLocks)
126 				lock.unlock();
127 			} catch (IOException e) {
128 				throw new TransportException(e.getMessage(), e);
129 			}
130 		}
131 	}
132 
133 	private void executeImp(final ProgressMonitor monitor,
134 			final FetchResult result) throws NotSupportedException,
135 			TransportException {
136 		conn = transport.openFetch();
137 		try {
138 			result.setAdvertisedRefs(transport.getURI(), conn.getRefsMap());
139 			result.peerUserAgent = conn.getPeerUserAgent();
140 			final Set<Ref> matched = new HashSet<Ref>();
141 			for (final RefSpec spec : toFetch) {
142 				if (spec.getSource() == null)
143 					throw new TransportException(MessageFormat.format(
144 							JGitText.get().sourceRefNotSpecifiedForRefspec, spec));
145 
146 				if (spec.isWildcard())
147 					expandWildcard(spec, matched);
148 				else
149 					expandSingle(spec, matched);
150 			}
151 
152 			Collection<Ref> additionalTags = Collections.<Ref> emptyList();
153 			final TagOpt tagopt = transport.getTagOpt();
154 			if (tagopt == TagOpt.AUTO_FOLLOW)
155 				additionalTags = expandAutoFollowTags();
156 			else if (tagopt == TagOpt.FETCH_TAGS)
157 				expandFetchTags();
158 
159 			final boolean includedTags;
160 			if (!askFor.isEmpty() && !askForIsComplete()) {
161 				fetchObjects(monitor);
162 				includedTags = conn.didFetchIncludeTags();
163 
164 				// Connection was used for object transfer. If we
165 				// do another fetch we must open a new connection.
166 				//
167 				closeConnection(result);
168 			} else {
169 				includedTags = false;
170 			}
171 
172 			if (tagopt == TagOpt.AUTO_FOLLOW && !additionalTags.isEmpty()) {
173 				// There are more tags that we want to follow, but
174 				// not all were asked for on the initial request.
175 				//
176 				have.addAll(askFor.keySet());
177 				askFor.clear();
178 				for (final Ref r : additionalTags) {
179 					ObjectId id = r.getPeeledObjectId();
180 					if (id == null)
181 						id = r.getObjectId();
182 					if (transport.local.hasObject(id))
183 						wantTag(r);
184 				}
185 
186 				if (!askFor.isEmpty() && (!includedTags || !askForIsComplete())) {
187 					reopenConnection();
188 					if (!askFor.isEmpty())
189 						fetchObjects(monitor);
190 				}
191 			}
192 		} finally {
193 			closeConnection(result);
194 		}
195 
196 		BatchRefUpdate batch = transport.local.getRefDatabase()
197 				.newBatchUpdate()
198 				.setAllowNonFastForwards(true)
199 				.setRefLogMessage("fetch", true); //$NON-NLS-1$
200 		try (final RevWalk walk = new RevWalk(transport.local)) {
201 			if (monitor instanceof BatchingProgressMonitor) {
202 				((BatchingProgressMonitor) monitor).setDelayStart(
203 						250, TimeUnit.MILLISECONDS);
204 			}
205 			if (transport.isRemoveDeletedRefs())
206 				deleteStaleTrackingRefs(result, batch);
207 			for (TrackingRefUpdate u : localUpdates) {
208 				result.add(u);
209 				batch.addCommand(u.asReceiveCommand());
210 			}
211 			for (ReceiveCommand cmd : batch.getCommands()) {
212 				cmd.updateType(walk);
213 				if (cmd.getType() == UPDATE_NONFASTFORWARD
214 						&& cmd instanceof TrackingRefUpdate.Command
215 						&& !((TrackingRefUpdate.Command) cmd).canForceUpdate())
216 					cmd.setResult(REJECTED_NONFASTFORWARD);
217 			}
218 			if (transport.isDryRun()) {
219 				for (ReceiveCommand cmd : batch.getCommands()) {
220 					if (cmd.getResult() == NOT_ATTEMPTED)
221 						cmd.setResult(OK);
222 				}
223 			} else
224 				batch.execute(walk, monitor);
225 		} catch (IOException err) {
226 			throw new TransportException(MessageFormat.format(
227 					JGitText.get().failureUpdatingTrackingRef,
228 					getFirstFailedRefName(batch), err.getMessage()), err);
229 		}
230 
231 		if (!fetchHeadUpdates.isEmpty()) {
232 			try {
233 				updateFETCH_HEAD(result);
234 			} catch (IOException err) {
235 				throw new TransportException(MessageFormat.format(
236 						JGitText.get().failureUpdatingFETCH_HEAD, err.getMessage()), err);
237 			}
238 		}
239 	}
240 
241 	private void fetchObjects(final ProgressMonitor monitor)
242 			throws TransportException {
243 		try {
244 			conn.setPackLockMessage("jgit fetch " + transport.uri); //$NON-NLS-1$
245 			conn.fetch(monitor, askFor.values(), have);
246 		} finally {
247 			packLocks.addAll(conn.getPackLocks());
248 		}
249 		if (transport.isCheckFetchedObjects()
250 				&& !conn.didFetchTestConnectivity() && !askForIsComplete())
251 			throw new TransportException(transport.getURI(),
252 					JGitText.get().peerDidNotSupplyACompleteObjectGraph);
253 	}
254 
255 	private void closeConnection(final FetchResult result) {
256 		if (conn != null) {
257 			conn.close();
258 			result.addMessages(conn.getMessages());
259 			conn = null;
260 		}
261 	}
262 
263 	private void reopenConnection() throws NotSupportedException,
264 			TransportException {
265 		if (conn != null)
266 			return;
267 
268 		conn = transport.openFetch();
269 
270 		// Since we opened a new connection we cannot be certain
271 		// that the system we connected to has the same exact set
272 		// of objects available (think round-robin DNS and mirrors
273 		// that aren't updated at the same time).
274 		//
275 		// We rebuild our askFor list using only the refs that the
276 		// new connection has offered to us.
277 		//
278 		final HashMap<ObjectId, Ref> avail = new HashMap<ObjectId, Ref>();
279 		for (final Ref r : conn.getRefs())
280 			avail.put(r.getObjectId(), r);
281 
282 		final Collection<Ref> wants = new ArrayList<Ref>(askFor.values());
283 		askFor.clear();
284 		for (final Ref want : wants) {
285 			final Ref newRef = avail.get(want.getObjectId());
286 			if (newRef != null) {
287 				askFor.put(newRef.getObjectId(), newRef);
288 			} else {
289 				removeFetchHeadRecord(want.getObjectId());
290 				removeTrackingRefUpdate(want.getObjectId());
291 			}
292 		}
293 	}
294 
295 	private void removeTrackingRefUpdate(final ObjectId want) {
296 		final Iterator<TrackingRefUpdate> i = localUpdates.iterator();
297 		while (i.hasNext()) {
298 			final TrackingRefUpdate u = i.next();
299 			if (u.getNewObjectId().equals(want))
300 				i.remove();
301 		}
302 	}
303 
304 	private void removeFetchHeadRecord(final ObjectId want) {
305 		final Iterator<FetchHeadRecord> i = fetchHeadUpdates.iterator();
306 		while (i.hasNext()) {
307 			final FetchHeadRecord fh = i.next();
308 			if (fh.newValue.equals(want))
309 				i.remove();
310 		}
311 	}
312 
313 	private void updateFETCH_HEAD(final FetchResult result) throws IOException {
314 		File meta = transport.local.getDirectory();
315 		if (meta == null)
316 			return;
317 		final LockFile lock = new LockFile(new File(meta, "FETCH_HEAD"), //$NON-NLS-1$
318 				transport.local.getFS());
319 		try {
320 			if (lock.lock()) {
321 				final Writer w = new OutputStreamWriter(lock.getOutputStream());
322 				try {
323 					for (final FetchHeadRecord h : fetchHeadUpdates) {
324 						h.write(w);
325 						result.add(h);
326 					}
327 				} finally {
328 					w.close();
329 				}
330 				lock.commit();
331 			}
332 		} finally {
333 			lock.unlock();
334 		}
335 	}
336 
337 	private boolean askForIsComplete() throws TransportException {
338 		try {
339 			try (final ObjectWalk ow = new ObjectWalk(transport.local)) {
340 				for (final ObjectId want : askFor.keySet())
341 					ow.markStart(ow.parseAny(want));
342 				for (final Ref ref : localRefs().values())
343 					ow.markUninteresting(ow.parseAny(ref.getObjectId()));
344 				ow.checkConnectivity();
345 			}
346 			return true;
347 		} catch (MissingObjectException e) {
348 			return false;
349 		} catch (IOException e) {
350 			throw new TransportException(JGitText.get().unableToCheckConnectivity, e);
351 		}
352 	}
353 
354 	private void expandWildcard(final RefSpec spec, final Set<Ref> matched)
355 			throws TransportException {
356 		for (final Ref src : conn.getRefs()) {
357 			if (spec.matchSource(src) && matched.add(src))
358 				want(src, spec.expandFromSource(src));
359 		}
360 	}
361 
362 	private void expandSingle(final RefSpec spec, final Set<Ref> matched)
363 			throws TransportException {
364 		final Ref src = conn.getRef(spec.getSource());
365 		if (src == null) {
366 			throw new TransportException(MessageFormat.format(JGitText.get().remoteDoesNotHaveSpec, spec.getSource()));
367 		}
368 		if (matched.add(src))
369 			want(src, spec);
370 	}
371 
372 	private Collection<Ref> expandAutoFollowTags() throws TransportException {
373 		final Collection<Ref> additionalTags = new ArrayList<Ref>();
374 		final Map<String, Ref> haveRefs = localRefs();
375 		for (final Ref r : conn.getRefs()) {
376 			if (!isTag(r))
377 				continue;
378 
379 			Ref local = haveRefs.get(r.getName());
380 			if (local != null)
381 				// We already have a tag with this name, don't fetch it (even if
382 				// the local is different).
383 				continue;
384 
385 			ObjectId obj = r.getPeeledObjectId();
386 			if (obj == null)
387 				obj = r.getObjectId();
388 
389 			if (askFor.containsKey(obj) || transport.local.hasObject(obj))
390 				wantTag(r);
391 			else
392 				additionalTags.add(r);
393 		}
394 		return additionalTags;
395 	}
396 
397 	private void expandFetchTags() throws TransportException {
398 		final Map<String, Ref> haveRefs = localRefs();
399 		for (final Ref r : conn.getRefs()) {
400 			if (!isTag(r))
401 				continue;
402 			final Ref local = haveRefs.get(r.getName());
403 			if (local == null || !r.getObjectId().equals(local.getObjectId()))
404 				wantTag(r);
405 		}
406 	}
407 
408 	private void wantTag(final Ref r) throws TransportException {
409 		want(r, new RefSpec().setSource(r.getName())
410 				.setDestination(r.getName()).setForceUpdate(true));
411 	}
412 
413 	private void want(final Ref src, final RefSpec spec)
414 			throws TransportException {
415 		final ObjectId newId = src.getObjectId();
416 		if (spec.getDestination() != null) {
417 			final TrackingRefUpdate tru = createUpdate(spec, newId);
418 			if (newId.equals(tru.getOldObjectId()))
419 				return;
420 			localUpdates.add(tru);
421 		}
422 
423 		askFor.put(newId, src);
424 
425 		final FetchHeadRecord fhr = new FetchHeadRecord();
426 		fhr.newValue = newId;
427 		fhr.notForMerge = spec.getDestination() != null;
428 		fhr.sourceName = src.getName();
429 		fhr.sourceURI = transport.getURI();
430 		fetchHeadUpdates.add(fhr);
431 	}
432 
433 	private TrackingRefUpdate createUpdate(RefSpec spec, ObjectId newId)
434 			throws TransportException {
435 		Ref ref = localRefs().get(spec.getDestination());
436 		ObjectId oldId = ref != null && ref.getObjectId() != null
437 				? ref.getObjectId()
438 				: ObjectId.zeroId();
439 		return new TrackingRefUpdate(
440 				spec.isForceUpdate(),
441 				spec.getSource(),
442 				spec.getDestination(),
443 				oldId,
444 				newId);
445 	}
446 
447 	private Map<String, Ref> localRefs() throws TransportException {
448 		if (localRefs == null) {
449 			try {
450 				localRefs = transport.local.getRefDatabase()
451 						.getRefs(RefDatabase.ALL);
452 			} catch (IOException err) {
453 				throw new TransportException(JGitText.get().cannotListRefs, err);
454 			}
455 		}
456 		return localRefs;
457 	}
458 
459 	private void deleteStaleTrackingRefs(FetchResult result,
460 			BatchRefUpdate batch) throws IOException {
461 		for (final Ref ref : localRefs().values()) {
462 			final String refname = ref.getName();
463 			for (final RefSpec spec : toFetch) {
464 				if (spec.matchDestination(refname)) {
465 					final RefSpec s = spec.expandFromDestination(refname);
466 					if (result.getAdvertisedRef(s.getSource()) == null) {
467 						deleteTrackingRef(result, batch, s, ref);
468 					}
469 				}
470 			}
471 		}
472 	}
473 
474 	private void deleteTrackingRef(final FetchResult result,
475 			final BatchRefUpdate batch, final RefSpec spec, final Ref localRef) {
476 		if (localRef.getObjectId() == null)
477 			return;
478 		TrackingRefUpdate update = new TrackingRefUpdate(
479 				true,
480 				spec.getSource(),
481 				localRef.getName(),
482 				localRef.getObjectId(),
483 				ObjectId.zeroId());
484 		result.add(update);
485 		batch.addCommand(update.asReceiveCommand());
486 	}
487 
488 	private static boolean isTag(final Ref r) {
489 		return isTag(r.getName());
490 	}
491 
492 	private static boolean isTag(final String name) {
493 		return name.startsWith(Constants.R_TAGS);
494 	}
495 
496 	private static String getFirstFailedRefName(BatchRefUpdate batch) {
497 		for (ReceiveCommand cmd : batch.getCommands()) {
498 			if (cmd.getResult() != ReceiveCommand.Result.OK)
499 				return cmd.getRefName();
500 		}
501 		return ""; //$NON-NLS-1$
502 	}
503 }