Example usage for org.eclipse.jgit.transport Transport close

List of usage examples for org.eclipse.jgit.transport Transport close

Introduction

In this page you can find the example usage for org.eclipse.jgit.transport Transport close.

Prototype

@Override
public abstract void close();

Source Link

Document

Close any resources used by this transport.

Usage

From source file:com.google.gerrit.server.git.PushOp.java

License:Apache License

private void runImpl() throws IOException {
    final Transport tn = Transport.open(db, uri);
    final PushResult res;
    try {// w w  w  .j  a  va2  s.c  o m
        res = pushVia(tn);
    } finally {
        try {
            tn.close();
        } catch (Throwable e2) {
            log.warn("Unexpected error while closing " + uri, e2);
        }
    }

    for (final RemoteRefUpdate u : res.getRemoteUpdates()) {
        switch (u.getStatus()) {
        case OK:
        case UP_TO_DATE:
        case NON_EXISTING:
            break;

        case NOT_ATTEMPTED:
        case AWAITING_REPORT:
        case REJECTED_NODELETE:
        case REJECTED_NONFASTFORWARD:
        case REJECTED_REMOTE_CHANGED:
            log.error("Failed replicate of " + u.getRemoteName() + " to " + uri + ": status "
                    + u.getStatus().name());
            break;

        case REJECTED_OTHER_REASON:
            if ("non-fast-forward".equals(u.getMessage())) {
                log.error("Failed replicate of " + u.getRemoteName() + " to " + uri
                        + ", remote rejected non-fast-forward push."
                        + "  Check receive.denyNonFastForwards variable in config file"
                        + " of destination repository.");
            } else {
                log.error("Failed replicate of " + u.getRemoteName() + " to " + uri + ", reason: "
                        + u.getMessage());
            }
            break;
        }
    }
}

From source file:com.madgag.agit.GitFetchService.java

License:Open Source License

public FetchResult fetch(RemoteConfig remote, Collection<RefSpec> toFetch) {
    Log.d(TAG, "About to run fetch : " + remote.getName() + " " + remote.getURIs());

    Transport transport = transportFactory.transportFor(remote);
    try {//from   w  ww .  ja v  a  2s .co m
        FetchResult fetchResult = transport
                .fetch(new MessagingProgressMonitor(progressListener, cancellationSignaller), toFetch);
        Log.d(TAG, "Fetch complete with : " + fetchResult);
        for (TrackingRefUpdate update : fetchResult.getTrackingRefUpdates()) {
            Log.d(TAG, "TrackingRefUpdate : " + update.getLocalName() + " old=" + update.getOldObjectId()
                    + " new=" + update.getNewObjectId());
        }
        repoUpdateBroadcaster.broadcastUpdate();
        return fetchResult;
    } catch (NotSupportedException e) {
        throw new RuntimeException(e);
    } catch (TransportException e) {
        Log.e(TAG, "TransportException ", e);
        String message = e.getMessage();
        Throwable cause = e.getCause();
        if (cause != null && cause instanceof JSchException) {
            message = "SSH: " + ((JSchException) cause).getMessage();
        }
        throw new RuntimeException(message, e);
    } finally {
        Log.d(TAG, "Closing transport " + transport);
        transport.close();
    }
}

From source file:jetbrains.buildServer.buildTriggers.vcs.git.FetchCommandImpl.java

License:Apache License

private void fetchInSameProcess(@NotNull Repository db, @NotNull URIish uri,
        @NotNull Collection<RefSpec> refSpecs, @NotNull FetchSettings settings)
        throws IOException, VcsException {
    final String debugInfo = getDebugInfo(db, uri, refSpecs);
    if (LOG.isDebugEnabled()) {
        LOG.debug("Fetch in server process: " + debugInfo);
    }/*  w  ww. j  a va 2s.  c o m*/
    final long fetchStart = System.currentTimeMillis();
    final Transport tn = myTransportFactory.createTransport(db, uri, settings.getAuthSettings());
    try {
        pruneRemovedBranches(db, tn, uri, settings.getAuthSettings());
        FetchResult result = GitServerUtil.fetch(db, uri, settings.getAuthSettings(), myTransportFactory, tn,
                settings.createProgressMonitor(), refSpecs);
        GitServerUtil.checkFetchSuccessful(db, result);
    } catch (OutOfMemoryError oom) {
        LOG.warn("There is not enough memory for git fetch, try to run fetch in a separate process.");
        clean(db);
    } finally {
        clean(db);
        tn.close();
        if (PERFORMANCE_LOG.isDebugEnabled()) {
            PERFORMANCE_LOG.debug("[fetch in server process] root=" + debugInfo + ", took "
                    + (System.currentTimeMillis() - fetchStart) + "ms");
        }
    }
}

From source file:jetbrains.buildServer.buildTriggers.vcs.git.Fetcher.java

License:Apache License

/**
 * Do fetch in directory <code>repositoryDir</code> with vcsRootProperties from <code>vcsRootProperties</code>
 *
 * @param repositoryDir     directory where run fetch
 * @param vcsRootProperties properties of vcsRoot
 * @throws IOException// w  ww. j a  v  a 2s . c o  m
 * @throws VcsException
 * @throws URISyntaxException
 */
private static void fetch(@NotNull File repositoryDir, @NotNull Map<String, String> vcsRootProperties,
        @NotNull ProgressMonitor progressMonitor) throws IOException, VcsException, URISyntaxException {
    final String fetchUrl = vcsRootProperties.get(Constants.FETCH_URL);
    final String refspecs = vcsRootProperties.get(Constants.REFSPEC);
    AuthSettings auth = new AuthSettings(vcsRootProperties);
    PluginConfigImpl config = new PluginConfigImpl();

    GitServerUtil.configureStreamFileThreshold(Integer.MAX_VALUE);

    TransportFactory transportFactory = new TransportFactoryImpl(config, new EmptyVcsRootSshKeyManager());
    Transport tn = null;
    try {
        Repository repository = new RepositoryBuilder().setBare().setGitDir(repositoryDir).build();
        workaroundRacyGit();
        tn = transportFactory.createTransport(repository, new URIish(fetchUrl), auth);
        try {
            pruneRemovedBranches(config, repository, transportFactory, tn, new URIish(fetchUrl), auth);
        } catch (Exception e) {
            System.err.println("Error while pruning removed branches: " + e.getMessage());
            e.printStackTrace(System.err);
        }
        FetchResult result = GitServerUtil.fetch(repository, new URIish(fetchUrl), auth, transportFactory, tn,
                progressMonitor, parseRefspecs(refspecs));
        GitServerUtil.checkFetchSuccessful(repository, result);
        logFetchResults(result);
    } finally {
        if (tn != null)
            tn.close();
    }
}

From source file:jetbrains.buildServer.buildTriggers.vcs.git.GitLabelingSupport.java

License:Apache License

@NotNull
private String push(@NotNull String label, @NotNull String version, @NotNull GitVcsRoot gitRoot,
        @NotNull Repository r, @NotNull Ref tagRef, @NotNull RevisionsInfo revisionsInfo)
        throws VcsException, IOException {
    long pushStart = System.currentTimeMillis();
    final Transport tn = myTransportFactory.createTransport(r, gitRoot.getRepositoryPushURL(),
            gitRoot.getAuthSettings(), myConfig.getPushTimeoutSeconds());
    PushConnection c = null;//from w  w  w  . j ava 2  s  . c  om
    try {
        c = tn.openPush();
        RemoteRefUpdate ru = new RemoteRefUpdate(r, tagRef.getName(), tagRef.getObjectId(), tagRef.getName(),
                false, null, null);
        PreparePackFunction preparePack = null;
        if (c instanceof BasePackPushConnection) {
            final RevTag tagObject = getTagObject(r, tagRef);
            if (tagObject != null) {
                preparePack = new PreparePackFunction(tagObject, revisionsInfo);
                ((BasePackPushConnection) c).setPreparePack(preparePack);
            } else {
                LOG.debug("Cannot locate the " + tagRef.getName() + " tag object, don't use pack heuristic");
            }
        }
        c.push(NullProgressMonitor.INSTANCE, Collections.singletonMap(tagRef.getName(), ru));
        LOG.info("Tag  " + label + "=" + version + " was pushed with status " + ru.getStatus() + " for "
                + gitRoot.debugInfo() + " in " + (System.currentTimeMillis() - pushStart) + "ms"
                + (preparePack != null ? " (prepare pack " + preparePack.getPreparePackDurationMillis() + "ms)"
                        : ""));
        switch (ru.getStatus()) {
        case UP_TO_DATE:
        case OK:
            break;
        default:
            String msg = ru.getMessage();
            throw new VcsException("The remote '" + label + "' tag was not created" + ", status: "
                    + ru.getStatus() + (!isEmpty(msg) ? ", message: " + msg : ""));
        }
        return label;
    } finally {
        if (c != null)
            c.close();
        tn.close();
    }
}

From source file:jetbrains.buildServer.buildTriggers.vcs.git.GitMergeSupport.java

License:Apache License

@NotNull
private MergeResult doMerge(@NotNull OperationContext context, @NotNull GitVcsRoot gitRoot,
        @NotNull Repository db, @NotNull String srcRevision, @NotNull String dstBranch, @NotNull String message,
        @NotNull MergeOptions options) throws IOException, VcsException {
    RefSpec spec = new RefSpec().setSource(GitUtils.expandRef(dstBranch))
            .setDestination(GitUtils.expandRef(dstBranch)).setForceUpdate(true);
    myCommitLoader.fetch(db, gitRoot.getRepositoryFetchURL(), asList(spec),
            new FetchSettings(gitRoot.getAuthSettings()));
    RevCommit srcCommit = myCommitLoader.findCommit(db, srcRevision);
    if (srcCommit == null)
        srcCommit = myCommitLoader.loadCommit(context, gitRoot, srcRevision);

    Ref dstRef = db.getRef(dstBranch);
    RevCommit dstBranchLastCommit = myCommitLoader.loadCommit(context, gitRoot, dstRef.getObjectId().name());
    ObjectId commitId;/* w  w w . j  a v  a2 s .  c  o  m*/
    try {
        commitId = mergeCommits(gitRoot, db, srcCommit, dstBranchLastCommit, message, options);
    } catch (MergeFailedException e) {
        LOG.debug("Merge error, root " + gitRoot + ", revision " + srcRevision + ", destination " + dstBranch,
                e);
        return MergeResult.createMergeError(e.getConflicts());
    }

    synchronized (myRepositoryManager.getWriteLock(gitRoot.getRepositoryDir())) {
        final Transport tn = myTransportFactory.createTransport(db, gitRoot.getRepositoryPushURL(),
                gitRoot.getAuthSettings(), myPluginConfig.getPushTimeoutSeconds());
        try {
            final PushConnection c = tn.openPush();
            try {
                RemoteRefUpdate ru = new RemoteRefUpdate(db, null, commitId, GitUtils.expandRef(dstBranch),
                        false, null, dstBranchLastCommit);
                c.push(NullProgressMonitor.INSTANCE,
                        Collections.singletonMap(GitUtils.expandRef(dstBranch), ru));
                switch (ru.getStatus()) {
                case UP_TO_DATE:
                case OK:
                    return MergeResult.createMergeSuccessResult();
                default:
                    return MergeResult.createMergeError("Push failed, " + ru.getMessage());
                }
            } finally {
                c.close();
            }
        } catch (IOException e) {
            LOG.debug("Error while pushing a merge commit, root " + gitRoot + ", revision " + srcRevision
                    + ", destination " + dstBranch, e);
            throw e;
        } finally {
            tn.close();
        }
    }
}

From source file:jetbrains.buildServer.buildTriggers.vcs.git.GitServerUtil.java

License:Apache License

static void pruneRemovedBranches(@NotNull ServerPluginConfig config, @NotNull TransportFactory transportFactory,
        @NotNull Transport tn, @NotNull Repository db, @NotNull URIish uri, @NotNull AuthSettings authSettings)
        throws IOException, VcsException {
    if (config.createNewConnectionForPrune()) {
        Transport transport = null;
        try {/*from   w  w  w.j  av a 2  s  . c  o  m*/
            transport = transportFactory.createTransport(db, uri, authSettings,
                    config.getRepositoryStateTimeoutSeconds());
            pruneRemovedBranches(db, transport);
        } finally {
            if (transport != null)
                transport.close();
        }
    } else {
        pruneRemovedBranches(db, tn);
    }
}

From source file:jetbrains.buildServer.buildTriggers.vcs.git.GitServerUtil.java

License:Apache License

@NotNull
public static FetchResult fetch(@NotNull Repository r, @NotNull URIish url, @NotNull AuthSettings authSettings,
        @NotNull TransportFactory transportFactory, @NotNull Transport transport,
        @NotNull ProgressMonitor progress, @NotNull Collection<RefSpec> refSpecs)
        throws NotSupportedException, TransportException, VcsException {
    try {/*from w  w  w . j  a v a2s  .c  o m*/
        return transport.fetch(progress, refSpecs);
    } catch (TransportException e) {
        Throwable cause = e.getCause();
        if (cause instanceof JSchException && "channel is not opened.".equals(cause.getMessage())) {
            Transport tn = null;
            try {
                tn = transportFactory.createTransport(r, url, authSettings);
                return tn.fetch(progress, refSpecs);
            } finally {
                if (tn != null)
                    tn.close();
            }
        } else {
            throw e;
        }
    }
}

From source file:jetbrains.buildServer.buildTriggers.vcs.git.GitVcsSupport.java

License:Apache License

@NotNull
private Map<String, Ref> getRemoteRefs(@NotNull Repository db, @NotNull GitVcsRoot gitRoot) throws Exception {
    long retryInterval = myConfig.getConnectionRetryIntervalMillis();
    int attemptsLeft = myConfig.getConnectionRetryAttempts();
    int timeout = myConfig.getRepositoryStateTimeoutSeconds();
    while (true) {
        final long start = System.currentTimeMillis();
        Transport transport = null;
        FetchConnection connection = null;
        try {/*from  w  w  w . j a  va 2  s  . c  o m*/
            transport = myTransportFactory.createTransport(db, gitRoot.getRepositoryFetchURL(),
                    gitRoot.getAuthSettings(), timeout);
            connection = transport.openFetch();
            return connection.getRefsMap();
        } catch (NotSupportedException nse) {
            throw friendlyNotSupportedException(gitRoot, nse);
        } catch (TransportException te) {
            attemptsLeft--;
            if (isRecoverable(te) && attemptsLeft > 0) {
                LOG.warn("List remote refs failed: " + te.getMessage() + ", " + attemptsLeft
                        + " attempt(s) left");
            } else {
                throw friendlyTransportException(te, gitRoot);
            }
        } catch (WrongPassphraseException e) {
            throw new VcsException(e.getMessage(), e);
        } finally {
            if (connection != null)
                connection.close();
            if (transport != null)
                transport.close();
            final long finish = System.currentTimeMillis();
            PERFORMANCE_LOG.debug("[getRemoteRefs] repository: " + LogUtil.describe(gitRoot) + ", took "
                    + (finish - start) + "ms");
        }
        Thread.sleep(retryInterval);
        retryInterval *= 2;
    }
}

From source file:jetbrains.buildServer.buildTriggers.vcs.git.TestConnectionCommand.java

License:Apache License

private void checkPushConnection(GitVcsRoot root, Repository r)
        throws NotSupportedException, VcsException, TransportException {
    if (!root.getRepositoryFetchURLNoFixedErrors().equals(root.getRepositoryPushURLNoFixedErrors())) {
        validate(root.getRepositoryPushURLNoFixedErrors());
        final Transport push = myTransportFactory.createTransport(r, root.getRepositoryPushURLNoFixedErrors(),
                root.getAuthSettings());
        PushConnection c = null;/*  w  w w  .j av a 2s  .  c  o  m*/
        try {
            c = push.openPush();
            c.getRefs();
        } finally {
            if (c != null) {
                c.close();
            }
            push.close();
        }
    }
}