1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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
86 private final Transport transport;
87
88
89 private final Collection<RefSpec> toFetch;
90
91
92 private final HashMap<ObjectId, Ref> askFor = new HashMap<>();
93
94
95 private final HashSet<ObjectId> have = new HashSet<>();
96
97
98 private final ArrayList<TrackingRefUpdate> localUpdates = new ArrayList<>();
99
100
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(final Transport t, final Collection<RefSpec> f) {
110 transport = t;
111 toFetch = f;
112 }
113
114 void execute(final ProgressMonitor monitor, final 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 (final 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 (final 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
166
167
168 closeConnection(result);
169 } else {
170 includedTags = false;
171 }
172
173 if (tagopt == TagOpt.AUTO_FOLLOW && !additionalTags.isEmpty()) {
174
175
176
177 have.addAll(askFor.keySet());
178 askFor.clear();
179 for (final 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);
201 try (final 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 for (TrackingRefUpdate u : localUpdates) {
209 result.add(u);
210 batch.addCommand(u.asReceiveCommand());
211 }
212 for (ReceiveCommand cmd : batch.getCommands()) {
213 cmd.updateType(walk);
214 if (cmd.getType() == UPDATE_NONFASTFORWARD
215 && cmd instanceof TrackingRefUpdate.Command
216 && !((TrackingRefUpdate.Command) cmd).canForceUpdate())
217 cmd.setResult(REJECTED_NONFASTFORWARD);
218 }
219 if (transport.isDryRun()) {
220 for (ReceiveCommand cmd : batch.getCommands()) {
221 if (cmd.getResult() == NOT_ATTEMPTED)
222 cmd.setResult(OK);
223 }
224 } else
225 batch.execute(walk, monitor);
226 } catch (IOException err) {
227 throw new TransportException(MessageFormat.format(
228 JGitText.get().failureUpdatingTrackingRef,
229 getFirstFailedRefName(batch), err.getMessage()), err);
230 }
231
232 if (!fetchHeadUpdates.isEmpty()) {
233 try {
234 updateFETCH_HEAD(result);
235 } catch (IOException err) {
236 throw new TransportException(MessageFormat.format(
237 JGitText.get().failureUpdatingFETCH_HEAD, err.getMessage()), err);
238 }
239 }
240 }
241
242 private void fetchObjects(final ProgressMonitor monitor)
243 throws TransportException {
244 try {
245 conn.setPackLockMessage("jgit fetch " + transport.uri);
246 conn.fetch(monitor, askFor.values(), have);
247 } finally {
248 packLocks.addAll(conn.getPackLocks());
249 }
250 if (transport.isCheckFetchedObjects()
251 && !conn.didFetchTestConnectivity() && !askForIsComplete())
252 throw new TransportException(transport.getURI(),
253 JGitText.get().peerDidNotSupplyACompleteObjectGraph);
254 }
255
256 private void closeConnection(final FetchResult result) {
257 if (conn != null) {
258 conn.close();
259 result.addMessages(conn.getMessages());
260 conn = null;
261 }
262 }
263
264 private void reopenConnection() throws NotSupportedException,
265 TransportException {
266 if (conn != null)
267 return;
268
269 conn = transport.openFetch();
270
271
272
273
274
275
276
277
278
279 final HashMap<ObjectId, Ref> avail = new HashMap<>();
280 for (final Ref r : conn.getRefs())
281 avail.put(r.getObjectId(), r);
282
283 final Collection<Ref> wants = new ArrayList<>(askFor.values());
284 askFor.clear();
285 for (final Ref want : wants) {
286 final Ref newRef = avail.get(want.getObjectId());
287 if (newRef != null) {
288 askFor.put(newRef.getObjectId(), newRef);
289 } else {
290 removeFetchHeadRecord(want.getObjectId());
291 removeTrackingRefUpdate(want.getObjectId());
292 }
293 }
294 }
295
296 private void removeTrackingRefUpdate(final ObjectId want) {
297 final Iterator<TrackingRefUpdate> i = localUpdates.iterator();
298 while (i.hasNext()) {
299 final TrackingRefUpdate u = i.next();
300 if (u.getNewObjectId().equals(want))
301 i.remove();
302 }
303 }
304
305 private void removeFetchHeadRecord(final ObjectId want) {
306 final Iterator<FetchHeadRecord> i = fetchHeadUpdates.iterator();
307 while (i.hasNext()) {
308 final FetchHeadRecord fh = i.next();
309 if (fh.newValue.equals(want))
310 i.remove();
311 }
312 }
313
314 private void updateFETCH_HEAD(final FetchResult result) throws IOException {
315 File meta = transport.local.getDirectory();
316 if (meta == null)
317 return;
318 final LockFile lock = new LockFile(new File(meta, "FETCH_HEAD"));
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 String want = spec.getSource();
365 if (ObjectId.isId(want)) {
366 want(ObjectId.fromString(want));
367 return;
368 }
369
370 Ref src = conn.getRef(want);
371 if (src == null) {
372 throw new TransportException(MessageFormat.format(JGitText.get().remoteDoesNotHaveSpec, want));
373 }
374 if (matched.add(src)) {
375 want(src, spec);
376 }
377 }
378
379 private Collection<Ref> expandAutoFollowTags() throws TransportException {
380 final Collection<Ref> additionalTags = new ArrayList<>();
381 final Map<String, Ref> haveRefs = localRefs();
382 for (final Ref r : conn.getRefs()) {
383 if (!isTag(r))
384 continue;
385
386 Ref local = haveRefs.get(r.getName());
387 if (local != null)
388
389
390 continue;
391
392 ObjectId obj = r.getPeeledObjectId();
393 if (obj == null)
394 obj = r.getObjectId();
395
396 if (askFor.containsKey(obj) || transport.local.hasObject(obj))
397 wantTag(r);
398 else
399 additionalTags.add(r);
400 }
401 return additionalTags;
402 }
403
404 private void expandFetchTags() throws TransportException {
405 final Map<String, Ref> haveRefs = localRefs();
406 for (final Ref r : conn.getRefs()) {
407 if (!isTag(r)) {
408 continue;
409 }
410 ObjectId id = r.getObjectId();
411 if (id == null) {
412 continue;
413 }
414 final Ref local = haveRefs.get(r.getName());
415 if (local == null || !id.equals(local.getObjectId())) {
416 wantTag(r);
417 }
418 }
419 }
420
421 private void wantTag(final Ref r) throws TransportException {
422 want(r, new RefSpec().setSource(r.getName())
423 .setDestination(r.getName()).setForceUpdate(true));
424 }
425
426 private void want(final Ref src, final RefSpec spec)
427 throws TransportException {
428 final ObjectId newId = src.getObjectId();
429 if (newId == null) {
430 throw new NullPointerException(MessageFormat.format(
431 JGitText.get().transportProvidedRefWithNoObjectId,
432 src.getName()));
433 }
434 if (spec.getDestination() != null) {
435 final TrackingRefUpdate tru = createUpdate(spec, newId);
436 if (newId.equals(tru.getOldObjectId()))
437 return;
438 localUpdates.add(tru);
439 }
440
441 askFor.put(newId, src);
442
443 final FetchHeadRecord fhr = new FetchHeadRecord();
444 fhr.newValue = newId;
445 fhr.notForMerge = spec.getDestination() != null;
446 fhr.sourceName = src.getName();
447 fhr.sourceURI = transport.getURI();
448 fetchHeadUpdates.add(fhr);
449 }
450
451 private void want(ObjectId id) {
452 askFor.put(id,
453 new ObjectIdRef.Unpeeled(Ref.Storage.NETWORK, id.name(), id));
454 }
455
456 private TrackingRefUpdate createUpdate(RefSpec spec, ObjectId newId)
457 throws TransportException {
458 Ref ref = localRefs().get(spec.getDestination());
459 ObjectId oldId = ref != null && ref.getObjectId() != null
460 ? ref.getObjectId()
461 : ObjectId.zeroId();
462 return new TrackingRefUpdate(
463 spec.isForceUpdate(),
464 spec.getSource(),
465 spec.getDestination(),
466 oldId,
467 newId);
468 }
469
470 private Map<String, Ref> localRefs() throws TransportException {
471 if (localRefs == null) {
472 try {
473 localRefs = transport.local.getRefDatabase()
474 .getRefs(RefDatabase.ALL);
475 } catch (IOException err) {
476 throw new TransportException(JGitText.get().cannotListRefs, err);
477 }
478 }
479 return localRefs;
480 }
481
482 private void deleteStaleTrackingRefs(FetchResult result,
483 BatchRefUpdate batch) throws IOException {
484 for (final Ref ref : localRefs().values()) {
485 final String refname = ref.getName();
486 for (final RefSpec spec : toFetch) {
487 if (spec.matchDestination(refname)) {
488 final RefSpec s = spec.expandFromDestination(refname);
489 if (result.getAdvertisedRef(s.getSource()) == null) {
490 deleteTrackingRef(result, batch, s, ref);
491 }
492 }
493 }
494 }
495 }
496
497 private void deleteTrackingRef(final FetchResult result,
498 final BatchRefUpdate batch, final RefSpec spec, final Ref localRef) {
499 if (localRef.getObjectId() == null)
500 return;
501 TrackingRefUpdate update = new TrackingRefUpdate(
502 true,
503 spec.getSource(),
504 localRef.getName(),
505 localRef.getObjectId(),
506 ObjectId.zeroId());
507 result.add(update);
508 batch.addCommand(update.asReceiveCommand());
509 }
510
511 private static boolean isTag(final Ref r) {
512 return isTag(r.getName());
513 }
514
515 private static boolean isTag(final String name) {
516 return name.startsWith(Constants.R_TAGS);
517 }
518
519 private static String getFirstFailedRefName(BatchRefUpdate batch) {
520 for (ReceiveCommand cmd : batch.getCommands()) {
521 if (cmd.getResult() != ReceiveCommand.Result.OK)
522 return cmd.getRefName();
523 }
524 return "";
525 }
526 }