Search in sources :

Example 1 with Repository

use of com.atlassian.stash.repository.Repository in project stashbot by palantir.

the class RetriggerLinkWebPanel method writeHtml.

@Override
public void writeHtml(Writer writer, Map<String, Object> context) throws IOException {
    try {
        Repository repo = (Repository) context.get("repository");
        RepositoryConfiguration rc = cpm.getRepositoryConfigurationForRepository(repo);
        if (!rc.getCiEnabled()) {
            // No link
            return;
        }
        Changeset changeset = (Changeset) context.get("changeset");
        String url = ub.getJenkinsTriggerUrl(repo, JobType.VERIFY_COMMIT, changeset.getId(), null);
        String pubUrl = ub.getJenkinsTriggerUrl(repo, JobType.PUBLISH, changeset.getId(), null);
        // TODO: add ?reason=<buildRef> somehow to end of URLs?
        writer.append("Trigger: ( <a href=\"" + url + "\">Verify</a> | ");
        writer.append("<a href=\"" + pubUrl + "\">Publish</a> )");
    } catch (SQLException e) {
        throw new IOException(e);
    }
}
Also used : Repository(com.atlassian.stash.repository.Repository) SQLException(java.sql.SQLException) IOException(java.io.IOException) RepositoryConfiguration(com.palantir.stash.stashbot.persistence.RepositoryConfiguration) Changeset(com.atlassian.stash.content.Changeset)

Example 2 with Repository

use of com.atlassian.stash.repository.Repository in project stashbot by palantir.

the class RepoConfigurationStatusServlet method doGet.

@Override
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    Repository rep = getRepository(req);
    if (rep == null) {
        res.sendError(404);
        return;
    }
    RepositoryConfiguration rc;
    try {
        rc = configurationPersistanceManager.getRepositoryConfigurationForRepository(rep);
    } catch (SQLException e1) {
        throw new ServletException(e1);
    }
    res.setContentType("text/html;charset=UTF-8");
    res.getWriter().print(rc.getCiEnabled());
    res.getWriter().flush();
    res.getWriter().close();
    return;
}
Also used : ServletException(javax.servlet.ServletException) Repository(com.atlassian.stash.repository.Repository) SQLException(java.sql.SQLException) RepositoryConfiguration(com.palantir.stash.stashbot.persistence.RepositoryConfiguration)

Example 3 with Repository

use of com.atlassian.stash.repository.Repository in project stashbot by palantir.

the class BuildStatusReportingServlet method doGet.

@Override
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    try {
        // Look at JenkinsManager class if you change this:
        // final two arguments could be empty...
        final String URL_FORMAT = "BASE_URL/REPO_ID_OR_SLUG/PULLREQUEST_ID]";
        final String pathInfo = req.getPathInfo();
        final String[] parts = pathInfo.split("/");
        // need at *least* 3 parts to be correct
        if (parts.length < 3) {
            throw new IllegalArgumentException("The format of the URL is " + URL_FORMAT);
        }
        // Last part is always the PR
        String pullRequestPart = parts[parts.length - 1];
        // First part is always empty because string starts with '/', last is pr, the rest is the slug
        String slugOrId = StringUtils.join(Arrays.copyOfRange(parts, 1, parts.length - 1), "/");
        Repository repo;
        try {
            int repoId = Integer.valueOf(slugOrId);
            repo = rs.getById(repoId);
            if (repo == null) {
                throw new IllegalArgumentException("Unable to find repository for repo id " + repoId);
            }
        } catch (NumberFormatException e) {
            // we have a slug, try to get a repo ID from that
            // slug should look like this: projects/PROJECT_KEY/repos/REPO_SLUG/pull-requests
            String[] newParts = slugOrId.split("/");
            if (newParts.length != 5) {
                throw new IllegalArgumentException("The format of the REPO_ID_OR_SLUG is an ID, or projects/PROJECT_KEY/repos/REPO_SLUG/pull-requests");
            }
            Project p = ps.getByKey(newParts[1]);
            if (p == null) {
                throw new IllegalArgumentException("Unable to find project for project key" + newParts[1]);
            }
            repo = rs.getBySlug(p.getKey(), newParts[3]);
            if (repo == null) {
                throw new IllegalArgumentException("Unable to find repository for project key" + newParts[1] + " and repo slug " + newParts[3]);
            }
        }
        final long pullRequestId;
        final PullRequest pullRequest;
        try {
            pullRequestId = Long.parseLong(pullRequestPart);
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("Unable to parse pull request id " + parts[7], e);
        }
        pullRequest = prs.getById(repo.getId(), pullRequestId);
        if (pullRequest == null) {
            throw new IllegalArgumentException("Unable to find pull request for repo id " + repo.getId().toString() + " pr id " + pullRequestId);
        }
        PullRequestMergeability canMerge = prs.canMerge(repo.getId(), pullRequestId);
        JSONObject output = new JSONObject();
        output.put("repoId", repo.getId());
        output.put("prId", pullRequestId);
        output.put("url", nb.repo(repo).pullRequest(pullRequest.getId()).buildAbsolute());
        output.put("canMerge", canMerge.canMerge());
        if (!canMerge.canMerge()) {
            JSONArray vetoes = new JSONArray();
            for (PullRequestMergeVeto prmv : canMerge.getVetos()) {
                JSONObject prmvjs = new JSONObject();
                prmvjs.put("summary", prmv.getSummaryMessage());
                prmvjs.put("details", prmv.getDetailedMessage());
                vetoes.put(prmvjs);
            }
            // You might expect a conflict would be included in the list of merge blockers.  You'd be mistaken.
            if (canMerge.isConflicted()) {
                JSONObject prmvjs = new JSONObject();
                prmvjs.put("summary", "This pull request is unmergeable due to conflicts.");
                prmvjs.put("details", "You will need to resolve conflicts to be able to merge.");
                vetoes.put(prmvjs);
            }
            output.put("vetoes", vetoes);
        }
        log.debug("Serving build status: " + output.toString());
        printOutput(output, req, res);
    } catch (Exception e) {
        res.reset();
        res.setStatus(500);
        res.setContentType("application/json");
        Writer w = res.getWriter();
        try {
            w.append(new JSONObject().put("error", e.getMessage()).toString());
        } catch (JSONException e1) {
            throw new RuntimeException("Errorception!", e1);
        }
        w.close();
    }
}
Also used : PullRequest(com.atlassian.stash.pull.PullRequest) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) JSONException(org.json.JSONException) PullRequestMergeability(com.atlassian.stash.pull.PullRequestMergeability) Project(com.atlassian.stash.project.Project) Repository(com.atlassian.stash.repository.Repository) JSONObject(org.json.JSONObject) PullRequestMergeVeto(com.atlassian.stash.pull.PullRequestMergeVeto) Writer(java.io.Writer)

Example 4 with Repository

use of com.atlassian.stash.repository.Repository in project stashbot by palantir.

the class BuildTriggerServlet method doGet.

@Override
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    final String pathInfo = req.getPathInfo();
    final String reason = req.getParameter("reason");
    final String[] parts = pathInfo.split("/");
    if (parts.length != 4 && parts.length != 6) {
        throw new IllegalArgumentException("The format of the URL is " + URL_FORMAT);
    }
    final int repoId;
    final Repository repo;
    final RepositoryConfiguration rc;
    final JobTemplate jt;
    try {
        repoId = Integer.valueOf(parts[1]);
        repo = repositoryService.getById(repoId);
        if (repo == null) {
            throw new IllegalArgumentException("Unable to get a repository for id " + repoId);
        }
        rc = cpm.getRepositoryConfigurationForRepository(repo);
        jt = jtm.fromString(rc, parts[2].toLowerCase());
    } catch (SQLException e) {
        throw new IllegalArgumentException("SQLException occured", e);
    } catch (NumberFormatException e) {
        throw new IllegalArgumentException("The format of the URL is " + URL_FORMAT, e);
    }
    if (jt == null) {
        throw new IllegalArgumentException("Unable to get a valid JobTemplate from " + parts[2] + " for repository " + repo.toString());
    }
    // TODO: ensure this hash actually exists?
    final String buildHead = parts[3];
    final String mergeHead;
    final String pullRequestId;
    final PullRequest pullRequest;
    if (parts.length == 6 && !parts[4].isEmpty() && !parts[5].isEmpty()) {
        mergeHead = parts[4];
        try {
            pullRequestId = parts[5];
            pullRequest = pullRequestService.getById(repo.getId(), Long.parseLong(pullRequestId));
            if (pullRequest == null) {
                throw new IllegalArgumentException("Unable to find pull request for repo id " + repo.getId().toString() + " pr id " + pullRequestId);
            }
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("Unable to parse pull request id " + parts[5], e);
        }
    } else {
        mergeHead = null;
        pullRequestId = null;
        pullRequest = null;
    }
    if (mergeHead == null) {
        log.debug("Triggering build for buildHead " + buildHead);
        try {
            // When triggered this way, we don't know the buildRef, so leave it blank
            jenkinsManager.triggerBuild(repo, jt.getJobType(), buildHead, reason);
            printOutput(req, res);
            return;
        } catch (Exception e) {
            printErrorOutput(req, res, e);
            return;
        }
    }
    // pullRequest is not null if we reach here.
    try {
        jenkinsManager.triggerBuild(repo, jt.getJobType(), pullRequest);
    } catch (Exception e) {
        printErrorOutput(req, res, e);
        return;
    }
    printOutput(req, res);
    return;
}
Also used : Repository(com.atlassian.stash.repository.Repository) SQLException(java.sql.SQLException) PullRequest(com.atlassian.stash.pull.PullRequest) RepositoryConfiguration(com.palantir.stash.stashbot.persistence.RepositoryConfiguration) JobTemplate(com.palantir.stash.stashbot.persistence.JobTemplate) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) SQLException(java.sql.SQLException)

Example 5 with Repository

use of com.atlassian.stash.repository.Repository in project stashbot by palantir.

the class RepoConfigurationServlet method doPost.

@Override
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    Repository rep = getRepository(req);
    if (rep == null) {
        log.error("Failed to get repo for request" + req.toString());
        res.sendError(404);
        return;
    }
    try {
        permissionValidationService.validateForRepository(rep, Permission.REPO_ADMIN);
    } catch (AuthorisationException notRepoAdmin) {
        // Skip form processing
        doGet(req, res);
        return;
    }
    try {
        // This is the new jenkins server name
        String jenkinsServerName = req.getParameter("jenkinsServerName");
        // If either the old or the new Jenkins Server Configuration is "locked", and we are trying to change it, then enforce SYS_ADMIN instead of REPO_ADMIN
        try {
            RepositoryConfiguration rc = configurationPersistanceManager.getRepositoryConfigurationForRepository(rep);
            JenkinsServerConfiguration oldConfig = configurationPersistanceManager.getJenkinsServerConfiguration(rc.getJenkinsServerName());
            JenkinsServerConfiguration newConfig = configurationPersistanceManager.getJenkinsServerConfiguration(jenkinsServerName);
            if (!jenkinsServerName.equals(oldConfig.getName())) {
                if (oldConfig.getLocked()) {
                    permissionValidationService.validateForGlobal(Permission.SYS_ADMIN);
                }
                if (newConfig.getLocked()) {
                    permissionValidationService.validateForGlobal(Permission.SYS_ADMIN);
                }
            }
        } catch (AuthorisationException notSysAdmin) {
            // only thrown when oldconfig is locked and newconfig's name is different from oldconfig's name.
            log.warn("User {} tried to change the jenkins configuration which was locked for repo {}", req.getRemoteUser(), rep.getSlug());
            res.sendError(HttpServletResponse.SC_UNAUTHORIZED, "You do not have permission to change the jenkins server configuration");
            return;
        }
        configurationPersistanceManager.setRepositoryConfigurationForRepositoryFromRequest(rep, req);
        RepositoryConfiguration rc = configurationPersistanceManager.getRepositoryConfigurationForRepository(rep);
        if (rc.getCiEnabled()) {
            // ensure all pull request metadata exists
            PullRequestSearchRequest prsr = new PullRequestSearchRequest.Builder().toRepositoryId(rep.getId()).build();
            PageRequest pageReq = new PageRequestImpl(0, 500);
            Page<PullRequest> page = prs.search(prsr, pageReq);
            while (true) {
                for (PullRequest pr : page.getValues()) {
                    // this auto-vivifies if it doesn't already exist
                    configurationPersistanceManager.getPullRequestMetadata(pr);
                }
                if (page.getIsLastPage()) {
                    break;
                }
                pageReq = page.getNextPageRequest();
                page = prs.search(prsr, pageReq);
            }
            // add permission to the requisite user
            JenkinsServerConfiguration jsc = configurationPersistanceManager.getJenkinsServerConfiguration(jenkinsServerName);
            pluginUserManager.addUserToRepoForReading(jsc.getStashUsername(), rep);
            // ensure hook is enabled, jobs exist
            jenkinsManager.updateRepo(rep);
        }
    } catch (SQLException e) {
        log.error("Unable to get repository confguration", e);
    }
    doGet(req, res);
}
Also used : Repository(com.atlassian.stash.repository.Repository) PageRequest(com.atlassian.stash.util.PageRequest) SQLException(java.sql.SQLException) PullRequest(com.atlassian.stash.pull.PullRequest) PageRequestImpl(com.atlassian.stash.util.PageRequestImpl) AuthorisationException(com.atlassian.stash.exception.AuthorisationException) RepositoryConfiguration(com.palantir.stash.stashbot.persistence.RepositoryConfiguration) JenkinsServerConfiguration(com.palantir.stash.stashbot.persistence.JenkinsServerConfiguration) PullRequestSearchRequest(com.atlassian.stash.pull.PullRequestSearchRequest)

Aggregations

Repository (com.atlassian.stash.repository.Repository)24 RepositoryConfiguration (com.palantir.stash.stashbot.persistence.RepositoryConfiguration)13 SQLException (java.sql.SQLException)11 IOException (java.io.IOException)8 ServletException (javax.servlet.ServletException)8 PullRequest (com.atlassian.stash.pull.PullRequest)7 AuthorisationException (com.atlassian.stash.exception.AuthorisationException)6 PageRequest (com.atlassian.stash.util.PageRequest)5 PageRequestImpl (com.atlassian.stash.util.PageRequestImpl)5 ArrayList (java.util.ArrayList)5 Future (java.util.concurrent.Future)4 ImmutableMap (com.google.common.collect.ImmutableMap)3 GlobalSettings (com.palantir.stash.codesearch.admin.GlobalSettings)3 JenkinsServerConfiguration (com.palantir.stash.stashbot.persistence.JenkinsServerConfiguration)3 Test (org.junit.Test)3 EventListener (com.atlassian.event.api.EventListener)2 Changeset (com.atlassian.stash.content.Changeset)2 Branch (com.atlassian.stash.repository.Branch)2 EmailSettings (com.palantir.stash.stashbot.config.ConfigurationPersistenceService.EmailSettings)2 JobTemplate (com.palantir.stash.stashbot.persistence.JobTemplate)2