Search in sources :

Example 1 with FlowExecution

use of org.jenkinsci.plugins.workflow.flow.FlowExecution in project workflow-cps-plugin by jenkinsci.

the class CpsFlowExecution method suspendAll.

@Restricted(DoNotUse.class)
@Terminator
public static void suspendAll() {
    CpsFlowExecution exec = null;
    try (Timeout t = Timeout.limit(3, TimeUnit.MINUTES)) {
        // TODO some complicated sequence of calls to Futures could allow all of them to run in parallel
        LOGGER.fine("starting to suspend all executions");
        for (FlowExecution execution : FlowExecutionList.get()) {
            if (execution instanceof CpsFlowExecution) {
                LOGGER.log(Level.FINE, "waiting to suspend {0}", execution);
                exec = (CpsFlowExecution) execution;
                // Like waitForSuspension but with a timeout:
                if (exec.programPromise != null) {
                    exec.programPromise.get(1, TimeUnit.MINUTES).scheduleRun().get(1, TimeUnit.MINUTES);
                }
            }
        }
        LOGGER.fine("finished suspending all executions");
    } catch (Exception x) {
        LOGGER.log(Level.WARNING, "problem suspending " + exec, x);
    }
}
Also used : Timeout(org.jenkinsci.plugins.workflow.support.concurrent.Timeout) FlowExecution(org.jenkinsci.plugins.workflow.flow.FlowExecution) UsernameNotFoundException(org.acegisecurity.userdetails.UsernameNotFoundException) AbortException(hudson.AbortException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) TimeoutException(java.util.concurrent.TimeoutException) FlowInterruptedException(org.jenkinsci.plugins.workflow.steps.FlowInterruptedException) Restricted(org.kohsuke.accmod.Restricted) Terminator(hudson.init.Terminator)

Example 2 with FlowExecution

use of org.jenkinsci.plugins.workflow.flow.FlowExecution in project workflow-cps-plugin by jenkinsci.

the class ArgumentsActionImplTest method testBasicCredentials.

@Test
public void testBasicCredentials() throws Exception {
    String username = "bob";
    String password = "s3cr3t";
    UsernamePasswordCredentialsImpl c = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "test", "sample", username, password);
    CredentialsProvider.lookupStores(r.jenkins).iterator().next().addCredentials(Domain.global(), c);
    WorkflowJob job = r.jenkins.createProject(WorkflowJob.class, "credentialed");
    job.setDefinition(new CpsFlowDefinition("node{ withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: 'test',\n" + "                usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD']]) {\n" + "    //available as an env variable, but will be masked if you try to print it out any which way\n" + "    echo \"$PASSWORD'\" \n" + "    echo \"${env.USERNAME}\"\n" + "    echo \"bob\"\n" + "} }\n" + "withCredentials([usernamePassword(credentialsId: 'test', usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD')]) {\n" + "  echo \"${env.USERNAME} ${env.PASSWORD}\"\n" + "}"));
    WorkflowRun run = job.scheduleBuild2(0).getStartCondition().get();
    r.waitForCompletion(run);
    FlowExecution exec = run.getExecution();
    String log = r.getLog(run);
    ForkScanner scanner = new ForkScanner();
    List<FlowNode> filtered = scanner.filteredNodes(exec, new DescriptorMatchPredicate(BindingStep.DescriptorImpl.class));
    // Check the binding step is OK
    Assert.assertEquals(8, filtered.size());
    FlowNode node = Collections2.filter(filtered, FlowScanningUtils.hasActionPredicate(ArgumentsActionImpl.class)).iterator().next();
    ArgumentsActionImpl act = node.getPersistentAction(ArgumentsActionImpl.class);
    Assert.assertNotNull(act.getArgumentValue("bindings"));
    Assert.assertNotNull(act.getArguments().get("bindings"));
    // Test that masking really does mask bound credentials appropriately
    filtered = scanner.filteredNodes(exec, new DescriptorMatchPredicate(EchoStep.DescriptorImpl.class));
    for (FlowNode f : filtered) {
        act = f.getPersistentAction(ArgumentsActionImpl.class);
        Assert.assertEquals(ArgumentsAction.NotStoredReason.MASKED_VALUE, act.getArguments().get("message"));
        Assert.assertNull(ArgumentsAction.getStepArgumentsAsString(f));
    }
    List<FlowNode> allStepped = scanner.filteredNodes(run.getExecution().getCurrentHeads(), FlowScanningUtils.hasActionPredicate(ArgumentsActionImpl.class));
    // One ArgumentsActionImpl per block or atomic step
    Assert.assertEquals(6, allStepped.size());
    testDeserialize(exec);
}
Also used : DescriptorMatchPredicate(org.jenkinsci.plugins.workflow.cps.DescriptorMatchPredicate) EchoStep(org.jenkinsci.plugins.workflow.steps.EchoStep) ForkScanner(org.jenkinsci.plugins.workflow.graphanalysis.ForkScanner) UsernamePasswordCredentialsImpl(com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl) WorkflowRun(org.jenkinsci.plugins.workflow.job.WorkflowRun) CpsFlowDefinition(org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition) FlowExecution(org.jenkinsci.plugins.workflow.flow.FlowExecution) CpsFlowExecution(org.jenkinsci.plugins.workflow.cps.CpsFlowExecution) WorkflowJob(org.jenkinsci.plugins.workflow.job.WorkflowJob) FlowNode(org.jenkinsci.plugins.workflow.graph.FlowNode) Test(org.junit.Test)

Example 3 with FlowExecution

use of org.jenkinsci.plugins.workflow.flow.FlowExecution in project workflow-cps-plugin by jenkinsci.

the class FlowDurabilityTest method testResumeBlockedAddedAfterRunStart.

@Test
@Issue("JENKINS-49961")
public void testResumeBlockedAddedAfterRunStart() throws Exception {
    final String jobName = "survivesEverything";
    final String[] logStart = new String[1];
    final List<FlowNode> nodesOut = new ArrayList<FlowNode>();
    story.addStepWithDirtyShutdown(new Statement() {

        @Override
        public void evaluate() throws Throwable {
            Jenkins jenkins = story.j.jenkins;
            WorkflowRun run = createAndRunSleeperJob(story.j.jenkins, jobName, FlowDurabilityHint.MAX_SURVIVABILITY);
            run.getParent().setResumeBlocked(false);
            FlowExecution exec = run.getExecution();
            if (exec instanceof CpsFlowExecution) {
                assert ((CpsFlowExecution) exec).getStorage().isPersistedFully();
            }
            logStart[0] = JenkinsRule.getLog(run);
            nodesOut.addAll(new DepthFirstScanner().allNodes(run.getExecution()));
            nodesOut.sort(FlowScanningUtils.ID_ORDER_COMPARATOR);
            run.getParent().setResumeBlocked(true);
        }
    });
    story.addStep(new Statement() {

        @Override
        public void evaluate() throws Throwable {
            WorkflowRun run = story.j.jenkins.getItemByFullName(jobName, WorkflowJob.class).getLastBuild();
            verifyFailedCleanly(story.j.jenkins, run);
            assertIncludesNodes(nodesOut, run);
        }
    });
}
Also used : Statement(org.junit.runners.model.Statement) ArrayList(java.util.ArrayList) WorkflowRun(org.jenkinsci.plugins.workflow.job.WorkflowRun) DepthFirstScanner(org.jenkinsci.plugins.workflow.graphanalysis.DepthFirstScanner) Jenkins(jenkins.model.Jenkins) FlowExecution(org.jenkinsci.plugins.workflow.flow.FlowExecution) FlowNode(org.jenkinsci.plugins.workflow.graph.FlowNode) Issue(org.jvnet.hudson.test.Issue) Test(org.junit.Test)

Example 4 with FlowExecution

use of org.jenkinsci.plugins.workflow.flow.FlowExecution in project workflow-cps-plugin by jenkinsci.

the class FlowDurabilityTest method verifyExecutionRemoved.

private static void verifyExecutionRemoved(WorkflowRun run) throws Exception {
    // Verify we've removed all FlowExcecutionList entries
    FlowExecutionList list = FlowExecutionList.get();
    for (FlowExecution fe : list) {
        if (fe == run.getExecution()) {
            Assert.fail("Run still has an execution in the list and should be removed!");
        }
    }
    Field f = list.getClass().getDeclaredField("runningTasks");
    f.setAccessible(true);
    CopyOnWriteList<FlowExecutionOwner> runningTasks = (CopyOnWriteList<FlowExecutionOwner>) (f.get(list));
    Assert.assertFalse(runningTasks.contains(run.asFlowExecutionOwner()));
}
Also used : FlowExecutionList(org.jenkinsci.plugins.workflow.flow.FlowExecutionList) Field(java.lang.reflect.Field) FlowExecutionOwner(org.jenkinsci.plugins.workflow.flow.FlowExecutionOwner) FlowExecution(org.jenkinsci.plugins.workflow.flow.FlowExecution) CopyOnWriteList(hudson.util.CopyOnWriteList)

Example 5 with FlowExecution

use of org.jenkinsci.plugins.workflow.flow.FlowExecution in project workflow-cps-plugin by jenkinsci.

the class FlowDurabilityTest method waitForBuildToResumeOrFail.

/**
 * Waits until the build to resume or die.
 */
static void waitForBuildToResumeOrFail(WorkflowRun run) throws Exception {
    CpsFlowExecution execution = (CpsFlowExecution) (run.getExecution());
    long nanoStartTime = System.nanoTime();
    while (true) {
        if (!run.isBuilding()) {
            return;
        }
        long currentTime = System.nanoTime();
        if (TimeUnit.SECONDS.convert(currentTime - nanoStartTime, TimeUnit.NANOSECONDS) > 10) {
            StringBuilder builder = new StringBuilder();
            builder.append("Run result: " + run.getResult());
            builder.append(" and execution != null:" + run.getExecution() != null + " ");
            FlowExecution exec = run.getExecution();
            if (exec instanceof CpsFlowExecution) {
                CpsFlowExecution cpsFlow = (CpsFlowExecution) exec;
                builder.append(", FlowExecution is paused: " + cpsFlow.isPaused()).append(", FlowExecution is complete: " + cpsFlow.isComplete()).append(", FlowExecution result: " + cpsFlow.getResult()).append(", FlowExecution PersistedClean: " + cpsFlow.persistedClean).append('\n');
            }
            throw new TimeoutException("Build didn't resume or fail in a timely fashion. " + builder.toString());
        }
        Thread.sleep(100L);
    }
}
Also used : FlowExecution(org.jenkinsci.plugins.workflow.flow.FlowExecution) TimeoutException(java.util.concurrent.TimeoutException)

Aggregations

FlowExecution (org.jenkinsci.plugins.workflow.flow.FlowExecution)28 WorkflowRun (org.jenkinsci.plugins.workflow.job.WorkflowRun)12 FlowNode (org.jenkinsci.plugins.workflow.graph.FlowNode)10 Test (org.junit.Test)9 IOException (java.io.IOException)7 ArrayList (java.util.ArrayList)7 Statement (org.junit.runners.model.Statement)7 Jenkins (jenkins.model.Jenkins)6 FlowExecutionOwner (org.jenkinsci.plugins.workflow.flow.FlowExecutionOwner)6 AbortException (hudson.AbortException)5 DepthFirstScanner (org.jenkinsci.plugins.workflow.graphanalysis.DepthFirstScanner)5 Action (hudson.model.Action)3 Link (io.jenkins.blueocean.rest.hal.Link)3 TimingAction (org.jenkinsci.plugins.workflow.actions.TimingAction)3 CpsFlowExecution (org.jenkinsci.plugins.workflow.cps.CpsFlowExecution)3 FlowInterruptedException (org.jenkinsci.plugins.workflow.steps.FlowInterruptedException)3 SuppressFBWarnings (edu.umd.cs.findbugs.annotations.SuppressFBWarnings)2 LineTransformationOutputStream (hudson.console.LineTransformationOutputStream)2 StreamBuildListener (hudson.model.StreamBuildListener)2 CopyOnWriteList (hudson.util.CopyOnWriteList)2