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

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