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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  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.BufferedOutputStream;
  46. import java.io.IOException;
  47. import java.io.OutputStream;
  48. import java.util.ArrayList;
  49. import java.util.Collection;
  50. import java.util.LinkedHashMap;
  51. import java.util.List;
  52. import java.util.Map;
  53. import java.util.TreeMap;
  54. import org.eclipse.jgit.JGitText;
  55. import org.eclipse.jgit.errors.TransportException;
  56. import org.eclipse.jgit.lib.AnyObjectId;
  57. import org.eclipse.jgit.lib.Constants;
  58. import org.eclipse.jgit.lib.ObjectId;
  59. import org.eclipse.jgit.lib.ObjectIdRef;
  60. import org.eclipse.jgit.lib.ProgressMonitor;
  61. import org.eclipse.jgit.lib.Ref;
  62. import org.eclipse.jgit.lib.RefWriter;
  63. import org.eclipse.jgit.lib.Repository;
  64. import org.eclipse.jgit.lib.Ref.Storage;
  65. import org.eclipse.jgit.storage.pack.PackWriter;
  66. import org.eclipse.jgit.transport.RemoteRefUpdate.Status;
  67. /**
  68. * Generic push support for dumb transport protocols.
  69. * <p>
  70. * Since there are no Git-specific smarts on the remote side of the connection
  71. * the client side must handle everything on its own. The generic push support
  72. * requires being able to delete, create and overwrite files on the remote side,
  73. * as well as create any missing directories (if necessary). Typically this can
  74. * be handled through an FTP style protocol.
  75. * <p>
  76. * Objects not on the remote side are uploaded as pack files, using one pack
  77. * file per invocation. This simplifies the implementation as only two data
  78. * files need to be written to the remote repository.
  79. * <p>
  80. * Push support supplied by this class is not multiuser safe. Concurrent pushes
  81. * to the same repository may yield an inconsistent reference database which may
  82. * confuse fetch clients.
  83. * <p>
  84. * A single push is concurrently safe with multiple fetch requests, due to the
  85. * careful order of operations used to update the repository. Clients fetching
  86. * may receive transient failures due to short reads on certain files if the
  87. * protocol does not support atomic file replacement.
  88. *
  89. * @see WalkRemoteObjectDatabase
  90. */
  91. class WalkPushConnection extends BaseConnection implements PushConnection {
  92. /** The repository this transport pushes out of. */
  93. private final Repository local;
  94. /** Location of the remote repository we are writing to. */
  95. private final URIish uri;
  96. /** Database connection to the remote repository. */
  97. private final WalkRemoteObjectDatabase dest;
  98. /** The configured transport we were constructed by. */
  99. private final Transport transport;
  100. /**
  101. * Packs already known to reside in the remote repository.
  102. * <p>
  103. * This is a LinkedHashMap to maintain the original order.
  104. */
  105. private LinkedHashMap<String, String> packNames;
  106. /** Complete listing of refs the remote will have after our push. */
  107. private Map<String, Ref> newRefs;
  108. /**
  109. * Updates which require altering the packed-refs file to complete.
  110. * <p>
  111. * If this collection is non-empty then any refs listed in {@link #newRefs}
  112. * with a storage class of {@link Storage#PACKED} will be written.
  113. */
  114. private Collection<RemoteRefUpdate> packedRefUpdates;
  115. WalkPushConnection(final WalkTransport walkTransport,
  116. final WalkRemoteObjectDatabase w) {
  117. transport = (Transport) walkTransport;
  118. local = transport.local;
  119. uri = transport.getURI();
  120. dest = w;
  121. }
  122. public void push(final ProgressMonitor monitor,
  123. final Map<String, RemoteRefUpdate> refUpdates)
  124. throws TransportException {
  125. markStartedOperation();
  126. packNames = null;
  127. newRefs = new TreeMap<String, Ref>(getRefsMap());
  128. packedRefUpdates = new ArrayList<RemoteRefUpdate>(refUpdates.size());
  129. // Filter the commands and issue all deletes first. This way we
  130. // can correctly handle a directory being cleared out and a new
  131. // ref using the directory name being created.
  132. //
  133. final List<RemoteRefUpdate> updates = new ArrayList<RemoteRefUpdate>();
  134. for (final RemoteRefUpdate u : refUpdates.values()) {
  135. final String n = u.getRemoteName();
  136. if (!n.startsWith("refs/") || !Repository.isValidRefName(n)) {
  137. u.setStatus(Status.REJECTED_OTHER_REASON);
  138. u.setMessage(JGitText.get().funnyRefname);
  139. continue;
  140. }
  141. if (AnyObjectId.equals(ObjectId.zeroId(), u.getNewObjectId()))
  142. deleteCommand(u);
  143. else
  144. updates.add(u);
  145. }
  146. // If we have any updates we need to upload the objects first, to
  147. // prevent creating refs pointing at non-existent data. Then we
  148. // can update the refs, and the info-refs file for dumb transports.
  149. //
  150. if (!updates.isEmpty())
  151. sendpack(updates, monitor);
  152. for (final RemoteRefUpdate u : updates)
  153. updateCommand(u);
  154. // Is this a new repository? If so we should create additional
  155. // metadata files so it is properly initialized during the push.
  156. //
  157. if (!updates.isEmpty() && isNewRepository())
  158. createNewRepository(updates);
  159. RefWriter refWriter = new RefWriter(newRefs.values()) {
  160. @Override
  161. protected void writeFile(String file, byte[] content)
  162. throws IOException {
  163. dest.writeFile(ROOT_DIR + file, content);
  164. }
  165. };
  166. if (!packedRefUpdates.isEmpty()) {
  167. try {
  168. refWriter.writePackedRefs();
  169. for (final RemoteRefUpdate u : packedRefUpdates)
  170. u.setStatus(Status.OK);
  171. } catch (IOException err) {
  172. for (final RemoteRefUpdate u : packedRefUpdates) {
  173. u.setStatus(Status.REJECTED_OTHER_REASON);
  174. u.setMessage(err.getMessage());
  175. }
  176. throw new TransportException(uri, JGitText.get().failedUpdatingRefs, err);
  177. }
  178. }
  179. try {
  180. refWriter.writeInfoRefs();
  181. } catch (IOException err) {
  182. throw new TransportException(uri, JGitText.get().failedUpdatingRefs, err);
  183. }
  184. }
  185. @Override
  186. public void close() {
  187. dest.close();
  188. }
  189. private void sendpack(final List<RemoteRefUpdate> updates,
  190. final ProgressMonitor monitor) throws TransportException {
  191. String pathPack = null;
  192. String pathIdx = null;
  193. final PackWriter writer = new PackWriter(transport.getPackConfig(),
  194. local.newObjectReader());
  195. try {
  196. final List<ObjectId> need = new ArrayList<ObjectId>();
  197. final List<ObjectId> have = new ArrayList<ObjectId>();
  198. for (final RemoteRefUpdate r : updates)
  199. need.add(r.getNewObjectId());
  200. for (final Ref r : getRefs()) {
  201. have.add(r.getObjectId());
  202. if (r.getPeeledObjectId() != null)
  203. have.add(r.getPeeledObjectId());
  204. }
  205. writer.preparePack(monitor, need, have);
  206. // We don't have to continue further if the pack will
  207. // be an empty pack, as the remote has all objects it
  208. // needs to complete this change.
  209. //
  210. if (writer.getObjectCount() == 0)
  211. return;
  212. packNames = new LinkedHashMap<String, String>();
  213. for (final String n : dest.getPackNames())
  214. packNames.put(n, n);
  215. final String base = "pack-" + writer.computeName().name();
  216. final String packName = base + ".pack";
  217. pathPack = "pack/" + packName;
  218. pathIdx = "pack/" + base + ".idx";
  219. if (packNames.remove(packName) != null) {
  220. // The remote already contains this pack. We should
  221. // remove the index before overwriting to prevent bad
  222. // offsets from appearing to clients.
  223. //
  224. dest.writeInfoPacks(packNames.keySet());
  225. dest.deleteFile(pathIdx);
  226. }
  227. // Write the pack file, then the index, as readers look the
  228. // other direction (index, then pack file).
  229. //
  230. final String wt = "Put " + base.substring(0, 12);
  231. OutputStream os = dest.writeFile(pathPack, monitor, wt + "..pack");
  232. try {
  233. os = new BufferedOutputStream(os);
  234. writer.writePack(monitor, monitor, os);
  235. } finally {
  236. os.close();
  237. }
  238. os = dest.writeFile(pathIdx, monitor, wt + "..idx");
  239. try {
  240. os = new BufferedOutputStream(os);
  241. writer.writeIndex(os);
  242. } finally {
  243. os.close();
  244. }
  245. // Record the pack at the start of the pack info list. This
  246. // way clients are likely to consult the newest pack first,
  247. // and discover the most recent objects there.
  248. //
  249. final ArrayList<String> infoPacks = new ArrayList<String>();
  250. infoPacks.add(packName);
  251. infoPacks.addAll(packNames.keySet());
  252. dest.writeInfoPacks(infoPacks);
  253. } catch (IOException err) {
  254. safeDelete(pathIdx);
  255. safeDelete(pathPack);
  256. throw new TransportException(uri, JGitText.get().cannotStoreObjects, err);
  257. } finally {
  258. writer.release();
  259. }
  260. }
  261. private void safeDelete(final String path) {
  262. if (path != null) {
  263. try {
  264. dest.deleteFile(path);
  265. } catch (IOException cleanupFailure) {
  266. // Ignore the deletion failure. We probably are
  267. // already failing and were just trying to pick
  268. // up after ourselves.
  269. }
  270. }
  271. }
  272. private void deleteCommand(final RemoteRefUpdate u) {
  273. final Ref r = newRefs.remove(u.getRemoteName());
  274. if (r == null) {
  275. // Already gone.
  276. //
  277. u.setStatus(Status.OK);
  278. return;
  279. }
  280. if (r.getStorage().isPacked())
  281. packedRefUpdates.add(u);
  282. if (r.getStorage().isLoose()) {
  283. try {
  284. dest.deleteRef(u.getRemoteName());
  285. u.setStatus(Status.OK);
  286. } catch (IOException e) {
  287. u.setStatus(Status.REJECTED_OTHER_REASON);
  288. u.setMessage(e.getMessage());
  289. }
  290. }
  291. try {
  292. dest.deleteRefLog(u.getRemoteName());
  293. } catch (IOException e) {
  294. u.setStatus(Status.REJECTED_OTHER_REASON);
  295. u.setMessage(e.getMessage());
  296. }
  297. }
  298. private void updateCommand(final RemoteRefUpdate u) {
  299. try {
  300. dest.writeRef(u.getRemoteName(), u.getNewObjectId());
  301. newRefs.put(u.getRemoteName(), new ObjectIdRef.Unpeeled(
  302. Storage.LOOSE, u.getRemoteName(), u.getNewObjectId()));
  303. u.setStatus(Status.OK);
  304. } catch (IOException e) {
  305. u.setStatus(Status.REJECTED_OTHER_REASON);
  306. u.setMessage(e.getMessage());
  307. }
  308. }
  309. private boolean isNewRepository() {
  310. return getRefsMap().isEmpty() && packNames != null
  311. && packNames.isEmpty();
  312. }
  313. private void createNewRepository(final List<RemoteRefUpdate> updates)
  314. throws TransportException {
  315. try {
  316. final String ref = "ref: " + pickHEAD(updates) + "\n";
  317. final byte[] bytes = Constants.encode(ref);
  318. dest.writeFile(ROOT_DIR + Constants.HEAD, bytes);
  319. } catch (IOException e) {
  320. throw new TransportException(uri, JGitText.get().cannotCreateHEAD, e);
  321. }
  322. try {
  323. final String config = "[core]\n"
  324. + "\trepositoryformatversion = 0\n";
  325. final byte[] bytes = Constants.encode(config);
  326. dest.writeFile(ROOT_DIR + "config", bytes);
  327. } catch (IOException e) {
  328. throw new TransportException(uri, JGitText.get().cannotCreateConfig, e);
  329. }
  330. }
  331. private static String pickHEAD(final List<RemoteRefUpdate> updates) {
  332. // Try to use master if the user is pushing that, it is the
  333. // default branch and is likely what they want to remain as
  334. // the default on the new remote.
  335. //
  336. for (final RemoteRefUpdate u : updates) {
  337. final String n = u.getRemoteName();
  338. if (n.equals(Constants.R_HEADS + Constants.MASTER))
  339. return n;
  340. }
  341. // Pick any branch, under the assumption the user pushed only
  342. // one to the remote side.
  343. //
  344. for (final RemoteRefUpdate u : updates) {
  345. final String n = u.getRemoteName();
  346. if (n.startsWith(Constants.R_HEADS))
  347. return n;
  348. }
  349. return updates.get(0).getRemoteName();
  350. }
  351. }