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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  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. }
  185. addUpdateBatchCommands(result, batch);
  186. for (ReceiveCommand cmd : batch.getCommands()) {
  187. cmd.updateType(walk);
  188. if (cmd.getType() == UPDATE_NONFASTFORWARD
  189. && cmd instanceof TrackingRefUpdate.Command
  190. && !((TrackingRefUpdate.Command) cmd).canForceUpdate())
  191. cmd.setResult(REJECTED_NONFASTFORWARD);
  192. }
  193. if (transport.isDryRun()) {
  194. for (ReceiveCommand cmd : batch.getCommands()) {
  195. if (cmd.getResult() == NOT_ATTEMPTED)
  196. cmd.setResult(OK);
  197. }
  198. } else {
  199. batch.execute(walk, monitor);
  200. }
  201. } catch (TransportException e) {
  202. throw e;
  203. } catch (IOException err) {
  204. throw new TransportException(MessageFormat.format(
  205. JGitText.get().failureUpdatingTrackingRef,
  206. getFirstFailedRefName(batch), err.getMessage()), err);
  207. }
  208. if (!fetchHeadUpdates.isEmpty()) {
  209. try {
  210. updateFETCH_HEAD(result);
  211. } catch (IOException err) {
  212. throw new TransportException(MessageFormat.format(
  213. JGitText.get().failureUpdatingFETCH_HEAD, err.getMessage()), err);
  214. }
  215. }
  216. }
  217. private void addUpdateBatchCommands(FetchResult result,
  218. BatchRefUpdate batch) throws TransportException {
  219. Map<String, ObjectId> refs = new HashMap<>();
  220. for (TrackingRefUpdate u : localUpdates) {
  221. // Try to skip duplicates if they'd update to the same object ID
  222. ObjectId existing = refs.get(u.getLocalName());
  223. if (existing == null) {
  224. refs.put(u.getLocalName(), u.getNewObjectId());
  225. result.add(u);
  226. batch.addCommand(u.asReceiveCommand());
  227. } else if (!existing.equals(u.getNewObjectId())) {
  228. throw new TransportException(MessageFormat
  229. .format(JGitText.get().duplicateRef, u.getLocalName()));
  230. }
  231. }
  232. }
  233. private void fetchObjects(final ProgressMonitor monitor)
  234. throws TransportException {
  235. try {
  236. conn.setPackLockMessage("jgit fetch " + transport.uri); //$NON-NLS-1$
  237. conn.fetch(monitor, askFor.values(), have);
  238. } finally {
  239. packLocks.addAll(conn.getPackLocks());
  240. }
  241. if (transport.isCheckFetchedObjects()
  242. && !conn.didFetchTestConnectivity() && !askForIsComplete())
  243. throw new TransportException(transport.getURI(),
  244. JGitText.get().peerDidNotSupplyACompleteObjectGraph);
  245. }
  246. private void closeConnection(final FetchResult result) {
  247. if (conn != null) {
  248. conn.close();
  249. result.addMessages(conn.getMessages());
  250. conn = null;
  251. }
  252. }
  253. private void reopenConnection() throws NotSupportedException,
  254. TransportException {
  255. if (conn != null)
  256. return;
  257. conn = transport.openFetch();
  258. // Since we opened a new connection we cannot be certain
  259. // that the system we connected to has the same exact set
  260. // of objects available (think round-robin DNS and mirrors
  261. // that aren't updated at the same time).
  262. //
  263. // We rebuild our askFor list using only the refs that the
  264. // new connection has offered to us.
  265. //
  266. final HashMap<ObjectId, Ref> avail = new HashMap<>();
  267. for (final Ref r : conn.getRefs())
  268. avail.put(r.getObjectId(), r);
  269. final Collection<Ref> wants = new ArrayList<>(askFor.values());
  270. askFor.clear();
  271. for (final Ref want : wants) {
  272. final Ref newRef = avail.get(want.getObjectId());
  273. if (newRef != null) {
  274. askFor.put(newRef.getObjectId(), newRef);
  275. } else {
  276. removeFetchHeadRecord(want.getObjectId());
  277. removeTrackingRefUpdate(want.getObjectId());
  278. }
  279. }
  280. }
  281. private void removeTrackingRefUpdate(final ObjectId want) {
  282. final Iterator<TrackingRefUpdate> i = localUpdates.iterator();
  283. while (i.hasNext()) {
  284. final TrackingRefUpdate u = i.next();
  285. if (u.getNewObjectId().equals(want))
  286. i.remove();
  287. }
  288. }
  289. private void removeFetchHeadRecord(final ObjectId want) {
  290. final Iterator<FetchHeadRecord> i = fetchHeadUpdates.iterator();
  291. while (i.hasNext()) {
  292. final FetchHeadRecord fh = i.next();
  293. if (fh.newValue.equals(want))
  294. i.remove();
  295. }
  296. }
  297. private void updateFETCH_HEAD(final FetchResult result) throws IOException {
  298. File meta = transport.local.getDirectory();
  299. if (meta == null)
  300. return;
  301. final LockFile lock = new LockFile(new File(meta, "FETCH_HEAD")); //$NON-NLS-1$
  302. try {
  303. if (lock.lock()) {
  304. final Writer w = new OutputStreamWriter(lock.getOutputStream());
  305. try {
  306. for (final FetchHeadRecord h : fetchHeadUpdates) {
  307. h.write(w);
  308. result.add(h);
  309. }
  310. } finally {
  311. w.close();
  312. }
  313. lock.commit();
  314. }
  315. } finally {
  316. lock.unlock();
  317. }
  318. }
  319. private boolean askForIsComplete() throws TransportException {
  320. try {
  321. try (final ObjectWalk ow = new ObjectWalk(transport.local)) {
  322. for (final ObjectId want : askFor.keySet())
  323. ow.markStart(ow.parseAny(want));
  324. for (final Ref ref : localRefs().values())
  325. ow.markUninteresting(ow.parseAny(ref.getObjectId()));
  326. ow.checkConnectivity();
  327. }
  328. return true;
  329. } catch (MissingObjectException e) {
  330. return false;
  331. } catch (IOException e) {
  332. throw new TransportException(JGitText.get().unableToCheckConnectivity, e);
  333. }
  334. }
  335. private void expandWildcard(final RefSpec spec, final Set<Ref> matched)
  336. throws TransportException {
  337. for (final Ref src : conn.getRefs()) {
  338. if (spec.matchSource(src) && matched.add(src))
  339. want(src, spec.expandFromSource(src));
  340. }
  341. }
  342. private void expandSingle(final RefSpec spec, final Set<Ref> matched)
  343. throws TransportException {
  344. String want = spec.getSource();
  345. if (ObjectId.isId(want)) {
  346. want(ObjectId.fromString(want));
  347. return;
  348. }
  349. Ref src = conn.getRef(want);
  350. if (src == null) {
  351. throw new TransportException(MessageFormat.format(JGitText.get().remoteDoesNotHaveSpec, want));
  352. }
  353. if (matched.add(src)) {
  354. want(src, spec);
  355. }
  356. }
  357. private Collection<Ref> expandAutoFollowTags() throws TransportException {
  358. final Collection<Ref> additionalTags = new ArrayList<>();
  359. final Map<String, Ref> haveRefs = localRefs();
  360. for (final Ref r : conn.getRefs()) {
  361. if (!isTag(r))
  362. continue;
  363. Ref local = haveRefs.get(r.getName());
  364. if (local != null)
  365. // We already have a tag with this name, don't fetch it (even if
  366. // the local is different).
  367. continue;
  368. ObjectId obj = r.getPeeledObjectId();
  369. if (obj == null)
  370. obj = r.getObjectId();
  371. if (askFor.containsKey(obj) || transport.local.hasObject(obj))
  372. wantTag(r);
  373. else
  374. additionalTags.add(r);
  375. }
  376. return additionalTags;
  377. }
  378. private void expandFetchTags() throws TransportException {
  379. final Map<String, Ref> haveRefs = localRefs();
  380. for (final Ref r : conn.getRefs()) {
  381. if (!isTag(r)) {
  382. continue;
  383. }
  384. ObjectId id = r.getObjectId();
  385. if (id == null) {
  386. continue;
  387. }
  388. final Ref local = haveRefs.get(r.getName());
  389. if (local == null || !id.equals(local.getObjectId())) {
  390. wantTag(r);
  391. }
  392. }
  393. }
  394. private void wantTag(final Ref r) throws TransportException {
  395. want(r, new RefSpec().setSource(r.getName())
  396. .setDestination(r.getName()).setForceUpdate(true));
  397. }
  398. private void want(final Ref src, final RefSpec spec)
  399. throws TransportException {
  400. final ObjectId newId = src.getObjectId();
  401. if (newId == null) {
  402. throw new NullPointerException(MessageFormat.format(
  403. JGitText.get().transportProvidedRefWithNoObjectId,
  404. src.getName()));
  405. }
  406. if (spec.getDestination() != null) {
  407. final TrackingRefUpdate tru = createUpdate(spec, newId);
  408. if (newId.equals(tru.getOldObjectId()))
  409. return;
  410. localUpdates.add(tru);
  411. }
  412. askFor.put(newId, src);
  413. final FetchHeadRecord fhr = new FetchHeadRecord();
  414. fhr.newValue = newId;
  415. fhr.notForMerge = spec.getDestination() != null;
  416. fhr.sourceName = src.getName();
  417. fhr.sourceURI = transport.getURI();
  418. fetchHeadUpdates.add(fhr);
  419. }
  420. private void want(ObjectId id) {
  421. askFor.put(id,
  422. new ObjectIdRef.Unpeeled(Ref.Storage.NETWORK, id.name(), id));
  423. }
  424. private TrackingRefUpdate createUpdate(RefSpec spec, ObjectId newId)
  425. throws TransportException {
  426. Ref ref = localRefs().get(spec.getDestination());
  427. ObjectId oldId = ref != null && ref.getObjectId() != null
  428. ? ref.getObjectId()
  429. : ObjectId.zeroId();
  430. return new TrackingRefUpdate(
  431. spec.isForceUpdate(),
  432. spec.getSource(),
  433. spec.getDestination(),
  434. oldId,
  435. newId);
  436. }
  437. private Map<String, Ref> localRefs() throws TransportException {
  438. if (localRefs == null) {
  439. try {
  440. localRefs = transport.local.getRefDatabase()
  441. .getRefs(RefDatabase.ALL);
  442. } catch (IOException err) {
  443. throw new TransportException(JGitText.get().cannotListRefs, err);
  444. }
  445. }
  446. return localRefs;
  447. }
  448. private void deleteStaleTrackingRefs(FetchResult result,
  449. BatchRefUpdate batch) throws IOException {
  450. final Set<Ref> processed = new HashSet<>();
  451. for (final Ref ref : localRefs().values()) {
  452. final String refname = ref.getName();
  453. for (final RefSpec spec : toFetch) {
  454. if (spec.matchDestination(refname)) {
  455. final RefSpec s = spec.expandFromDestination(refname);
  456. if (result.getAdvertisedRef(s.getSource()) == null
  457. && processed.add(ref)) {
  458. deleteTrackingRef(result, batch, s, ref);
  459. }
  460. }
  461. }
  462. }
  463. }
  464. private void deleteTrackingRef(final FetchResult result,
  465. final BatchRefUpdate batch, final RefSpec spec, final Ref localRef) {
  466. if (localRef.getObjectId() == null)
  467. return;
  468. TrackingRefUpdate update = new TrackingRefUpdate(
  469. true,
  470. spec.getSource(),
  471. localRef.getName(),
  472. localRef.getObjectId(),
  473. ObjectId.zeroId());
  474. result.add(update);
  475. batch.addCommand(update.asReceiveCommand());
  476. }
  477. private static boolean isTag(final Ref r) {
  478. return isTag(r.getName());
  479. }
  480. private static boolean isTag(final String name) {
  481. return name.startsWith(Constants.R_TAGS);
  482. }
  483. private static String getFirstFailedRefName(BatchRefUpdate batch) {
  484. for (ReceiveCommand cmd : batch.getCommands()) {
  485. if (cmd.getResult() != ReceiveCommand.Result.OK)
  486. return cmd.getRefName();
  487. }
  488. return ""; //$NON-NLS-1$
  489. }
  490. }