WalkPushConnection.java

  1. /*
  2.  * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org> and others
  3.  *
  4.  * This program and the accompanying materials are made available under the
  5.  * terms of the Eclipse Distribution License v. 1.0 which is available at
  6.  * https://www.eclipse.org/org/documents/edl-v10.php.
  7.  *
  8.  * SPDX-License-Identifier: BSD-3-Clause
  9.  */

  10. package org.eclipse.jgit.transport;

  11. import static org.eclipse.jgit.transport.WalkRemoteObjectDatabase.ROOT_DIR;

  12. import java.io.BufferedOutputStream;
  13. import java.io.File;
  14. import java.io.IOException;
  15. import java.io.OutputStream;
  16. import java.util.ArrayList;
  17. import java.util.Collection;
  18. import java.util.HashSet;
  19. import java.util.LinkedHashMap;
  20. import java.util.List;
  21. import java.util.Map;
  22. import java.util.Set;
  23. import java.util.TreeMap;

  24. import org.eclipse.jgit.errors.TransportException;
  25. import org.eclipse.jgit.internal.JGitText;
  26. import org.eclipse.jgit.internal.storage.file.PackFile;
  27. import org.eclipse.jgit.internal.storage.pack.PackExt;
  28. import org.eclipse.jgit.internal.storage.pack.PackWriter;
  29. import org.eclipse.jgit.lib.AnyObjectId;
  30. import org.eclipse.jgit.lib.Constants;
  31. import org.eclipse.jgit.lib.ObjectId;
  32. import org.eclipse.jgit.lib.ObjectIdRef;
  33. import org.eclipse.jgit.lib.ProgressMonitor;
  34. import org.eclipse.jgit.lib.Ref;
  35. import org.eclipse.jgit.lib.Ref.Storage;
  36. import org.eclipse.jgit.lib.RefWriter;
  37. import org.eclipse.jgit.lib.Repository;
  38. import org.eclipse.jgit.transport.RemoteRefUpdate.Status;

  39. /**
  40.  * Generic push support for dumb transport protocols.
  41.  * <p>
  42.  * Since there are no Git-specific smarts on the remote side of the connection
  43.  * the client side must handle everything on its own. The generic push support
  44.  * requires being able to delete, create and overwrite files on the remote side,
  45.  * as well as create any missing directories (if necessary). Typically this can
  46.  * be handled through an FTP style protocol.
  47.  * <p>
  48.  * Objects not on the remote side are uploaded as pack files, using one pack
  49.  * file per invocation. This simplifies the implementation as only two data
  50.  * files need to be written to the remote repository.
  51.  * <p>
  52.  * Push support supplied by this class is not multiuser safe. Concurrent pushes
  53.  * to the same repository may yield an inconsistent reference database which may
  54.  * confuse fetch clients.
  55.  * <p>
  56.  * A single push is concurrently safe with multiple fetch requests, due to the
  57.  * careful order of operations used to update the repository. Clients fetching
  58.  * may receive transient failures due to short reads on certain files if the
  59.  * protocol does not support atomic file replacement.
  60.  *
  61.  * @see WalkRemoteObjectDatabase
  62.  */
  63. class WalkPushConnection extends BaseConnection implements PushConnection {
  64.     /** The repository this transport pushes out of. */
  65.     private final Repository local;

  66.     /** Location of the remote repository we are writing to. */
  67.     private final URIish uri;

  68.     /** Database connection to the remote repository. */
  69.     final WalkRemoteObjectDatabase dest;

  70.     /** The configured transport we were constructed by. */
  71.     private final Transport transport;

  72.     /**
  73.      * Packs already known to reside in the remote repository.
  74.      * <p>
  75.      * This is a LinkedHashMap to maintain the original order.
  76.      */
  77.     private LinkedHashMap<String, String> packNames;

  78.     /** Complete listing of refs the remote will have after our push. */
  79.     private Map<String, Ref> newRefs;

  80.     /**
  81.      * Updates which require altering the packed-refs file to complete.
  82.      * <p>
  83.      * If this collection is non-empty then any refs listed in {@link #newRefs}
  84.      * with a storage class of {@link Storage#PACKED} will be written.
  85.      */
  86.     private Collection<RemoteRefUpdate> packedRefUpdates;

  87.     WalkPushConnection(final WalkTransport walkTransport,
  88.             final WalkRemoteObjectDatabase w) {
  89.         transport = (Transport) walkTransport;
  90.         local = transport.local;
  91.         uri = transport.getURI();
  92.         dest = w;
  93.     }

  94.     /** {@inheritDoc} */
  95.     @Override
  96.     public void push(final ProgressMonitor monitor,
  97.             final Map<String, RemoteRefUpdate> refUpdates)
  98.             throws TransportException {
  99.         push(monitor, refUpdates, null);
  100.     }

  101.     /** {@inheritDoc} */
  102.     @Override
  103.     public void push(final ProgressMonitor monitor,
  104.             final Map<String, RemoteRefUpdate> refUpdates, OutputStream out)
  105.             throws TransportException {
  106.         markStartedOperation();
  107.         packNames = null;
  108.         newRefs = new TreeMap<>(getRefsMap());
  109.         packedRefUpdates = new ArrayList<>(refUpdates.size());

  110.         // Filter the commands and issue all deletes first. This way we
  111.         // can correctly handle a directory being cleared out and a new
  112.         // ref using the directory name being created.
  113.         //
  114.         final List<RemoteRefUpdate> updates = new ArrayList<>();
  115.         for (RemoteRefUpdate u : refUpdates.values()) {
  116.             final String n = u.getRemoteName();
  117.             if (!n.startsWith("refs/") || !Repository.isValidRefName(n)) { //$NON-NLS-1$
  118.                 u.setStatus(Status.REJECTED_OTHER_REASON);
  119.                 u.setMessage(JGitText.get().funnyRefname);
  120.                 continue;
  121.             }

  122.             if (AnyObjectId.isEqual(ObjectId.zeroId(), u.getNewObjectId()))
  123.                 deleteCommand(u);
  124.             else
  125.                 updates.add(u);
  126.         }

  127.         // If we have any updates we need to upload the objects first, to
  128.         // prevent creating refs pointing at non-existent data. Then we
  129.         // can update the refs, and the info-refs file for dumb transports.
  130.         //
  131.         if (!updates.isEmpty())
  132.             sendpack(updates, monitor);
  133.         for (RemoteRefUpdate u : updates)
  134.             updateCommand(u);

  135.         // Is this a new repository? If so we should create additional
  136.         // metadata files so it is properly initialized during the push.
  137.         //
  138.         if (!updates.isEmpty() && isNewRepository())
  139.             createNewRepository(updates);

  140.         RefWriter refWriter = new RefWriter(newRefs.values()) {
  141.             @Override
  142.             protected void writeFile(String file, byte[] content)
  143.                     throws IOException {
  144.                 dest.writeFile(ROOT_DIR + file, content);
  145.             }
  146.         };
  147.         if (!packedRefUpdates.isEmpty()) {
  148.             try {
  149.                 refWriter.writePackedRefs();
  150.                 for (RemoteRefUpdate u : packedRefUpdates)
  151.                     u.setStatus(Status.OK);
  152.             } catch (IOException err) {
  153.                 for (RemoteRefUpdate u : packedRefUpdates) {
  154.                     u.setStatus(Status.REJECTED_OTHER_REASON);
  155.                     u.setMessage(err.getMessage());
  156.                 }
  157.                 throw new TransportException(uri, JGitText.get().failedUpdatingRefs, err);
  158.             }
  159.         }

  160.         try {
  161.             refWriter.writeInfoRefs();
  162.         } catch (IOException err) {
  163.             throw new TransportException(uri, JGitText.get().failedUpdatingRefs, err);
  164.         }
  165.     }

  166.     /** {@inheritDoc} */
  167.     @Override
  168.     public void close() {
  169.         dest.close();
  170.     }

  171.     private void sendpack(final List<RemoteRefUpdate> updates,
  172.             final ProgressMonitor monitor) throws TransportException {
  173.         PackFile pack = null;
  174.         PackFile idx = null;
  175.         try (PackWriter writer = new PackWriter(transport.getPackConfig(),
  176.                 local.newObjectReader())) {

  177.             final Set<ObjectId> need = new HashSet<>();
  178.             final Set<ObjectId> have = new HashSet<>();
  179.             for (RemoteRefUpdate r : updates)
  180.                 need.add(r.getNewObjectId());
  181.             for (Ref r : getRefs()) {
  182.                 have.add(r.getObjectId());
  183.                 if (r.getPeeledObjectId() != null)
  184.                     have.add(r.getPeeledObjectId());
  185.             }
  186.             writer.preparePack(monitor, need, have);

  187.             // We don't have to continue further if the pack will
  188.             // be an empty pack, as the remote has all objects it
  189.             // needs to complete this change.
  190.             //
  191.             if (writer.getObjectCount() == 0)
  192.                 return;

  193.             packNames = new LinkedHashMap<>();
  194.             for (String n : dest.getPackNames())
  195.                 packNames.put(n, n);

  196.             File packDir = new File("pack"); //$NON-NLS-1$
  197.             pack = new PackFile(packDir, writer.computeName(),
  198.                     PackExt.PACK);
  199.             idx = pack.create(PackExt.INDEX);

  200.             if (packNames.remove(pack.getName()) != null) {
  201.                 // The remote already contains this pack. We should
  202.                 // remove the index before overwriting to prevent bad
  203.                 // offsets from appearing to clients.
  204.                 //
  205.                 dest.writeInfoPacks(packNames.keySet());
  206.                 dest.deleteFile(idx.getPath());
  207.             }

  208.             // Write the pack file, then the index, as readers look the
  209.             // other direction (index, then pack file).
  210.             //
  211.             String wt = "Put " + pack.getName().substring(0, 12); //$NON-NLS-1$
  212.             try (OutputStream os = new BufferedOutputStream(
  213.                     dest.writeFile(pack.getPath(), monitor,
  214.                             wt + "." + pack.getPackExt().getExtension()))) { //$NON-NLS-1$
  215.                 writer.writePack(monitor, monitor, os);
  216.             }

  217.             try (OutputStream os = new BufferedOutputStream(
  218.                     dest.writeFile(idx.getPath(), monitor,
  219.                             wt + "." + idx.getPackExt().getExtension()))) { //$NON-NLS-1$
  220.                 writer.writeIndex(os);
  221.             }

  222.             // Record the pack at the start of the pack info list. This
  223.             // way clients are likely to consult the newest pack first,
  224.             // and discover the most recent objects there.
  225.             //
  226.             final ArrayList<String> infoPacks = new ArrayList<>();
  227.             infoPacks.add(pack.getName());
  228.             infoPacks.addAll(packNames.keySet());
  229.             dest.writeInfoPacks(infoPacks);

  230.         } catch (IOException err) {
  231.             safeDelete(idx);
  232.             safeDelete(pack);

  233.             throw new TransportException(uri, JGitText.get().cannotStoreObjects, err);
  234.         }
  235.     }

  236.     private void safeDelete(File path) {
  237.         if (path != null) {
  238.             try {
  239.                 dest.deleteFile(path.getPath());
  240.             } catch (IOException cleanupFailure) {
  241.                 // Ignore the deletion failure. We probably are
  242.                 // already failing and were just trying to pick
  243.                 // up after ourselves.
  244.             }
  245.         }
  246.     }

  247.     private void deleteCommand(RemoteRefUpdate u) {
  248.         final Ref r = newRefs.remove(u.getRemoteName());
  249.         if (r == null) {
  250.             // Already gone.
  251.             //
  252.             u.setStatus(Status.OK);
  253.             return;
  254.         }

  255.         if (r.getStorage().isPacked())
  256.             packedRefUpdates.add(u);

  257.         if (r.getStorage().isLoose()) {
  258.             try {
  259.                 dest.deleteRef(u.getRemoteName());
  260.                 u.setStatus(Status.OK);
  261.             } catch (IOException e) {
  262.                 u.setStatus(Status.REJECTED_OTHER_REASON);
  263.                 u.setMessage(e.getMessage());
  264.             }
  265.         }

  266.         try {
  267.             dest.deleteRefLog(u.getRemoteName());
  268.         } catch (IOException e) {
  269.             u.setStatus(Status.REJECTED_OTHER_REASON);
  270.             u.setMessage(e.getMessage());
  271.         }
  272.     }

  273.     private void updateCommand(RemoteRefUpdate u) {
  274.         try {
  275.             dest.writeRef(u.getRemoteName(), u.getNewObjectId());
  276.             newRefs.put(u.getRemoteName(), new ObjectIdRef.Unpeeled(
  277.                     Storage.LOOSE, u.getRemoteName(), u.getNewObjectId()));
  278.             u.setStatus(Status.OK);
  279.         } catch (IOException e) {
  280.             u.setStatus(Status.REJECTED_OTHER_REASON);
  281.             u.setMessage(e.getMessage());
  282.         }
  283.     }

  284.     private boolean isNewRepository() {
  285.         return getRefsMap().isEmpty() && packNames != null
  286.                 && packNames.isEmpty();
  287.     }

  288.     private void createNewRepository(List<RemoteRefUpdate> updates)
  289.             throws TransportException {
  290.         try {
  291.             final String ref = "ref: " + pickHEAD(updates) + "\n"; //$NON-NLS-1$ //$NON-NLS-2$
  292.             final byte[] bytes = Constants.encode(ref);
  293.             dest.writeFile(ROOT_DIR + Constants.HEAD, bytes);
  294.         } catch (IOException e) {
  295.             throw new TransportException(uri, JGitText.get().cannotCreateHEAD, e);
  296.         }

  297.         try {
  298.             final String config = "[core]\n" //$NON-NLS-1$
  299.                     + "\trepositoryformatversion = 0\n"; //$NON-NLS-1$
  300.             final byte[] bytes = Constants.encode(config);
  301.             dest.writeFile(ROOT_DIR + Constants.CONFIG, bytes);
  302.         } catch (IOException e) {
  303.             throw new TransportException(uri, JGitText.get().cannotCreateConfig, e);
  304.         }
  305.     }

  306.     private static String pickHEAD(List<RemoteRefUpdate> updates) {
  307.         // Try to use master if the user is pushing that, it is the
  308.         // default branch and is likely what they want to remain as
  309.         // the default on the new remote.
  310.         //
  311.         for (RemoteRefUpdate u : updates) {
  312.             final String n = u.getRemoteName();
  313.             if (n.equals(Constants.R_HEADS + Constants.MASTER))
  314.                 return n;
  315.         }

  316.         // Pick any branch, under the assumption the user pushed only
  317.         // one to the remote side.
  318.         //
  319.         for (RemoteRefUpdate u : updates) {
  320.             final String n = u.getRemoteName();
  321.             if (n.startsWith(Constants.R_HEADS))
  322.                 return n;
  323.         }
  324.         return updates.get(0).getRemoteName();
  325.     }
  326. }