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.

WalkPushConnection.java 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. /*
  2. * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org>
  3. * and other copyright owners as documented in the project's IP log.
  4. *
  5. * This program and the accompanying materials are made available
  6. * under the terms of the Eclipse Distribution License v1.0 which
  7. * accompanies this distribution, is reproduced below, and is
  8. * available at http://www.eclipse.org/org/documents/edl-v10.php
  9. *
  10. * All rights reserved.
  11. *
  12. * Redistribution and use in source and binary forms, with or
  13. * without modification, are permitted provided that the following
  14. * conditions are met:
  15. *
  16. * - Redistributions of source code must retain the above copyright
  17. * notice, this list of conditions and the following disclaimer.
  18. *
  19. * - Redistributions in binary form must reproduce the above
  20. * copyright notice, this list of conditions and the following
  21. * disclaimer in the documentation and/or other materials provided
  22. * with the distribution.
  23. *
  24. * - Neither the name of the Eclipse Foundation, Inc. nor the
  25. * names of its contributors may be used to endorse or promote
  26. * products derived from this software without specific prior
  27. * written permission.
  28. *
  29. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  30. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  31. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  32. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  33. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  34. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  35. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  36. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  37. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  38. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  39. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  40. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  41. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  42. */
  43. package org.eclipse.jgit.transport;
  44. import static org.eclipse.jgit.transport.WalkRemoteObjectDatabase.ROOT_DIR;
  45. import java.io.IOException;
  46. import java.io.OutputStream;
  47. import java.util.ArrayList;
  48. import java.util.Collection;
  49. import java.util.HashSet;
  50. import java.util.LinkedHashMap;
  51. import java.util.List;
  52. import java.util.Map;
  53. import java.util.Set;
  54. import java.util.TreeMap;
  55. import org.eclipse.jgit.errors.TransportException;
  56. import org.eclipse.jgit.internal.JGitText;
  57. import org.eclipse.jgit.internal.storage.pack.PackWriter;
  58. import org.eclipse.jgit.lib.AnyObjectId;
  59. import org.eclipse.jgit.lib.Constants;
  60. import org.eclipse.jgit.lib.ObjectId;
  61. import org.eclipse.jgit.lib.ObjectIdRef;
  62. import org.eclipse.jgit.lib.ProgressMonitor;
  63. import org.eclipse.jgit.lib.Ref;
  64. import org.eclipse.jgit.lib.Ref.Storage;
  65. import org.eclipse.jgit.lib.RefWriter;
  66. import org.eclipse.jgit.lib.Repository;
  67. import org.eclipse.jgit.transport.RemoteRefUpdate.Status;
  68. import org.eclipse.jgit.util.io.SafeBufferedOutputStream;
  69. /**
  70. * Generic push support for dumb transport protocols.
  71. * <p>
  72. * Since there are no Git-specific smarts on the remote side of the connection
  73. * the client side must handle everything on its own. The generic push support
  74. * requires being able to delete, create and overwrite files on the remote side,
  75. * as well as create any missing directories (if necessary). Typically this can
  76. * be handled through an FTP style protocol.
  77. * <p>
  78. * Objects not on the remote side are uploaded as pack files, using one pack
  79. * file per invocation. This simplifies the implementation as only two data
  80. * files need to be written to the remote repository.
  81. * <p>
  82. * Push support supplied by this class is not multiuser safe. Concurrent pushes
  83. * to the same repository may yield an inconsistent reference database which may
  84. * confuse fetch clients.
  85. * <p>
  86. * A single push is concurrently safe with multiple fetch requests, due to the
  87. * careful order of operations used to update the repository. Clients fetching
  88. * may receive transient failures due to short reads on certain files if the
  89. * protocol does not support atomic file replacement.
  90. *
  91. * @see WalkRemoteObjectDatabase
  92. */
  93. class WalkPushConnection extends BaseConnection implements PushConnection {
  94. /** The repository this transport pushes out of. */
  95. private final Repository local;
  96. /** Location of the remote repository we are writing to. */
  97. private final URIish uri;
  98. /** Database connection to the remote repository. */
  99. private final WalkRemoteObjectDatabase dest;
  100. /** The configured transport we were constructed by. */
  101. private final Transport transport;
  102. /**
  103. * Packs already known to reside in the remote repository.
  104. * <p>
  105. * This is a LinkedHashMap to maintain the original order.
  106. */
  107. private LinkedHashMap<String, String> packNames;
  108. /** Complete listing of refs the remote will have after our push. */
  109. private Map<String, Ref> newRefs;
  110. /**
  111. * Updates which require altering the packed-refs file to complete.
  112. * <p>
  113. * If this collection is non-empty then any refs listed in {@link #newRefs}
  114. * with a storage class of {@link Storage#PACKED} will be written.
  115. */
  116. private Collection<RemoteRefUpdate> packedRefUpdates;
  117. WalkPushConnection(final WalkTransport walkTransport,
  118. final WalkRemoteObjectDatabase w) {
  119. transport = (Transport) walkTransport;
  120. local = transport.local;
  121. uri = transport.getURI();
  122. dest = w;
  123. }
  124. public void push(final ProgressMonitor monitor,
  125. final Map<String, RemoteRefUpdate> refUpdates)
  126. throws TransportException {
  127. push(monitor, refUpdates, null);
  128. }
  129. public void push(final ProgressMonitor monitor,
  130. final Map<String, RemoteRefUpdate> refUpdates, OutputStream out)
  131. throws TransportException {
  132. markStartedOperation();
  133. packNames = null;
  134. newRefs = new TreeMap<String, Ref>(getRefsMap());
  135. packedRefUpdates = new ArrayList<RemoteRefUpdate>(refUpdates.size());
  136. // Filter the commands and issue all deletes first. This way we
  137. // can correctly handle a directory being cleared out and a new
  138. // ref using the directory name being created.
  139. //
  140. final List<RemoteRefUpdate> updates = new ArrayList<RemoteRefUpdate>();
  141. for (final RemoteRefUpdate u : refUpdates.values()) {
  142. final String n = u.getRemoteName();
  143. if (!n.startsWith("refs/") || !Repository.isValidRefName(n)) { //$NON-NLS-1$
  144. u.setStatus(Status.REJECTED_OTHER_REASON);
  145. u.setMessage(JGitText.get().funnyRefname);
  146. continue;
  147. }
  148. if (AnyObjectId.equals(ObjectId.zeroId(), u.getNewObjectId()))
  149. deleteCommand(u);
  150. else
  151. updates.add(u);
  152. }
  153. // If we have any updates we need to upload the objects first, to
  154. // prevent creating refs pointing at non-existent data. Then we
  155. // can update the refs, and the info-refs file for dumb transports.
  156. //
  157. if (!updates.isEmpty())
  158. sendpack(updates, monitor);
  159. for (final RemoteRefUpdate u : updates)
  160. updateCommand(u);
  161. // Is this a new repository? If so we should create additional
  162. // metadata files so it is properly initialized during the push.
  163. //
  164. if (!updates.isEmpty() && isNewRepository())
  165. createNewRepository(updates);
  166. RefWriter refWriter = new RefWriter(newRefs.values()) {
  167. @Override
  168. protected void writeFile(String file, byte[] content)
  169. throws IOException {
  170. dest.writeFile(ROOT_DIR + file, content);
  171. }
  172. };
  173. if (!packedRefUpdates.isEmpty()) {
  174. try {
  175. refWriter.writePackedRefs();
  176. for (final RemoteRefUpdate u : packedRefUpdates)
  177. u.setStatus(Status.OK);
  178. } catch (IOException err) {
  179. for (final RemoteRefUpdate u : packedRefUpdates) {
  180. u.setStatus(Status.REJECTED_OTHER_REASON);
  181. u.setMessage(err.getMessage());
  182. }
  183. throw new TransportException(uri, JGitText.get().failedUpdatingRefs, err);
  184. }
  185. }
  186. try {
  187. refWriter.writeInfoRefs();
  188. } catch (IOException err) {
  189. throw new TransportException(uri, JGitText.get().failedUpdatingRefs, err);
  190. }
  191. }
  192. @Override
  193. public void close() {
  194. dest.close();
  195. }
  196. private void sendpack(final List<RemoteRefUpdate> updates,
  197. final ProgressMonitor monitor) throws TransportException {
  198. String pathPack = null;
  199. String pathIdx = null;
  200. try (final PackWriter writer = new PackWriter(transport.getPackConfig(),
  201. local.newObjectReader())) {
  202. final Set<ObjectId> need = new HashSet<ObjectId>();
  203. final Set<ObjectId> have = new HashSet<ObjectId>();
  204. for (final RemoteRefUpdate r : updates)
  205. need.add(r.getNewObjectId());
  206. for (final Ref r : getRefs()) {
  207. have.add(r.getObjectId());
  208. if (r.getPeeledObjectId() != null)
  209. have.add(r.getPeeledObjectId());
  210. }
  211. writer.preparePack(monitor, need, have);
  212. // We don't have to continue further if the pack will
  213. // be an empty pack, as the remote has all objects it
  214. // needs to complete this change.
  215. //
  216. if (writer.getObjectCount() == 0)
  217. return;
  218. packNames = new LinkedHashMap<String, String>();
  219. for (final String n : dest.getPackNames())
  220. packNames.put(n, n);
  221. final String base = "pack-" + writer.computeName().name(); //$NON-NLS-1$
  222. final String packName = base + ".pack"; //$NON-NLS-1$
  223. pathPack = "pack/" + packName; //$NON-NLS-1$
  224. pathIdx = "pack/" + base + ".idx"; //$NON-NLS-1$ //$NON-NLS-2$
  225. if (packNames.remove(packName) != null) {
  226. // The remote already contains this pack. We should
  227. // remove the index before overwriting to prevent bad
  228. // offsets from appearing to clients.
  229. //
  230. dest.writeInfoPacks(packNames.keySet());
  231. dest.deleteFile(pathIdx);
  232. }
  233. // Write the pack file, then the index, as readers look the
  234. // other direction (index, then pack file).
  235. //
  236. final String wt = "Put " + base.substring(0, 12); //$NON-NLS-1$
  237. OutputStream os = dest.writeFile(pathPack, monitor, wt + "..pack"); //$NON-NLS-1$
  238. try {
  239. os = new SafeBufferedOutputStream(os);
  240. writer.writePack(monitor, monitor, os);
  241. } finally {
  242. os.close();
  243. }
  244. os = dest.writeFile(pathIdx, monitor, wt + "..idx"); //$NON-NLS-1$
  245. try {
  246. os = new SafeBufferedOutputStream(os);
  247. writer.writeIndex(os);
  248. } finally {
  249. os.close();
  250. }
  251. // Record the pack at the start of the pack info list. This
  252. // way clients are likely to consult the newest pack first,
  253. // and discover the most recent objects there.
  254. //
  255. final ArrayList<String> infoPacks = new ArrayList<String>();
  256. infoPacks.add(packName);
  257. infoPacks.addAll(packNames.keySet());
  258. dest.writeInfoPacks(infoPacks);
  259. } catch (IOException err) {
  260. safeDelete(pathIdx);
  261. safeDelete(pathPack);
  262. throw new TransportException(uri, JGitText.get().cannotStoreObjects, err);
  263. }
  264. }
  265. private void safeDelete(final String path) {
  266. if (path != null) {
  267. try {
  268. dest.deleteFile(path);
  269. } catch (IOException cleanupFailure) {
  270. // Ignore the deletion failure. We probably are
  271. // already failing and were just trying to pick
  272. // up after ourselves.
  273. }
  274. }
  275. }
  276. private void deleteCommand(final RemoteRefUpdate u) {
  277. final Ref r = newRefs.remove(u.getRemoteName());
  278. if (r == null) {
  279. // Already gone.
  280. //
  281. u.setStatus(Status.OK);
  282. return;
  283. }
  284. if (r.getStorage().isPacked())
  285. packedRefUpdates.add(u);
  286. if (r.getStorage().isLoose()) {
  287. try {
  288. dest.deleteRef(u.getRemoteName());
  289. u.setStatus(Status.OK);
  290. } catch (IOException e) {
  291. u.setStatus(Status.REJECTED_OTHER_REASON);
  292. u.setMessage(e.getMessage());
  293. }
  294. }
  295. try {
  296. dest.deleteRefLog(u.getRemoteName());
  297. } catch (IOException e) {
  298. u.setStatus(Status.REJECTED_OTHER_REASON);
  299. u.setMessage(e.getMessage());
  300. }
  301. }
  302. private void updateCommand(final RemoteRefUpdate u) {
  303. try {
  304. dest.writeRef(u.getRemoteName(), u.getNewObjectId());
  305. newRefs.put(u.getRemoteName(), new ObjectIdRef.Unpeeled(
  306. Storage.LOOSE, u.getRemoteName(), u.getNewObjectId()));
  307. u.setStatus(Status.OK);
  308. } catch (IOException e) {
  309. u.setStatus(Status.REJECTED_OTHER_REASON);
  310. u.setMessage(e.getMessage());
  311. }
  312. }
  313. private boolean isNewRepository() {
  314. return getRefsMap().isEmpty() && packNames != null
  315. && packNames.isEmpty();
  316. }
  317. private void createNewRepository(final List<RemoteRefUpdate> updates)
  318. throws TransportException {
  319. try {
  320. final String ref = "ref: " + pickHEAD(updates) + "\n"; //$NON-NLS-1$ //$NON-NLS-2$
  321. final byte[] bytes = Constants.encode(ref);
  322. dest.writeFile(ROOT_DIR + Constants.HEAD, bytes);
  323. } catch (IOException e) {
  324. throw new TransportException(uri, JGitText.get().cannotCreateHEAD, e);
  325. }
  326. try {
  327. final String config = "[core]\n" //$NON-NLS-1$
  328. + "\trepositoryformatversion = 0\n"; //$NON-NLS-1$
  329. final byte[] bytes = Constants.encode(config);
  330. dest.writeFile(ROOT_DIR + Constants.CONFIG, bytes);
  331. } catch (IOException e) {
  332. throw new TransportException(uri, JGitText.get().cannotCreateConfig, e);
  333. }
  334. }
  335. private static String pickHEAD(final List<RemoteRefUpdate> updates) {
  336. // Try to use master if the user is pushing that, it is the
  337. // default branch and is likely what they want to remain as
  338. // the default on the new remote.
  339. //
  340. for (final RemoteRefUpdate u : updates) {
  341. final String n = u.getRemoteName();
  342. if (n.equals(Constants.R_HEADS + Constants.MASTER))
  343. return n;
  344. }
  345. // Pick any branch, under the assumption the user pushed only
  346. // one to the remote side.
  347. //
  348. for (final RemoteRefUpdate u : updates) {
  349. final String n = u.getRemoteName();
  350. if (n.startsWith(Constants.R_HEADS))
  351. return n;
  352. }
  353. return updates.get(0).getRemoteName();
  354. }
  355. }