Example usage for org.eclipse.jgit.api Git gc

List of usage examples for org.eclipse.jgit.api Git gc

Introduction

In this page you can find the example usage for org.eclipse.jgit.api Git gc.

Prototype

public GarbageCollectCommand gc() 

Source Link

Document

Return a command object to execute a gc command

Usage

From source file:com.gitblit.GCExecutor.java

License:Apache License

@Override
public void run() {
    if (!isReady()) {
        return;/*  w ww .j  ava2  s. co  m*/
    }

    running.set(true);
    Date now = new Date();

    for (String repositoryName : GitBlit.self().getRepositoryList()) {
        if (forceClose.get()) {
            break;
        }
        if (isCollectingGarbage(repositoryName)) {
            logger.warn(MessageFormat.format("Already collecting garbage from {0}?!?", repositoryName));
            continue;
        }
        boolean garbageCollected = false;
        RepositoryModel model = null;
        Repository repository = null;
        try {
            model = GitBlit.self().getRepositoryModel(repositoryName);
            repository = GitBlit.self().getRepository(repositoryName);
            if (repository == null) {
                logger.warn(MessageFormat.format("GCExecutor is missing repository {0}?!?", repositoryName));
                continue;
            }

            if (!isRepositoryIdle(repository)) {
                logger.debug(MessageFormat.format("GCExecutor is skipping {0} because it is not idle",
                        repositoryName));
                continue;
            }

            // By setting the GCStatus to COLLECTING we are
            // disabling *all* access to this repository from Gitblit.
            // Think of this as a clutch in a manual transmission vehicle.
            if (!setGCStatus(repositoryName, GCStatus.COLLECTING)) {
                logger.warn(MessageFormat.format("Can not acquire GC lock for {0}, skipping", repositoryName));
                continue;
            }

            logger.debug(MessageFormat.format("GCExecutor locked idle repository {0}", repositoryName));

            Git git = new Git(repository);
            GarbageCollectCommand gc = git.gc();
            Properties stats = gc.getStatistics();

            // determine if this is a scheduled GC
            Calendar cal = Calendar.getInstance();
            cal.setTime(model.lastGC);
            cal.set(Calendar.HOUR_OF_DAY, 0);
            cal.set(Calendar.MINUTE, 0);
            cal.set(Calendar.SECOND, 0);
            cal.set(Calendar.MILLISECOND, 0);
            cal.add(Calendar.DATE, model.gcPeriod);
            Date gcDate = cal.getTime();
            boolean shouldCollectGarbage = now.after(gcDate);

            // determine if filesize triggered GC
            long gcThreshold = FileUtils.convertSizeToLong(model.gcThreshold, 500 * 1024L);
            long sizeOfLooseObjects = (Long) stats.get("sizeOfLooseObjects");
            boolean hasEnoughGarbage = sizeOfLooseObjects >= gcThreshold;

            // if we satisfy one of the requirements, GC
            boolean hasGarbage = sizeOfLooseObjects > 0;
            if (hasGarbage && (hasEnoughGarbage || shouldCollectGarbage)) {
                long looseKB = sizeOfLooseObjects / 1024L;
                logger.info(MessageFormat.format("Collecting {1} KB of loose objects from {0}", repositoryName,
                        looseKB));

                // do the deed
                gc.call();

                garbageCollected = true;
            }
        } catch (Exception e) {
            logger.error("Error collecting garbage in " + repositoryName, e);
        } finally {
            // cleanup
            if (repository != null) {
                if (garbageCollected) {
                    // update the last GC date
                    model.lastGC = new Date();
                    GitBlit.self().updateConfiguration(repository, model);
                }

                repository.close();
            }

            // reset the GC lock 
            releaseLock(repositoryName);
            logger.debug(MessageFormat.format("GCExecutor released GC lock for {0}", repositoryName));
        }
    }

    running.set(false);
}

From source file:com.gitblit.service.GarbageCollectorService.java

License:Apache License

@Override
public void run() {
    if (!isReady()) {
        return;//from  ww  w . jav  a2 s.c  o  m
    }

    running.set(true);
    Date now = new Date();

    for (String repositoryName : repositoryManager.getRepositoryList()) {
        if (forceClose.get()) {
            break;
        }
        if (isCollectingGarbage(repositoryName)) {
            logger.warn(MessageFormat.format("Already collecting garbage from {0}?!?", repositoryName));
            continue;
        }
        boolean garbageCollected = false;
        RepositoryModel model = null;
        Repository repository = null;
        try {
            model = repositoryManager.getRepositoryModel(repositoryName);
            repository = repositoryManager.getRepository(repositoryName);
            if (repository == null) {
                logger.warn(MessageFormat.format("GCExecutor is missing repository {0}?!?", repositoryName));
                continue;
            }

            if (!repositoryManager.isIdle(repository)) {
                logger.debug(MessageFormat.format("GCExecutor is skipping {0} because it is not idle",
                        repositoryName));
                continue;
            }

            // By setting the GCStatus to COLLECTING we are
            // disabling *all* access to this repository from Gitblit.
            // Think of this as a clutch in a manual transmission vehicle.
            if (!setGCStatus(repositoryName, GCStatus.COLLECTING)) {
                logger.warn(MessageFormat.format("Can not acquire GC lock for {0}, skipping", repositoryName));
                continue;
            }

            logger.debug(MessageFormat.format("GCExecutor locked idle repository {0}", repositoryName));

            Git git = new Git(repository);
            GarbageCollectCommand gc = git.gc();
            Properties stats = gc.getStatistics();

            // determine if this is a scheduled GC
            Calendar cal = Calendar.getInstance();
            cal.setTime(model.lastGC);
            cal.set(Calendar.HOUR_OF_DAY, 0);
            cal.set(Calendar.MINUTE, 0);
            cal.set(Calendar.SECOND, 0);
            cal.set(Calendar.MILLISECOND, 0);
            cal.add(Calendar.DATE, model.gcPeriod);
            Date gcDate = cal.getTime();
            boolean shouldCollectGarbage = now.after(gcDate);

            // determine if filesize triggered GC
            long gcThreshold = FileUtils.convertSizeToLong(model.gcThreshold, 500 * 1024L);
            long sizeOfLooseObjects = (Long) stats.get("sizeOfLooseObjects");
            boolean hasEnoughGarbage = sizeOfLooseObjects >= gcThreshold;

            // if we satisfy one of the requirements, GC
            boolean hasGarbage = sizeOfLooseObjects > 0;
            if (hasGarbage && (hasEnoughGarbage || shouldCollectGarbage)) {
                long looseKB = sizeOfLooseObjects / 1024L;
                logger.info(MessageFormat.format("Collecting {1} KB of loose objects from {0}", repositoryName,
                        looseKB));

                // do the deed
                gc.call();

                garbageCollected = true;
            }
        } catch (Exception e) {
            logger.error("Error collecting garbage in " + repositoryName, e);
        } finally {
            // cleanup
            if (repository != null) {
                if (garbageCollected) {
                    // update the last GC date
                    model.lastGC = new Date();
                    repositoryManager.updateConfiguration(repository, model);
                }

                repository.close();
            }

            // reset the GC lock
            releaseLock(repositoryName);
            logger.debug(MessageFormat.format("GCExecutor released GC lock for {0}", repositoryName));
        }
    }

    running.set(false);
}

From source file:edu.wustl.lookingglass.community.CommunityRepository.java

License:Open Source License

private Git load() throws IOException, URISyntaxException, IllegalStateException, GitAPIException {
    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    Repository repository = builder.setGitDir(this.gitDir).readEnvironment().build();

    Git newGit;
    if (hasAtLeastOneReference(repository)) {
        // The repository is valid
        newGit = new Git(repository);
    } else {/*from ww  w  .  ja  v  a 2s  .  com*/
        // The current git dir isn't valid... so let's make a new one.
        Logger.warning("invalid git dir found " + this.gitDir + "; deleting.");
        FileUtils.forceDelete(this.gitDir);
        newGit = init();
    }

    // We need to make sure this repo stays in shape...
    // so let's do some maintenance every now and then...
    Properties gcStats = newGit.gc().getStatistics();
    int looseObjects = Integer.valueOf(gcStats.getProperty("numberOfLooseObjects", "0"));
    if ((AUTO_GC_LOOSE_OBJECTS != 0) && (looseObjects > AUTO_GC_LOOSE_OBJECTS)) {
        newGit.gc().call();
    }

    return newGit;
}

From source file:io.fabric8.git.internal.GitDataStore.java

License:Apache License

public <T> T gitOperation(PersonIdent personIdent, GitOperation<T> operation, boolean pullFirst,
        GitContext context) {//from w  w w  . j  a v a  2 s. c  o  m
    synchronized (gitOperationMonitor) {
        assertValid();

        // must set the TCCL to the classloader that loaded GitDataStore as we need the classloader
        // that could load this class, as jgit will load resources from classpath using the TCCL
        // and that requires the TCCL to the classloader that could load GitDataStore as the resources
        // jgit requires are in the same bundle as GitDataSource (eg embedded inside fabric-git)
        // see FABRIC-887
        ClassLoader oldCl = Thread.currentThread().getContextClassLoader();
        ClassLoader cl = GitDataStore.class.getClassLoader();
        Thread.currentThread().setContextClassLoader(cl);
        LOG.trace("Setting ThreadContextClassLoader to {} instead of {}", cl, oldCl);
        try {
            Git git = getGit();
            Repository repository = git.getRepository();
            // lets default the identity if none specified
            if (personIdent == null) {
                personIdent = new PersonIdent(repository);
            }

            if (GitHelpers.hasGitHead(git)) {
                // lets stash any local changes just in case..
                git.stashCreate().setPerson(personIdent).setWorkingDirectoryMessage("Stash before a write")
                        .call();
            }

            if (pullFirst) {
                doPull(git, getCredentialsProvider(), false);
            }

            T answer = operation.call(git, context);
            boolean requirePush = context.isRequirePush();
            if (context.isRequireCommit()) {
                requirePush = true;
                String message = context.getCommitMessage().toString();
                if (message.length() == 0) {
                    LOG.warn("No commit message from " + operation + ". Please add one! :)");
                }
                git.commit().setMessage(message).call();
                if (--commitsWithoutGC < 0) {
                    commitsWithoutGC = MAX_COMMITS_WITHOUT_GC;
                    LOG.debug("Performing \"git gc\" after {} commits", MAX_COMMITS_WITHOUT_GC);
                    git.gc().call();
                }
            }

            if (requirePush) {
                doPush(git, context, getCredentialsProvider());
            }

            if (context.isRequireCommit()) {
                clearCaches();
                fireChangeNotifications();
            }
            return answer;
        } catch (Exception e) {
            throw FabricException.launderThrowable(e);
        } finally {
            LOG.trace("Restoring ThreadContextClassLoader to {}", oldCl);
            Thread.currentThread().setContextClassLoader(oldCl);
        }
    }
}

From source file:io.fabric8.git.internal.GitDataStoreImpl.java

License:Apache License

private void doCommit(Git git, GitContext context) {
    try {// w  ww. j  av  a  2  s  .c o m
        String message = context.getCommitMessage();
        IllegalStateAssertion.assertTrue(message.length() > 0, "Empty commit message");

        // git add --all
        git.add().addFilepattern(".").call();

        // git commit -m message
        git.commit().setMessage(message).call();

        if (--commitsWithoutGC < 0) {
            commitsWithoutGC = MAX_COMMITS_WITHOUT_GC;
            LOGGER.debug("Performing 'git gc' after {} commits", MAX_COMMITS_WITHOUT_GC);
            git.gc().call();
        }
    } catch (GitAPIException ex) {
        throw FabricException.launderThrowable(ex);
    }
}

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

License:Apache License

public static void main(String... args) throws Exception {
    GitServerUtil.configureExternalProcessLogger(false);
    try {//w  w  w  .  ja  va  2s  .  co  m
        String gitDir = args[0];
        System.out.println("run gc in " + gitDir);
        Repository r = new RepositoryBuilder().setBare().setGitDir(new File(gitDir)).build();
        Git git = new Git(r);
        GarbageCollectCommand gc = git.gc();
        gc.setProgressMonitor(new TextProgressMonitor(new PrintWriter(System.out)));
        gc.call();
    } catch (Throwable t) {
        if (isImportant(t)) {
            t.printStackTrace(System.err);
        } else {
            System.err.println(t.getMessage());
        }
        System.exit(1);
    }
}