Search in sources :

Example 16 with Link

use of io.jenkins.blueocean.rest.hal.Link in project blueocean-plugin by jenkinsci.

the class AbstractBitbucketScm method getOrganizations.

@Override
public Container<ScmOrganization> getOrganizations() {
    User authenticatedUser = getAuthenticatedUser();
    StaplerRequest request = Stapler.getCurrentRequest();
    Objects.requireNonNull(request, "This request must be made in HTTP context");
    String credentialId = BitbucketCredentialUtils.computeCredentialId(getCredentialIdFromRequest(request), getId(), getUri());
    List<ErrorMessage.Error> errors = new ArrayList<>();
    StandardUsernamePasswordCredentials credential = null;
    if (credentialId == null) {
        errors.add(new ErrorMessage.Error("credentialId", ErrorMessage.Error.ErrorCodes.MISSING.toString(), "Missing credential id. It must be provided either as HTTP header: " + X_CREDENTIAL_ID + " or as query parameter 'credentialId'"));
    } else {
        credential = CredentialsUtils.findCredential(credentialId, StandardUsernamePasswordCredentials.class, new BlueOceanDomainRequirement());
        if (credential == null) {
            errors.add(new ErrorMessage.Error("credentialId", ErrorMessage.Error.ErrorCodes.INVALID.toString(), String.format("credentialId: %s not found in user %s's credential store", credentialId, authenticatedUser.getId())));
        }
    }
    String apiUrl = request.getParameter("apiUrl");
    if (StringUtils.isBlank(apiUrl)) {
        errors.add(new ErrorMessage.Error("apiUrl", ErrorMessage.Error.ErrorCodes.MISSING.toString(), "apiUrl is required parameter"));
    }
    if (!errors.isEmpty()) {
        throw new ServiceException.BadRequestException(new ErrorMessage(400, "Failed to return Bitbucket organizations").addAll(errors));
    } else {
        apiUrl = normalizeApiUrl(apiUrl);
        BitbucketApiFactory apiFactory = BitbucketApiFactory.resolve(this.getId());
        if (apiFactory == null) {
            throw new ServiceException.UnexpectedErrorException("BitbucketApiFactory to handle apiUrl " + apiUrl + " not found");
        }
        Objects.requireNonNull(credential);
        final BitbucketApi api = apiFactory.create(apiUrl, credential);
        return new Container<ScmOrganization>() {

            @Override
            public ScmOrganization get(String name) {
                return new BitbucketOrg(api.getOrg(name), api, getLink());
            }

            @Override
            public Link getLink() {
                return AbstractBitbucketScm.this.getLink().rel("organizations");
            }

            @Override
            public Iterator<ScmOrganization> iterator() {
                return iterator(0, 100);
            }

            @Override
            public Iterator<ScmOrganization> iterator(int start, int limit) {
                if (limit <= 0) {
                    limit = PagedResponse.DEFAULT_LIMIT;
                }
                if (start < 0) {
                    start = 0;
                }
                int page = (start / limit) + 1;
                return api.getOrgs(page, limit).getValues().stream().map(input -> {
                    if (input != null) {
                        return (ScmOrganization) new BitbucketOrg(input, api, getLink());
                    }
                    return null;
                }).iterator();
            }
        };
    }
}
Also used : BlueOceanDomainRequirement(io.jenkins.blueocean.rest.impl.pipeline.credential.BlueOceanDomainRequirement) StringUtils(org.apache.commons.lang.StringUtils) URL(java.net.URL) PagedResponse(io.jenkins.blueocean.rest.pageable.PagedResponse) StaplerRequest(org.kohsuke.stapler.StaplerRequest) ArrayList(java.util.ArrayList) UsernamePasswordCredentialsImpl(com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl) ScmOrganization(io.jenkins.blueocean.rest.impl.pipeline.scm.ScmOrganization) BlueOceanDomainSpecification(io.jenkins.blueocean.rest.impl.pipeline.credential.BlueOceanDomainSpecification) Container(io.jenkins.blueocean.rest.model.Container) User(hudson.model.User) CredentialsScope(com.cloudbees.plugins.credentials.CredentialsScope) CredentialsUtils(io.jenkins.blueocean.credential.CredentialsUtils) Nonnull(javax.annotation.Nonnull) Restricted(org.kohsuke.accmod.Restricted) Iterator(java.util.Iterator) HttpResponse(org.kohsuke.stapler.HttpResponse) MalformedURLException(java.net.MalformedURLException) Reachable(io.jenkins.blueocean.rest.Reachable) NoExternalUse(org.kohsuke.accmod.restrictions.NoExternalUse) IOException(java.io.IOException) ServiceException(io.jenkins.blueocean.commons.ServiceException) JsonBody(io.jenkins.blueocean.commons.stapler.JsonBody) Objects(java.util.Objects) StandardUsernamePasswordCredentials(com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials) List(java.util.List) Stapler(org.kohsuke.stapler.Stapler) BitbucketEndpointConfiguration(com.cloudbees.jenkins.plugins.bitbucket.endpoints.BitbucketEndpointConfiguration) JSONObject(net.sf.json.JSONObject) ErrorMessage(io.jenkins.blueocean.commons.ErrorMessage) AbstractScm(io.jenkins.blueocean.rest.impl.pipeline.scm.AbstractScm) Collections(java.util.Collections) Link(io.jenkins.blueocean.rest.hal.Link) User(hudson.model.User) StaplerRequest(org.kohsuke.stapler.StaplerRequest) ArrayList(java.util.ArrayList) StandardUsernamePasswordCredentials(com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials) Container(io.jenkins.blueocean.rest.model.Container) ScmOrganization(io.jenkins.blueocean.rest.impl.pipeline.scm.ScmOrganization) BlueOceanDomainRequirement(io.jenkins.blueocean.rest.impl.pipeline.credential.BlueOceanDomainRequirement) ErrorMessage(io.jenkins.blueocean.commons.ErrorMessage)

Example 17 with Link

use of io.jenkins.blueocean.rest.hal.Link in project blueocean-plugin by jenkinsci.

the class PipelineNodeGraphVisitor method getPipelineNodeSteps.

@Override
public List<BluePipelineStep> getPipelineNodeSteps(Link parent) {
    FlowExecution execution = run.getExecution();
    if (execution == null) {
        return Collections.emptyList();
    }
    PipelineStepVisitor visitor = new PipelineStepVisitor(run, null);
    ForkScanner.visitSimpleChunks(execution.getCurrentHeads(), visitor, new StageChunkFinder());
    return visitor.getSteps().stream().map(node -> new PipelineStepImpl(node, parent)).collect(Collectors.toList());
}
Also used : DepthFirstScanner(org.jenkinsci.plugins.workflow.graphanalysis.DepthFirstScanner) Arrays(java.util.Arrays) InputAction(org.jenkinsci.plugins.workflow.support.steps.input.InputAction) LoggerFactory(org.slf4j.LoggerFactory) LabelAction(org.jenkinsci.plugins.workflow.actions.LabelAction) StringUtils(org.apache.commons.lang3.StringUtils) GenericStatus(org.jenkinsci.plugins.workflow.pipelinegraphanalysis.GenericStatus) MemoryFlowChunk(org.jenkinsci.plugins.workflow.graphanalysis.MemoryFlowChunk) Map(java.util.Map) ExecutionModelAction(org.jenkinsci.plugins.pipeline.modeldefinition.actions.ExecutionModelAction) FlowExecution(org.jenkinsci.plugins.workflow.flow.FlowExecution) BluePipelineNode(io.jenkins.blueocean.rest.model.BluePipelineNode) Action(hudson.model.Action) Collection(java.util.Collection) Set(java.util.Set) Collectors(java.util.stream.Collectors) StepStartNode(org.jenkinsci.plugins.workflow.cps.nodes.StepStartNode) List(java.util.List) PauseAction(org.jenkinsci.plugins.workflow.support.actions.PauseAction) Optional(java.util.Optional) FlowStartNode(org.jenkinsci.plugins.workflow.graph.FlowStartNode) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings) WorkflowRun(org.jenkinsci.plugins.workflow.job.WorkflowRun) Link(io.jenkins.blueocean.rest.hal.Link) FlowNode(org.jenkinsci.plugins.workflow.graph.FlowNode) TimingAction(org.jenkinsci.plugins.workflow.actions.TimingAction) HashMap(java.util.HashMap) Stack(java.util.Stack) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) LinkedHashMap(java.util.LinkedHashMap) TimingInfo(org.jenkinsci.plugins.workflow.pipelinegraphanalysis.TimingInfo) BlockEndNode(org.jenkinsci.plugins.workflow.graph.BlockEndNode) StandardChunkVisitor(org.jenkinsci.plugins.workflow.graphanalysis.StandardChunkVisitor) Nonnull(javax.annotation.Nonnull) Nullable(javax.annotation.Nullable) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) StageChunkFinder(org.jenkinsci.plugins.workflow.pipelinegraphanalysis.StageChunkFinder) StatusAndTiming(org.jenkinsci.plugins.workflow.pipelinegraphanalysis.StatusAndTiming) BluePipelineStep(io.jenkins.blueocean.rest.model.BluePipelineStep) BlueRun(io.jenkins.blueocean.rest.model.BlueRun) NotExecutedNodeAction(org.jenkinsci.plugins.workflow.actions.NotExecutedNodeAction) IOException(java.io.IOException) ForkScanner(org.jenkinsci.plugins.workflow.graphanalysis.ForkScanner) StepAtomNode(org.jenkinsci.plugins.workflow.cps.nodes.StepAtomNode) StepEndNode(org.jenkinsci.plugins.workflow.cps.nodes.StepEndNode) ArrayDeque(java.util.ArrayDeque) Comparator(java.util.Comparator) CheckForNull(javax.annotation.CheckForNull) Collections(java.util.Collections) StageChunkFinder(org.jenkinsci.plugins.workflow.pipelinegraphanalysis.StageChunkFinder) FlowExecution(org.jenkinsci.plugins.workflow.flow.FlowExecution)

Example 18 with Link

use of io.jenkins.blueocean.rest.hal.Link in project blueocean-plugin by jenkinsci.

the class PipelineNodeTest method sequentialParallelStagesLongRun.

@Ignore("Fails on ci.jenkins.io but not locally. Reasons unclear.  Likely a timing issue.")
@Test
public void sequentialParallelStagesLongRun() throws Exception {
    WorkflowJob p = createWorkflowJobWithJenkinsfile(getClass(), "sequential_parallel_stages_long_run_time.jenkinsfile");
    Slave s = j.createOnlineSlave();
    s.setNumExecutors(3);
    WorkflowRun run = p.scheduleBuild2(0).waitForStart();
    j.waitForCompletion(run);
    List<String> watchedStages = Arrays.asList("first-sequential-stage", "second-sequential-stage", "third-sequential-stage");
    run = p.scheduleBuild2(0).waitForStart();
    Thread.sleep(1000);
    long loopCount = 0;
    while (run.isBuilding()) {
        PipelineNodeContainerImpl pipelineNodeContainer = new PipelineNodeContainerImpl(run, new Link("foo"));
        List<BluePipelineNode> nodes = pipelineNodeContainer.getNodes();
        for (BluePipelineNode node : nodes) {
            if (StringUtils.isEmpty(node.getFirstParent()) && watchedStages.contains(node.getDisplayName())) {
                LOGGER.error("node {} has getFirstParent null", node);
                fail("node with getFirstParent null:" + node);
            }
            // we try to find edges with id for a non existing node in the list
            List<BluePipelineNode.Edge> emptyEdges = node.getEdges().stream().filter(edge -> !nodes.stream().filter(bluePipelineNode -> bluePipelineNode.getId().equals(edge.getId())).findFirst().isPresent()).collect(Collectors.toList());
            if (!emptyEdges.isEmpty()) {
                // TODO remove this weird if but it's only to have breakpoint in IDE
                assertTrue("edges with unknown nodes" + nodes, !emptyEdges.isEmpty());
            }
        }
        LOGGER.debug("nodes size {}", nodes.size());
        if (nodes.size() != 9) {
            LOGGER.info("loop: " + loopCount + ", nodes size {}", nodes.size());
            LOGGER.info("nodes != 9 {}", nodes);
            fail("nodes != 9:  " + nodes);
        }
        Thread.sleep(100);
    }
}
Also used : CpsFlowDefinition(org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition) Arrays(java.util.Arrays) CoreMatchers.hasItem(org.hamcrest.CoreMatchers.hasItem) Issue(org.jvnet.hudson.test.Issue) QueueTaskFuture(hudson.model.queue.QueueTaskFuture) URL(java.net.URL) InputAction(org.jenkinsci.plugins.workflow.support.steps.input.InputAction) PARAMETERS_ELEMENT(io.jenkins.blueocean.rest.impl.pipeline.PipelineStepImpl.PARAMETERS_ELEMENT) StringUtils(org.apache.commons.lang3.StringUtils) RunList(hudson.util.RunList) MemoryFlowChunk(org.jenkinsci.plugins.workflow.graphanalysis.MemoryFlowChunk) Map(java.util.Map) FlowExecution(org.jenkinsci.plugins.workflow.flow.FlowExecution) BluePipelineNode(io.jenkins.blueocean.rest.model.BluePipelineNode) Jenkins(jenkins.model.Jenkins) MapsHelper(io.jenkins.blueocean.commons.MapsHelper) TypeSafeMatcher(org.hamcrest.TypeSafeMatcher) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) Run(hudson.model.Run) IOUtils(org.apache.commons.io.IOUtils) List(java.util.List) NodeDownstreamBuildAction(io.jenkins.blueocean.listeners.NodeDownstreamBuildAction) FilePath(hudson.FilePath) Result(hudson.model.Result) JSONObject(net.sf.json.JSONObject) WorkflowMultiBranchProject(org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject) Optional(java.util.Optional) WorkflowRun(org.jenkinsci.plugins.workflow.job.WorkflowRun) Link(io.jenkins.blueocean.rest.hal.Link) FlowNode(org.jenkinsci.plugins.workflow.graph.FlowNode) BeforeClass(org.junit.BeforeClass) SemaphoreStep(org.jenkinsci.plugins.workflow.test.steps.SemaphoreStep) FreeStyleProject(hudson.model.FreeStyleProject) CpsFlowExecution(org.jenkinsci.plugins.workflow.cps.CpsFlowExecution) FlowGraphTable(org.jenkinsci.plugins.workflow.support.visualization.table.FlowGraphTable) UnstableStep(org.jenkinsci.plugins.workflow.steps.UnstableStep) GitSampleRepoRule(jenkins.plugins.git.GitSampleRepoRule) Unirest(com.mashape.unirest.http.Unirest) SCMSource(jenkins.scm.api.SCMSource) Util(hudson.Util) WorkflowJob(org.jenkinsci.plugins.workflow.job.WorkflowJob) Description(org.hamcrest.Description) Iterator(java.util.Iterator) BluePipelineStep(io.jenkins.blueocean.rest.model.BluePipelineStep) BlueRun(io.jenkins.blueocean.rest.model.BlueRun) Test(org.junit.Test) BranchSource(jenkins.branch.BranchSource) File(java.io.File) TimeUnit(java.util.concurrent.TimeUnit) Rule(org.junit.Rule) Ignore(org.junit.Ignore) Matcher(org.hamcrest.Matcher) Assert(org.junit.Assert) Slave(hudson.model.Slave) ExtensionList(hudson.ExtensionList) GitSCMSource(jenkins.plugins.git.GitSCMSource) WorkflowRun(org.jenkinsci.plugins.workflow.job.WorkflowRun) Slave(hudson.model.Slave) WorkflowJob(org.jenkinsci.plugins.workflow.job.WorkflowJob) BluePipelineNode(io.jenkins.blueocean.rest.model.BluePipelineNode) Link(io.jenkins.blueocean.rest.hal.Link) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 19 with Link

use of io.jenkins.blueocean.rest.hal.Link in project blueocean-plugin by jenkinsci.

the class PipelineNodeTest method checkConsistencyWhileBuilding.

private String checkConsistencyWhileBuilding(String jenkinsFileName) throws Exception {
    /*
            Run a complex pipeline to completion, then start a new build and inspect it while it's running, to exercise
            the code that merges incomplete runs with previous builds to generate a complete graph
         */
    WorkflowJob p = createWorkflowJobWithJenkinsfile(getClass(), jenkinsFileName);
    // Do an initial run, collect the nodes
    final WorkflowRun run1 = p.scheduleBuild2(0).waitForStart();
    j.waitForCompletion(run1);
    final List<BluePipelineNode> completeNodes = new PipelineNodeContainerImpl(run1, new Link("foo")).getNodes();
    final String completeNodeNames = completeNodes.stream().map(BluePipelineStep::getDisplayName).sorted().collect(Collectors.joining(", "));
    // Start another build...
    final WorkflowRun run2 = p.scheduleBuild2(0).waitForStart();
    // ... then watch while it runs, checking for the same graph nodes
    int loopCount = 0;
    do {
        Thread.sleep(1000);
        List<BluePipelineNode> runningNodes = new PipelineNodeContainerImpl(run2, new Link("foo")).getNodes();
        String runningNodeNames = runningNodes.stream().map(BluePipelineStep::getDisplayName).sorted().collect(Collectors.joining(", "));
        assertEquals("running node names", completeNodeNames, runningNodeNames);
        loopCount++;
    } while (run2.isBuilding());
    // Sanity check, make sure we're *actually* checking stuff.
    assertTrue("Checked multiple times while building", loopCount > 5);
    // So caller can do any additional checks
    return completeNodeNames;
}
Also used : WorkflowJob(org.jenkinsci.plugins.workflow.job.WorkflowJob) BluePipelineNode(io.jenkins.blueocean.rest.model.BluePipelineNode) WorkflowRun(org.jenkinsci.plugins.workflow.job.WorkflowRun) Link(io.jenkins.blueocean.rest.hal.Link) BluePipelineStep(io.jenkins.blueocean.rest.model.BluePipelineStep)

Example 20 with Link

use of io.jenkins.blueocean.rest.hal.Link in project blueocean-plugin by jenkinsci.

the class OrganizationFolderTest method mockOrganization.

static BlueOrganization mockOrganization() {
    BlueOrganization organization = mock(BlueOrganization.class);
    when(organization.getName()).thenReturn("jenkins");
    when(organization.getLink()).thenReturn(new Link("/blue/rest/organizations/jenkins/"));
    return organization;
}
Also used : BlueOrganization(io.jenkins.blueocean.rest.model.BlueOrganization) Link(io.jenkins.blueocean.rest.hal.Link)

Aggregations

Link (io.jenkins.blueocean.rest.hal.Link)30 Test (org.junit.Test)12 BlueRun (io.jenkins.blueocean.rest.model.BlueRun)8 Run (hudson.model.Run)7 WorkflowJob (org.jenkinsci.plugins.workflow.job.WorkflowJob)7 Reachable (io.jenkins.blueocean.rest.Reachable)6 IOException (java.io.IOException)6 ArrayList (java.util.ArrayList)6 List (java.util.List)6 BlueOrganization (io.jenkins.blueocean.rest.model.BlueOrganization)5 BluePipelineNode (io.jenkins.blueocean.rest.model.BluePipelineNode)5 HashMap (java.util.HashMap)4 Map (java.util.Map)4 Optional (java.util.Optional)4 Collectors (java.util.stream.Collectors)4 WorkflowRun (org.jenkinsci.plugins.workflow.job.WorkflowRun)4 Job (hudson.model.Job)3 ServiceException (io.jenkins.blueocean.commons.ServiceException)3 BluePipelineStep (io.jenkins.blueocean.rest.model.BluePipelineStep)3 BlueQueueItem (io.jenkins.blueocean.rest.model.BlueQueueItem)3