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

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