org.jenkinsci.plugins.workflow.flow.FlowExecution Java Examples

The following examples show how to use org.jenkinsci.plugins.workflow.flow.FlowExecution. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GithubBuildStatusGraphListenerTest.java    From github-autostatus-plugin with MIT License 6 votes vote down vote up
@Test
public void testStageNode() throws IOException {
    StepStartNode stageNode = mock(StepStartNode.class);
    StageAction stageAction = mock(StageAction.class);
    FlowExecution execution = mock(FlowExecution.class);
    when(stageNode.getAction(StageAction.class)).thenReturn(stageAction);
    when(stageNode.getExecution()).thenReturn(execution);
    FlowExecutionOwner owner = mock(FlowExecutionOwner.class);
    when(execution.getOwner()).thenReturn(owner);
    AbstractBuild build = mock(AbstractBuild.class);

    when(owner.getExecutable()).thenReturn(build);
    ExecutionModelAction executionModel = mock(ExecutionModelAction.class);
    when(build.getAction(ExecutionModelAction.class)).thenReturn(executionModel);

    ModelASTStages stages = new ModelASTStages(null);
    when(executionModel.getStages()).thenReturn(stages);

    GithubBuildStatusGraphListener instance = new GithubBuildStatusGraphListener();
    instance.onNewHead(stageNode);
    verify(build).addAction(any(BuildStatusAction.class));
}
 
Example #2
Source File: GitLabSCMPublishAction.java    From gitlab-branch-source-plugin with GNU General Public License v2.0 6 votes vote down vote up
private void attachGraphListener(final WorkflowRun build, final GraphListener listener) {
    build.getExecutionPromise().addListener(
        new Runnable() {
            @Override
            public void run() {
                build.addAction(new RunningContextsAction());
                FlowExecution execution = build.getExecution();
                if (execution != null) {
                    execution.addListener(listener);
                } else {
                    LOGGER.log(SEVERE, "could not get flow-execution for build " + build.getFullDisplayName());
                }
            }
        },
        Executors.newSingleThreadExecutor()
    );
}
 
Example #3
Source File: PipelineNodeGraphVisitor.java    From blueocean-plugin with MIT License 6 votes vote down vote up
public PipelineNodeGraphVisitor(WorkflowRun run) {
    this.run = run;
    this.inputAction = run.getAction(InputAction.class);
    this.pipelineActions = new HashSet<>();
    this.pendingActionsForBranches = new HashMap<>();
    declarative = run.getAction(ExecutionModelAction.class) != null;
    FlowExecution execution = run.getExecution();
    if (execution != null) {
        try {
            ForkScanner.visitSimpleChunks(execution.getCurrentHeads(), this, new StageChunkFinder());
        } catch (final Throwable t) {
            // Log run ID, because the eventual exception handler (probably Stapler) isn't specific enough to do so
            logger.error("Caught a " + t.getClass().getSimpleName() +
                             " traversing the graph for run " + run.getExternalizableId());
            throw t;
        }
    } else {
        logger.debug("Could not find execution for run " + run.getExternalizableId());
    }
}
 
Example #4
Source File: PipelineNodeGraphVisitor.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Override
public List<BluePipelineStep> getPipelineNodeSteps(final String nodeId, Link parent) {
    FlowExecution execution = run.getExecution();
    if (execution == null) {
        logger.debug(String.format("Pipeline %s, runid %s  has null execution", run.getParent().getName(), run.getId()));
        return Collections.emptyList();
    }
    DepthFirstScanner depthFirstScanner = new DepthFirstScanner();
    //If blocked scope, get the end node
    FlowNode n = depthFirstScanner
        .findFirstMatch(execution.getCurrentHeads(),
                        input -> (input != null
                            && input.getId().equals(nodeId)
                            && (PipelineNodeUtil.isStage(input) || PipelineNodeUtil.isParallelBranch(input))));

    if (n == null) { //if no node found or the node is not stage or parallel we return empty steps
        return Collections.emptyList();
    }
    PipelineStepVisitor visitor = new PipelineStepVisitor(run, n);
    ForkScanner.visitSimpleChunks(execution.getCurrentHeads(), visitor, new StageChunkFinder());
    return visitor.getSteps()
                  .stream()
                  .map(node -> new PipelineStepImpl(node, parent))
                  .collect(Collectors.toList());
}
 
Example #5
Source File: DefaultsBinder.java    From pipeline-multibranch-defaults-plugin with MIT License 6 votes vote down vote up
@Override
public FlowExecution create(FlowExecutionOwner handle, TaskListener listener, List<? extends Action> actions) throws Exception {
    Jenkins jenkins = Jenkins.getInstance();
    if (jenkins == null) {
        throw new IllegalStateException("inappropriate context");
    }
    Queue.Executable exec = handle.getExecutable();
    if (!(exec instanceof WorkflowRun)) {
        throw new IllegalStateException("inappropriate context");
    }

    ConfigFileStore store = GlobalConfigFiles.get();
    if (store != null) {
        Config config = store.getById(PipelineBranchDefaultsProjectFactory.SCRIPT);
        if (config != null) {
            return new CpsFlowDefinition(config.content, false).create(handle, listener, actions);
        }
    }
    throw new IllegalArgumentException("Default " + PipelineBranchDefaultsProjectFactory.SCRIPT + " not found. Check configuration.");
}
 
Example #6
Source File: PipelineNodeTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Issue("JENKINS-47158")
@Test
public void syntheticParallelFlowNodeNotSaved() throws Exception {
    WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "pipeline1");
    p.setDefinition(new CpsFlowDefinition("parallel a: {\n" +
                                              "    node {\n" +
                                              "        echo 'a'\n" +
                                              "    }\n" +
                                              "}, b: {\n" +
                                              "    node {\n" +
                                              "        echo 'b'\n" +
                                              "    }\n" +
                                              "}\n", true));
    WorkflowRun b = j.buildAndAssertSuccess(p);
    get("/organizations/jenkins/pipelines/pipeline1/runs/1/nodes/", List.class);
    FlowExecution rawExec = b.getExecution();
    assert (rawExec instanceof CpsFlowExecution);
    CpsFlowExecution execution = (CpsFlowExecution) rawExec;
    File storage = execution.getStorageDir();

    // Nodes 5 and 6 are the parallel branch start nodes. Make sure no "5-parallel-synthetic.xml" and "6..." files
    // exist in the storage directory, showing we haven't saved them.
    assertFalse(new File(storage, "5-parallel-synthetic.xml").exists());
    assertFalse(new File(storage, "6-parallel-synthetic.xml").exists());
}
 
Example #7
Source File: PipelineNodeGraphVisitor.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Override
public BluePipelineStep getPipelineNodeStep(String id, Link parent) {
    FlowExecution execution = run.getExecution();
    if (execution == null) {
        return null;
    }
    PipelineStepVisitor visitor = new PipelineStepVisitor(run, null);
    ForkScanner.visitSimpleChunks(execution.getCurrentHeads(), visitor, new StageChunkFinder());
    FlowNodeWrapper node = visitor.getStep(id);
    if (node == null) {
        return null;
    }
    return new PipelineStepImpl(node, parent);
}
 
Example #8
Source File: PipelineHelper.java    From jenkins-build-monitor-plugin with MIT License 5 votes vote down vote up
public static List<String> getPipelines(Run<?, ?> run) {
    WorkflowRun currentBuild = (WorkflowRun) run;
    FlowExecution execution = currentBuild.getExecution();
    if (execution != null) {
        WorkflowNodeTraversal traversal = new WorkflowNodeTraversal();
        traversal.start(execution.getCurrentHeads());
        return traversal.getStages();
    }
    return Collections.emptyList();
}
 
Example #9
Source File: JUnitResultsStepTest.java    From junit-plugin with MIT License 5 votes vote down vote up
public static void assertStageResults(WorkflowRun run, int suiteCount, int testCount, int failCount, String stageName) {
    FlowExecution execution = run.getExecution();
    DepthFirstScanner scanner = new DepthFirstScanner();
    BlockStartNode aStage = (BlockStartNode)scanner.findFirstMatch(execution, stageForName(stageName));
    assertNotNull(aStage);
    assertBlockResults(run, suiteCount, testCount, failCount, aStage);
}
 
Example #10
Source File: JUnitResultsStepTest.java    From junit-plugin with MIT License 5 votes vote down vote up
public static void assertBranchResults(WorkflowRun run, int suiteCount, int testCount, int failCount, String branchName, String stageName,
                                       String innerStageName) {
    FlowExecution execution = run.getExecution();
    DepthFirstScanner scanner = new DepthFirstScanner();
    BlockStartNode aBranch = (BlockStartNode)scanner.findFirstMatch(execution, branchForName(branchName));
    assertNotNull(aBranch);
    TestResult branchResult = assertBlockResults(run, suiteCount, testCount, failCount, aBranch);
    String namePrefix = stageName + " / " + branchName;
    if (innerStageName != null) {
        namePrefix += " / " + innerStageName;
    }
    for (CaseResult c : branchResult.getPassedTests()) {
        assertEquals(namePrefix + " / " + c.getTransformedTestName(), c.getDisplayName());
    }
}
 
Example #11
Source File: JUnitResultsStepTest.java    From junit-plugin with MIT License 5 votes vote down vote up
@Issue("JENKINS-48250")
@Test
public void emptyFails() throws Exception {
    WorkflowJob j = rule.jenkins.createProject(WorkflowJob.class, "emptyFails");
    j.setDefinition(new CpsFlowDefinition("stage('first') {\n" +
            "  node {\n" +
            (Functions.isWindows() ?
            "    bat 'echo hi'\n" :
            "    sh 'echo hi'\n") +
            "    junit('*.xml')\n" +
            "  }\n" +
            "}\n", true));

    WorkflowRun r = j.scheduleBuild2(0).waitForStart();
    rule.assertBuildStatus(Result.FAILURE, rule.waitForCompletion(r));
    rule.assertLogContains("ERROR: " + Messages.JUnitResultArchiver_NoTestReportFound(), r);
    FlowExecution execution = r.getExecution();
    DepthFirstScanner scanner = new DepthFirstScanner();
    FlowNode f = scanner.findFirstMatch(execution, new Predicate<FlowNode>() {
        @Override
        public boolean apply(@Nullable FlowNode input) {
            return input instanceof StepAtomNode &&
                    ((StepAtomNode) input).getDescriptor() instanceof JUnitResultsStep.DescriptorImpl;
        }
    });
    assertNotNull(f);
    LogAction logAction = f.getPersistentAction(LogAction.class);
    assertNotNull(logAction);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    logAction.getLogText().writeRawLogTo(0, baos);
    String log = baos.toString();
    assertThat(log, CoreMatchers.containsString(Messages.JUnitResultArchiver_NoTestReportFound()));
}
 
Example #12
Source File: PipelineEventListener.java    From blueocean-plugin with MIT License 5 votes vote down vote up
private static Message newMessage(PipelineEventChannel.Event event, FlowExecution exec) {
    SimpleMessage message = new SimpleMessage()
            .setChannelName(PipelineEventChannel.NAME)
            .setEventName(event);
    Run<?, ?> run = runFor(exec);
    if (run != null) {
        message.set(PipelineEventChannel.EventProps.pipeline_job_name, run.getParent().getFullName())
               .set(PipelineEventChannel.EventProps.pipeline_run_id, run.getId());
    }
    return message;
}
 
Example #13
Source File: PipelineEventListener.java    From blueocean-plugin with MIT License 5 votes vote down vote up
private static @CheckForNull Run<?, ?> runFor(FlowExecution exec) {
    Queue.Executable executable;
    try {
        executable = exec.getOwner().getExecutable();
    } catch (IOException x) {
        LOGGER.log(Level.WARNING, null, x);
        return null;
    }
    if (executable instanceof Run) {
        return (Run<?, ?>) executable;
    } else {
        return null;
    }
}
 
Example #14
Source File: PipelineNodeGraphVisitor.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@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());
}
 
Example #15
Source File: GithubBuildStatusGraphListenerTest.java    From github-autostatus-plugin with MIT License 5 votes vote down vote up
public void testComplexPipeline() throws IOException {
    StepStartNode stageNode = mock(StepStartNode.class);
    StageAction stageAction = mock(StageAction.class);
    FlowExecution execution = mock(FlowExecution.class);
    when(stageNode.getAction(StageAction.class)).thenReturn(stageAction);
    when(stageNode.getExecution()).thenReturn(execution);
    FlowExecutionOwner owner = mock(FlowExecutionOwner.class);
    when(execution.getOwner()).thenReturn(owner);
    AbstractBuild build = mock(AbstractBuild.class);

    when(owner.getExecutable()).thenReturn(build);
    ExecutionModelAction executionModel = mock(ExecutionModelAction.class);
    when(build.getAction(ExecutionModelAction.class)).thenReturn(executionModel);

    // Construct a complex pipeline model
    ModelASTStages stages = createStages("Outer Stage 1", "Outer Stage 2");
    ModelASTStages innerStages = createStages("Inner Stage 1", "Inner Stage 2", "Inner Stage 3");
    ModelASTStages innerInnerStages = createStages("Inner Inner Stage 1");
    ModelASTStages parallelStages = createStages("Parallel Stage 1", "Parallel Stage 2");
    stages.getStages().get(0).setStages(innerStages);
    innerStages.getStages().get(2).setStages(innerInnerStages);
    stages.getStages().get(1).setParallelContent(parallelStages.getStages());
    // Create a linear list of the pipeline stages for comparison
    List<String> fullStageList = Arrays.asList(new String[]{"Outer Stage 1", "Inner Stage 1", "Inner Stage 2", "Inner Stage 3", "Inner Inner Stage 1", "Outer Stage 2", "Parallel Stage 1", "Parallel Stage 2"});

    when(executionModel.getStages()).thenReturn(stages);

    GithubBuildStatusGraphListener instance = new GithubBuildStatusGraphListener();
    instance.onNewHead(stageNode);
    verify(build).addAction(any(BuildStatusAction.class));
    // Check that the pipeline stages found match the list of expected stages
    assertTrue(GithubBuildStatusGraphListener.getDeclarativeStages(build).equals(fullStageList));
}
 
Example #16
Source File: GithubBuildStatusGraphListener.java    From github-autostatus-plugin with MIT License 5 votes vote down vote up
/**
 * Gets the jenkins run object of the specified executing workflow.
 *
 * @param exec execution of a workflow
 * @return jenkins run object of a job
 */
private static @CheckForNull Run<?, ?> runFor(FlowExecution exec) {
    Queue.Executable executable;
    try {
        executable = exec.getOwner().getExecutable();
    } catch (IOException x) {
        getLogger().log(Level.WARNING, null, x);
        return null;
    }
    if (executable instanceof Run) {
        return (Run<?, ?>) executable;
    } else {
        return null;
    }
}
 
Example #17
Source File: GithubBuildStatusGraphListener.java    From github-autostatus-plugin with MIT License 5 votes vote down vote up
private static @CheckForNull BuildStatusAction buildStatusActionFor(FlowExecution exec) {
    BuildStatusAction buildStatusAction = null;
    Run<?, ?> run = runFor(exec);
    if (run != null) {
        buildStatusAction = run.getAction(BuildStatusAction.class);
    }
    return buildStatusAction;
}
 
Example #18
Source File: YamlFlowDefinition.java    From simple-pull-request-job-plugin with Apache License 2.0 4 votes vote down vote up
@Override
public FlowExecution create(FlowExecutionOwner owner, TaskListener listener,
                            List<? extends Action> actions) throws Exception {
    Queue.Executable exec = owner.getExecutable();
    if (!(exec instanceof WorkflowRun)) {
        throw new IllegalStateException("inappropriate context");
    }

    WorkflowRun build = (WorkflowRun) exec;
    WorkflowJob job = build.getParent();
    BranchJobProperty property = job.getProperty(BranchJobProperty.class);

    Branch branch = property.getBranch();
    ItemGroup<?> parent = job.getParent();

    if (!(parent instanceof WorkflowMultiBranchProject)) {
        throw new IllegalStateException("inappropriate context");
    }

    SCMSource scmSource = ((WorkflowMultiBranchProject) parent).getSCMSource(branch.getSourceId());

    if (scmSource == null) {
        throw new IllegalStateException(branch.getSourceId() + " not found");
    }

    GitConfig gitConfig = new GitConfig();

    SCMHead head = branch.getHead();

    if ("Pull Request".equals(head.getPronoun())) {
        ChangeRequestSCMHead2 changeRequestSCMHead2 = (ChangeRequestSCMHead2) branch.getHead();
        head = changeRequestSCMHead2.getTarget();
    }

    SCMRevision tip = scmSource.fetch(head, listener);

    if (tip == null) {
        throw new IllegalStateException("Cannot determine the revision.");
    }

    SCMRevision rev = scmSource.getTrustedRevision(tip, listener);
    GitSCM gitSCM = (GitSCM) scmSource.build(head, rev);

    gitConfig.setGitUrl(gitSCM.getUserRemoteConfigs().get(0).getUrl());
    gitConfig.setCredentialsId(gitSCM.getUserRemoteConfigs().get(0).getCredentialsId());
    gitConfig.setGitBranch(head.getName());

    String script;
    try (SCMFileSystem fs = SCMFileSystem.of(scmSource, head, rev)) {
        if (fs != null) {
            InputStream yamlInputStream = fs.child(scriptPath).content();
            listener.getLogger().println("Path of yaml/yml config file: " + fs.child(scriptPath).getPath());
            YamlToPipeline y = new YamlToPipeline();
            script = y.generatePipeline(yamlInputStream, gitConfig, listener);
        } else {
            throw new IOException("SCM not supported");
            // FIXME implement full checkout
        }
    }

    listener.getLogger().println(script);
    return new CpsFlowExecution(script, false, owner);
}
 
Example #19
Source File: PipelineEventListener.java    From blueocean-plugin with MIT License 4 votes vote down vote up
@Override
public void onRunning(FlowExecution execution) {
    publishEvent(newMessage(PipelineEventChannel.Event.pipeline_start, execution));
}
 
Example #20
Source File: GithubBuildStatusGraphListener.java    From github-autostatus-plugin with MIT License 4 votes vote down vote up
/**
 * Checks whether the current build meets our requirements for providing
 * status, and adds a BuildStatusAction to the build if so.
 *
 * @param flowNode node of a workflow
 */
private static void checkEnableBuildStatus(FlowNode flowNode) {
    FlowExecution exec = flowNode.getExecution();
    try {
        BuildStatusAction buildStatusAction = buildStatusActionFor(exec);

        Run<?, ?> run = runFor(exec);
        if (null == run) {
            log(Level.WARNING, "Could not find Run - status will not be provided build");
            return;
        }

        // Declarative pipeline jobs come with a nice execution model, which allows you
        // to get all of the stages at once at the beginning of the job.
        // Older scripted pipeline jobs do not, so we have to add them one at a
        // time as we discover them.
        List<BuildStage> stageNames = getDeclarativeStages(run);
        boolean isDeclarativePipeline = stageNames != null;

        String targetUrl;
        try {
            targetUrl = DisplayURLProvider.get().getRunURL(run);
        } catch (Exception e) {
            targetUrl = "";
        }

        if (isDeclarativePipeline && buildStatusAction != null) {
            buildStatusAction.connectNotifiers(run, targetUrl);
            return;
        }
        if (stageNames == null) {
            ArrayList<BuildStage> stageNameList = new ArrayList<>();
            stageNameList.add(new BuildStage(flowNode.getDisplayName()));
            stageNames = stageNameList;
        }

        if (buildStatusAction == null) {
            buildStatusAction = BuildStatusAction.newAction(run, targetUrl, stageNames);
            buildStatusAction.setIsDeclarativePipeline(isDeclarativePipeline);

            run.addAction(buildStatusAction);
        } else {
            buildStatusAction.addBuildStatus(flowNode.getDisplayName());
        }
    } catch (Exception ex) {
        try {
            exec.getOwner().getListener().getLogger().println(ex.toString());
        } catch (IOException ex1) {
            Logger.getLogger(GithubBuildStatusGraphListener.class.getName()).log(Level.SEVERE, null, ex1);
        }
        Logger.getLogger(GithubBuildStatusGraphListener.class.getName()).log(Level.SEVERE, null, ex);
    }
}