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.

FetchProcess.java 15KB

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