Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

WalkPushConnection.java 12KB

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