Search in sources :

Example 6 with RepositoryConfiguration

use of com.palantir.stash.stashbot.persistence.RepositoryConfiguration in project stashbot by palantir.

the class RepoConfigurationServlet method doGet.

@Override
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    Repository rep = getRepository(req);
    if (rep == null) {
        res.sendError(404);
        return;
    }
    try {
        permissionValidationService.validateForRepository(rep, Permission.REPO_ADMIN);
    } catch (AuthorisationException notRepoAdmin) {
        log.warn("User {} tried to access the stashbot admin page for {}", req.getRemoteUser(), rep.getSlug());
        res.sendError(HttpServletResponse.SC_UNAUTHORIZED, "You do not have permission to access this page.");
        return;
    }
    RepositoryConfiguration rc;
    JenkinsServerConfiguration theJsc;
    try {
        rc = configurationPersistanceManager.getRepositoryConfigurationForRepository(rep);
        theJsc = configurationPersistanceManager.getJenkinsServerConfiguration(rc.getJenkinsServerName());
    } catch (SQLException e1) {
        throw new ServletException(e1);
    }
    res.setContentType("text/html;charset=UTF-8");
    try {
        List<Map<String, String>> jenkinsServersData = new ArrayList<Map<String, String>>();
        for (JenkinsServerConfiguration jsc : configurationPersistanceManager.getAllJenkinsServerConfigurations()) {
            HashMap<String, String> m = new HashMap<String, String>();
            m.put("text", jsc.getName());
            m.put("value", jsc.getName());
            if (rc.getJenkinsServerName().equals(jsc.getName())) {
                m.put("selected", "true");
            }
            jenkinsServersData.add(m);
        }
        pageBuilderService.assembler().resources().requireContext("plugin.page.stashbot");
        pageBuilderService.assembler().resources().requireWebResource("com.palantir.stash.stashbot:stashbot-resources");
        soyTemplateRenderer.render(res.getWriter(), "com.palantir.stash.stashbot:stashbotConfigurationResources", "plugin.page.stashbot.repositoryConfigurationPanel", ImmutableMap.<String, Object>builder().put("repository", rep).put("ciEnabled", rc.getCiEnabled()).put("publishBranchRegex", rc.getPublishBranchRegex()).put("publishBuildCommand", rc.getPublishBuildCommand()).put("verifyBranchRegex", rc.getVerifyBranchRegex()).put("verifyBuildCommand", rc.getVerifyBuildCommand()).put("prebuildCommand", rc.getPrebuildCommand()).put("jenkinsServerName", rc.getJenkinsServerName()).put("maxVerifyChain", rc.getMaxVerifyChain().toString()).put("rebuildOnUpdate", rc.getRebuildOnTargetUpdate()).put("isVerifyPinned", rc.getVerifyPinned()).put("verifyLabel", rc.getVerifyLabel()).put("isPublishPinned", rc.getPublishPinned()).put("publishLabel", rc.getPublishLabel()).put("isJunit", rc.getJunitEnabled()).put("junitPath", rc.getJunitPath()).put("artifactsEnabled", rc.getArtifactsEnabled()).put("artifactsPath", rc.getArtifactsPath()).put("jenkinsServersData", jenkinsServersData).put("isEmailNotificationsEnabled", rc.getEmailNotificationsEnabled()).put("isEmailForEveryUnstableBuild", rc.getEmailForEveryUnstableBuild()).put("isEmailPerModuleEmail", rc.getEmailPerModuleEmail()).put("emailRecipients", rc.getEmailRecipients()).put("isEmailSendToIndividuals", rc.getEmailSendToIndividuals()).put("isStrictVerifyMode", rc.getStrictVerifyMode()).put("isPreserveJenkinsJobConfig", rc.getPreserveJenkinsJobConfig()).put("isLocked", isLocked(theJsc)).put("verificationEnabled", configurationPersistanceManager.getJobTypeStatusMapping(rc, JobType.VERIFY_COMMIT)).put("verifyPREnabled", configurationPersistanceManager.getJobTypeStatusMapping(rc, JobType.VERIFY_PR)).put("publishEnabled", configurationPersistanceManager.getJobTypeStatusMapping(rc, JobType.PUBLISH)).build());
    } catch (SoyException e) {
        Throwable cause = e.getCause();
        if (cause instanceof IOException) {
            throw (IOException) cause;
        } else {
            throw new ServletException(e);
        }
    } catch (SQLException e) {
        throw new ServletException(e);
    }
}
Also used : SQLException(java.sql.SQLException) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) SoyException(com.atlassian.soy.renderer.SoyException) IOException(java.io.IOException) ServletException(javax.servlet.ServletException) Repository(com.atlassian.stash.repository.Repository) AuthorisationException(com.atlassian.stash.exception.AuthorisationException) RepositoryConfiguration(com.palantir.stash.stashbot.persistence.RepositoryConfiguration) JenkinsServerConfiguration(com.palantir.stash.stashbot.persistence.JenkinsServerConfiguration) HashMap(java.util.HashMap) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap)

Example 7 with RepositoryConfiguration

use of com.palantir.stash.stashbot.persistence.RepositoryConfiguration in project stashbot by palantir.

the class IsCiEnabledForRepoCondition method shouldDisplay.

@Override
public boolean shouldDisplay(Map<String, Object> context) {
    // request, principal, changeset, repository
    Repository repo = (Repository) context.get("repository");
    RepositoryConfiguration rc;
    if (repo == null) {
        return false;
    }
    try {
        rc = cpm.getRepositoryConfigurationForRepository(repo);
    } catch (SQLException e) {
        rc = null;
        log.error("Failed to get RepositoryConfiguration for repo: " + repo.toString(), e);
    }
    if (rc != null && rc.getCiEnabled()) {
        return true;
    }
    return false;
}
Also used : Repository(com.atlassian.stash.repository.Repository) SQLException(java.sql.SQLException) RepositoryConfiguration(com.palantir.stash.stashbot.persistence.RepositoryConfiguration)

Example 8 with RepositoryConfiguration

use of com.palantir.stash.stashbot.persistence.RepositoryConfiguration in project stashbot by palantir.

the class ConfigurationTest method getsStoredRepoData.

@Test
public void getsStoredRepoData() throws Exception {
    Repository repo = Mockito.mock(Repository.class);
    Mockito.when(repo.getId()).thenReturn(10);
    RepositoryConfiguration rc = cpm.getRepositoryConfigurationForRepository(repo);
    Assert.assertEquals("publishBranchRegex", rc.getPublishBranchRegex());
    Assert.assertEquals("publishBuildCommand", rc.getPublishBuildCommand());
    Assert.assertEquals("verifyBranchRegex", rc.getVerifyBranchRegex());
    Assert.assertEquals("verifyBuildCommand", rc.getVerifyBuildCommand());
    Assert.assertTrue(rc.getCiEnabled());
    Assert.assertFalse(rc.getPreserveJenkinsJobConfig());
}
Also used : Repository(com.atlassian.stash.repository.Repository) RepositoryConfiguration(com.palantir.stash.stashbot.persistence.RepositoryConfiguration) Test(org.junit.Test)

Example 9 with RepositoryConfiguration

use of com.palantir.stash.stashbot.persistence.RepositoryConfiguration in project stashbot by palantir.

the class TriggerJenkinsBuildHook method onReceive.

@Override
public void onReceive(@Nonnull Repository repo, @Nonnull Collection<RefChange> changes, @Nonnull HookResponse response) {
    final RepositoryConfiguration rc;
    try {
        rc = cpm.getRepositoryConfigurationForRepository(repo);
    } catch (SQLException e) {
        throw new RuntimeException("Failed to get repositoryConfiguration for repo " + repo.toString());
    }
    if (!rc.getCiEnabled()) {
        log.debug("CI disabled for repo " + repo.getName());
        return;
    }
    Set<String> publishBuilds = new HashSet<String>();
    // First trigger all publish builds (if they are enabled)
    if (cpm.getJobTypeStatusMapping(rc, JobType.PUBLISH)) {
        for (RefChange refChange : changes) {
            if (!refChange.getRefId().matches(rc.getPublishBranchRegex())) {
                continue;
            }
            // but it seems more reliable to use RefChangeType
            if (refChange.getType().equals(RefChangeType.DELETE)) {
                log.debug("Detected delete, not triggering a build for this change");
                continue;
            }
            // if matches publication regex, no verify build needed for that hash
            // Only perform publish builds of the "to ref", not commits between
            // I.E. if you have A-B-C and you push -D-E-F, a verify build of D and E might be triggered, but F would be
            // published and not verified, if the ref matches both build and verify.
            log.info("Stashbot Trigger: Triggering PUBLISH build for commit " + refChange.getToHash());
            // trigger a publication build
            jenkinsManager.triggerBuild(repo, JobType.PUBLISH, refChange.getToHash(), refChange.getRefId());
            publishBuilds.add(refChange.getToHash());
        }
    }
    // Nothing to do if VERIFY_COMMIT not enabled
    if (!cpm.getJobTypeStatusMapping(rc, JobType.VERIFY_COMMIT)) {
        return;
    }
    // Calculate the sum of all new commits introduced by this change
    // This would be:
    // (existing refs matching regex, deleted refs, changed refs old values)..(added refs, changed refs new values)
    // We will need a list of branches first
    GitScmCommandBuilder gcb = gcbf.builder(repo).command("branch");
    CommandOutputHandler<Object> gboh = cohf.getBranchContainsOutputHandler();
    gcb.build(gboh).call();
    @SuppressWarnings("unchecked") ImmutableList<String> branches = (ImmutableList<String>) gboh.getOutput();
    HashSet<String> plusBranches = new HashSet<String>();
    HashSet<String> minusBranches = new HashSet<String>();
    // add verify-matching branches to the minusBranches set
    minusBranches.addAll(ImmutableList.copyOf(Iterables.filter(branches, new Predicate<String>() {

        @Override
        public boolean apply(String input) {
            if (input.matches(rc.getVerifyBranchRegex())) {
                return true;
            }
            return false;
        }
    })));
    // now calculate the changed/added/deleted refs
    for (RefChange refChange : changes) {
        if (!refChange.getRefId().matches(rc.getVerifyBranchRegex())) {
            continue;
        }
        // Since we are a verify branch that changed, we need to not be in minusBranches anymore
        minusBranches.remove(refChange.getRefId());
        switch(refChange.getType()) {
            case DELETE:
                minusBranches.add(refChange.getFromHash());
                break;
            case ADD:
                plusBranches.add(refChange.getToHash());
                break;
            case UPDATE:
                minusBranches.add(refChange.getFromHash());
                plusBranches.add(refChange.getToHash());
                break;
            default:
                throw new IllegalStateException("Unknown change type " + refChange.getType().toString());
        }
    }
    // we can now calculate all the new commits introduced by this change in one revwalk.
    GitScmCommandBuilder gscb = gcbf.builder(repo);
    GitRevListBuilder grlb = gscb.revList();
    for (String mb : minusBranches) {
        grlb.revs("^" + mb);
    }
    for (String pb : plusBranches) {
        grlb.revs(pb);
    }
    Integer maxVerifyChain = getMaxVerifyChain(rc);
    if (maxVerifyChain != 0) {
        log.debug("Limiting to " + maxVerifyChain.toString() + " commits for verification");
        grlb.limit(maxVerifyChain);
    }
    CommandOutputHandler<Object> rloh = cohf.getRevlistOutputHandler();
    grlb.build(rloh).call();
    // returns in old-to-new order, already limited by max-verify-build limiter
    @SuppressWarnings("unchecked") ImmutableList<String> changesets = (ImmutableList<String>) rloh.getOutput();
    // For each new commit
    for (String cs : changesets) {
        if (publishBuilds.contains(cs)) {
            log.info("Stashbot Trigger: NOT triggering VERIFICATION build for commit " + cs + " because it already triggered a PUBLISH build");
            continue;
        }
        log.info("Stashbot Trigger: Triggering VERIFICATION build for commit " + cs);
        // trigger a verification build (no merge)
        jenkinsManager.triggerBuild(repo, JobType.VERIFY_COMMIT, cs, "");
    }
}
Also used : SQLException(java.sql.SQLException) ImmutableList(com.google.common.collect.ImmutableList) GitScmCommandBuilder(com.atlassian.stash.scm.git.GitScmCommandBuilder) GitRevListBuilder(com.atlassian.stash.scm.git.revlist.GitRevListBuilder) RefChange(com.atlassian.stash.repository.RefChange) RepositoryConfiguration(com.palantir.stash.stashbot.persistence.RepositoryConfiguration) HashSet(java.util.HashSet)

Example 10 with RepositoryConfiguration

use of com.palantir.stash.stashbot.persistence.RepositoryConfiguration in project stashbot by palantir.

the class ConfigurationPersistenceImpl method setRepositoryConfigurationForRepositoryFromRequest.

/* (non-Javadoc)
     * @see com.palantir.stash.stashbot.config.ConfigurationPersistenceService#setRepositoryConfigurationForRepositoryFromRequest(com.atlassian.stash.repository.Repository, javax.servlet.http.HttpServletRequest)
     */
@Override
public void setRepositoryConfigurationForRepositoryFromRequest(Repository repo, HttpServletRequest req) throws SQLException, NumberFormatException {
    Boolean ciEnabled = getBoolean(req, "ciEnabled");
    String publishBranchRegex = req.getParameter("publishBranchRegex");
    String publishBuildCommand = req.getParameter("publishBuildCommand");
    Boolean isPublishPinned = getBoolean(req, "isPublishPinned");
    String publishLabel = req.getParameter("publishLabel");
    String verifyBranchRegex = req.getParameter("verifyBranchRegex");
    String verifyBuildCommand = req.getParameter("verifyBuildCommand");
    Boolean isVerifyPinned = getBoolean(req, "isVerifyPinned");
    String verifyLabel = req.getParameter("verifyLabel");
    String prebuildCommand = req.getParameter("prebuildCommand");
    String jenkinsServerName = req.getParameter("jenkinsServerName");
    String maxVerifyChainStr = req.getParameter("maxVerifyChain");
    Integer maxVerifyChain = null;
    if (maxVerifyChainStr != null && !maxVerifyChainStr.isEmpty()) {
        maxVerifyChain = Integer.parseInt(maxVerifyChainStr);
    }
    Boolean strictVerifyMode = getBoolean(req, "isStrictVerifyMode");
    Boolean preserveJenkinsJobConfig = getBoolean(req, "isPreserveJenkinsJobConfig");
    Boolean junitEnabled = getBoolean(req, "isJunit");
    String junitPath = req.getParameter("junitPath");
    Boolean artifactsEnabled = getBoolean(req, "artifactsEnabled");
    String artifactsPath = req.getParameter("artifactsPath");
    Boolean rebuildOnUpdate = getBoolean(req, "rebuildOnUpdate");
    EmailSettings emailSettings = getEmailSettings(req);
    setRepositoryConfigurationForRepository(repo, ciEnabled, verifyBranchRegex, verifyBuildCommand, isVerifyPinned, verifyLabel, publishBranchRegex, publishBuildCommand, isPublishPinned, publishLabel, prebuildCommand, jenkinsServerName, rebuildOnUpdate, junitEnabled, junitPath, artifactsEnabled, artifactsPath, maxVerifyChain, emailSettings, strictVerifyMode, preserveJenkinsJobConfig);
    RepositoryConfiguration rc = getRepositoryConfigurationForRepository(repo);
    setJobTypeStatusMapping(rc, JobType.VERIFY_COMMIT, getBoolean(req, "verificationEnabled"));
    setJobTypeStatusMapping(rc, JobType.VERIFY_PR, getBoolean(req, "verifyPREnabled"));
    setJobTypeStatusMapping(rc, JobType.PUBLISH, getBoolean(req, "publishEnabled"));
}
Also used : RepositoryConfiguration(com.palantir.stash.stashbot.persistence.RepositoryConfiguration)

Aggregations

RepositoryConfiguration (com.palantir.stash.stashbot.persistence.RepositoryConfiguration)24 SQLException (java.sql.SQLException)16 Repository (com.atlassian.stash.repository.Repository)13 JenkinsServerConfiguration (com.palantir.stash.stashbot.persistence.JenkinsServerConfiguration)9 IOException (java.io.IOException)8 PullRequest (com.atlassian.stash.pull.PullRequest)6 JobTemplate (com.palantir.stash.stashbot.persistence.JobTemplate)5 JenkinsServer (com.offbytwo.jenkins.JenkinsServer)4 Job (com.offbytwo.jenkins.model.Job)4 URISyntaxException (java.net.URISyntaxException)4 ServletException (javax.servlet.ServletException)4 DBParam (net.java.ao.DBParam)3 EventListener (com.atlassian.event.api.EventListener)2 Changeset (com.atlassian.stash.content.Changeset)2 AuthorisationException (com.atlassian.stash.exception.AuthorisationException)2 PageRequest (com.atlassian.stash.util.PageRequest)2 PageRequestImpl (com.atlassian.stash.util.PageRequestImpl)2 ImmutableList (com.google.common.collect.ImmutableList)2 ImmutableMap (com.google.common.collect.ImmutableMap)2 PullRequestMetadata (com.palantir.stash.stashbot.persistence.PullRequestMetadata)2