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 14KB

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