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