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

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