@Override public void evaluate() throws Throwable { WorkflowRun run = story.j.jenkins.getItemByFullName(jobName, WorkflowJob.class).getLastBuild(); assert run.isBuilding(); assert run.getResult() != Result.FAILURE; Thread.sleep(35000); // Step completes if (run.getExecution() instanceof CpsFlowExecution) { CpsFlowExecution exec = (CpsFlowExecution)run.getExecution(); assert exec.persistedClean == null; } } });
public static Pipeline resolve(WorkflowJob project, WorkflowRun build) throws PipelineException { String pipelineTimestamp = TimestampFormat.formatTimestamp(build.getTimeInMillis()); List<FlowNode> stageNodes = FlowNodeUtil.getStageNodes(build.getExecution()); return new Pipeline(project.getName(), build.getDisplayName(), Stage.extractStages(build, stageNodes), Change.getChanges(build.getChangeSets()), TriggerCause.getTriggeredBy(project, build), pipelineTimestamp); }
@Override public void onCompleted(WorkflowRun workflowRun, @Nonnull TaskListener listener) { super.onCompleted(workflowRun, listener); // Note: run.duration is zero in onCompleted(), do the substraction in this listener Result result = workflowRun.getResult(); if (result == null) { result = Result.SUCCESS; // FIXME more elegant handling } globalPipelineMavenConfig.getDao().updateBuildOnCompletion( workflowRun.getParent().getFullName(), workflowRun.getNumber(), result.ordinal, workflowRun.getStartTimeInMillis(), Math.max(System.currentTimeMillis() - workflowRun.getStartTimeInMillis(), 0)); // @see HUDSON-5844 } }
Owner(WorkflowRun run) { job = run.getParent().getFullName(); id = run.getId(); this.run = run; } private String key() {
@CheckForNull protected Result getExecutionResult(@Nonnull WorkflowRun r) { FlowExecution execution = r.getExecution(); if (execution instanceof CpsFlowExecution) { return ((CpsFlowExecution) execution).getResult(); } else { return r.getResult(); } }
@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()); } } },
@Issue("JENKINS-50880") @Test public void whenBeforeInputTrue() throws Exception { String whenFile = "whenBeforeInputTrue"; WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, whenFile); p.setDefinition(new CpsFlowDefinition(pipelineSourceFromResources(whenFile), true)); // get the build going, and wait until workflow pauses QueueTaskFuture<WorkflowRun> q = p.scheduleBuild2(0); WorkflowRun b = q.getStartCondition().get(); CpsFlowExecution e = (CpsFlowExecution) b.getExecutionPromise().get(); while (b.getAction(InputAction.class)==null) { e.waitForSuspension(); } // make sure we are pausing at the right state that reflects what we wrote in the program InputAction a = b.getAction(InputAction.class); assertEquals(1, a.getExecutions().size()); InputStepExecution is = a.getExecution("Simple-input"); assertEquals("Continue?", is.getInput().getMessage()); assertNull(is.getInput().getSubmitter()); JenkinsRule.WebClient wc = j.createWebClient(); HtmlPage page = wc.getPage(b, a.getUrlName()); j.submit(page.getFormByName(is.getId()), "proceed"); assertEquals(0, a.getExecutions().size()); q.get(); j.assertBuildStatusSuccess(j.waitForCompletion(b)); j.assertLogContains("X-SHOW-X", b); }
/** * Main entry point invoked by the setup module */ public int run(Bootstrap bootstrap) throws Exception { Jenkins j = Jenkins.getInstance(); WorkflowJob w = j.createProject(WorkflowJob.class, "job"); w.addProperty(new DurabilityHintJobProperty(FlowDurabilityHint.PERFORMANCE_OPTIMIZED)); w.setDefinition(new CpsScmFlowDefinition( new FileSystemSCM(bootstrap.jenkinsfile.getParent()), bootstrap.jenkinsfile.getName())); QueueTaskFuture<WorkflowRun> f = w.scheduleBuild2(0, new SetJenkinsfileLocation(bootstrap.jenkinsfile)); b = f.getStartCondition().get(); writeLogTo(System.out); f.get(); // wait for the completion return b.getResult().ordinal; }
if (!globalPipelineMavenConfig.getTriggerDownstreamBuildsResultsCriteria().contains(upstreamBuild.getResult())) { Map<String, List<MavenDependencyCause>> omittedPipelineFullNamesAndCauses = new HashMap<>(); for (Cause cause: upstreamBuild.getCauses()) { if (cause instanceof MavenDependencyCause) { MavenDependencyCause mavenDependencyCause = (MavenDependencyCause) cause; listener.getLogger().println("[withMaven] Skip triggering downstream jobs for upstream build with ignored result status " + upstreamBuild + ": " + upstreamBuild.getResult()); } else { listener.getLogger().println("[withMaven] downstreamPipelineTriggerRunListener - Triggering downstream pipeline " + ModelHyperlinkNote.encodeTo(omittedPipeline) + " despite build result " + upstreamBuild.getResult() + " for the upstream causes: " + omittedPipelineTriggerCauses.stream().map(c -> c.getShortDescription()).collect(Collectors.joining(", "))); WorkflowJob upstreamPipeline = upstreamBuild.getParent(); String upstreamPipelineFullName = upstreamPipeline.getFullName(); int upstreamBuildNumber = upstreamBuild.getNumber(); Map<MavenArtifact, SortedSet<String>> downstreamPipelinesByArtifact = globalPipelineMavenConfig.getDao().listDownstreamJobsByArtifact(upstreamPipelineFullName, upstreamBuildNumber); final WorkflowJob downstreamPipeline = Jenkins.getInstance().getItemByFullName(downstreamPipelineFullName, WorkflowJob.class); if (downstreamPipeline == null || downstreamPipeline.getLastBuild() == null) { LOGGER.log(Level.FINE, "Downstream pipeline {0} or downstream pipeline last build not found from upstream build {1}. Database synchronization issue or security restriction?", new Object[]{downstreamPipelineFullName, upstreamBuild.getFullDisplayName(), Jenkins.getAuthentication()}); continue; int downstreamBuildNumber = downstreamPipeline.getLastBuild().getNumber(); if (!downstreamPipeline.isBuildable()) { LOGGER.log(Level.FINE, "Skip triggering of non buildable (disabled: {0}, isHoldOffBuildUntilSave: {1}) downstream pipeline {2} from upstream build {3}", new Object[]{downstreamPipeline.isDisabled(), downstreamPipeline.isHoldOffBuildUntilSave(), downstreamPipeline.getFullName(), upstreamBuild.getFullDisplayName()});
static WorkflowRun createAndRunSleeperJob(Jenkins jenkins, String jobName, FlowDurabilityHint durabilityHint) throws Exception { Item prev = jenkins.getItemByFullName(jobName); if (prev != null) { prev.delete(); } WorkflowJob job = jenkins.createProject(WorkflowJob.class, jobName); CpsFlowDefinition def = new CpsFlowDefinition("node {\n " + "sleep 30 \n" + "} \n" + "echo 'I like cheese'\n", false); TestDurabilityHintProvider provider = Jenkins.get().getExtensionList(TestDurabilityHintProvider.class).get(0); provider.registerHint(jobName, durabilityHint); job.setDefinition(def); WorkflowRun run = job.scheduleBuild2(0).getStartCondition().get(); Thread.sleep(4000L); // Hacky but we just need to ensure this can start up Assert.assertFalse(run.getExecution().isComplete()); Assert.assertFalse(((CpsFlowExecution)(run.getExecution())).done); Assert.assertEquals(durabilityHint, run.getExecution().getDurabilityHint()); Assert.assertEquals("sleep", run.getExecution().getCurrentHeads().get(0).getDisplayFunctionName()); return run; }
MercurialInstallation installation = new MercurialInstallation(instName, "", "hg", false, true, false, null, null); LogTaskListener listener = new LogTaskListener(Logger.getLogger(getClass().getName()), Level.INFO); final HgExe hg = new HgExe(installation, null, r.jenkins.createLauncher( listener), r.jenkins, listener, new EnvVars()); String version; sampleRepo.child("file").write("initial content", null); m.hg(sampleRepo, "commit", "--addremove", "--message=flow"); WorkflowMultiBranchProject mp = r.jenkins.createProject(WorkflowMultiBranchProject.class, "p"); r.jenkins.getDescriptorByType(MercurialInstallation.DescriptorImpl.class).setInstallations(installation); installation.forNode(r.jenkins, StreamTaskListener.fromStdout()); mp.getSourcesList().add(new BranchSource(new MercurialSCMSource(null, instName, sampleRepo.toURI().toString(), null, null, null, null, null, true))); WorkflowJob p = scheduleAndFindBranchProject(mp, "default"); r.waitUntilNoActivity(); WorkflowRun b1 = p.getLastBuild(); assertNotNull(b1); assertEquals(1, b1.getNumber()); r.waitUntilNoActivity(); WorkflowRun b2 = p.getLastBuild(); assertEquals(2, b2.getNumber()); r.assertLogContains("initial content", r.assertBuildStatusSuccess(b1)); r.assertLogContains("SUBSEQUENT CONTENT", r.assertBuildStatusSuccess(b2)); List<ChangeLogSet<? extends ChangeLogSet.Entry>> changeSets = b2.getChangeSets();
WorkflowJob job = jenkins.getItemByFullName(jobName, WorkflowJob.class); if (job == null) { // Job may already have been created job = jenkins.createProject(WorkflowJob.class, jobName); job.addProperty(new DurabilityHintJobProperty(hint)); job.setDefinition(new CpsFlowDefinition( "echo 'first'\n" + "def steps = [:]\n" + story.j.buildAndAssertSuccess(job); long millisDuration = job.getLastBuild().getDuration(); System.out.println("Test fuzzer job in completed in "+millisDuration+" ms"); WorkflowRun run = job.scheduleBuild2(0).getStartCondition().get(); run.getExecutionPromise().get(); // Ensures run has begun so that it *can* complete cleanly. Thread.sleep(time); return run;
@Override public void evaluate() throws Throwable { WorkflowJob p = story.j.jenkins.getItemByFullName("p", WorkflowJob.class); WorkflowRun b3 = p.getLastBuild(); assertEquals(3, b3.getNumber()); // Resume #3, and verify that the build completes with the expected replacements. SemaphoreStep.success("wait/3", null); story.j.waitForCompletion(b3); story.j.assertLogNotContains("trying edits", b3); story.j.assertLogContains("new first part", b3); story.j.assertLogContains("newer second part", b3); } });
m.hg(sampleRepo, "commit", "--message=unrelated branch, not buildable"); m.hg(sampleRepo, "update", "default"); WorkflowMultiBranchProject mp = r.jenkins.createProject(WorkflowMultiBranchProject.class, "p"); String instName = "caching"; r.jenkins.getDescriptorByType(MercurialInstallation.DescriptorImpl.class).setInstallations( new MercurialInstallation(instName, "", "hg", false, true, false, null, null)); mp.getSourcesList().add(new BranchSource(new MercurialSCMSource(null, instName, sampleRepo.toURI().toString(), null, null, null, null, null, true))); assertEquals(1, mp.getItems().size()); SemaphoreStep.waitForStart("wait/1", null); WorkflowRun b1 = p.getLastBuild(); assertNotNull(b1); assertEquals(1, b1.getNumber()); sampleRepo.child("Jenkinsfile").write("node {checkout scm; echo readFile('file').toUpperCase()}", null); sampleRepo.child("file").write("subsequent content", null); m.notifyCommit(sampleRepo); showIndexing(mp); WorkflowRun b2 = p.getLastBuild(); assertEquals(2, b2.getNumber()); r.assertLogContains("initial content", r.assertBuildStatusSuccess(b1)); r.assertLogContains("SUBSEQUENT CONTENT", r.assertBuildStatusSuccess(b2)); List<ChangeLogSet<? extends ChangeLogSet.Entry>> changeSets = b2.getChangeSets();
@Issue("JENKINS-44149") @Test public void propsRemoved() throws Exception { WorkflowRun b = getAndStartNonRepoBuild("simpleJobProperties"); j.assertBuildStatusSuccess(j.waitForCompletion(b)); WorkflowJob job = b.getParent(); assertNotNull(job.getProperty(BuildDiscarderProperty.class)); job.setDefinition(new CpsFlowDefinition(pipelineSourceFromResources("propsTriggersParamsRemoved"), true)); j.buildAndAssertSuccess(job); assertNull(job.getProperty(BuildDiscarderProperty.class)); }
@Override public void evaluate() throws Throwable { WorkflowJob p = story.j.jenkins.createProject(WorkflowJob.class, "p"); p.addProperty(new ParametersDefinitionProperty(new StringParameterDefinition("param", ""))); p.setDefinition(new CpsFlowDefinition("echo \"run with ${param}\"", true)); WorkflowRun b1 = story.j.assertBuildStatusSuccess(p.scheduleBuild2(0, new ParametersAction(new StringParameterValue("param", "some value")))); story.j.assertLogContains("run with some value", b1); // When we replay a parameterized build, we expect the original parameter values to be set. WorkflowRun b2 = (WorkflowRun) b1.getAction(ReplayAction.class).run("echo \"run again with ${param}\"", Collections.<String,String>emptyMap()).get(); story.j.assertLogContains("run again with some value", story.j.assertBuildStatusSuccess(b2)); } });
WorkflowRun original = p.getLastSuccessfulBuild(); assertNotNull(original); sampleRepo.git("commit", "--message=tada"); WorkflowRun failing = p.scheduleBuild2(0).waitForStart(); j.assertBuildStatus(Result.FAILURE, j.waitForCompletion(failing)); assertNotNull(failing.getChangeSets()); assertFalse(failing.getChangeSets().isEmpty()); assertEquals(1, failing.getChangeSets().size()); ChangeLogSet<? extends ChangeLogSet.Entry> failingChanges = failing.getChangeSets().get(0); assertEquals(1, failingChanges.getItems().length); ChangeLogSet.Entry failingEntry = failingChanges.iterator().next(); assertEquals(p.getAbsoluteUrl(), redirect.getUrl().toString()); j.waitUntilNoActivity(); j.assertLogNotContains("This shouldn't show up on third run", b3); assertNotNull(b3.getChangeSets()); assertFalse(b3.getChangeSets().isEmpty()); assertEquals(1, b3.getChangeSets().size()); ChangeLogSet<? extends ChangeLogSet.Entry> b3Changes = failing.getChangeSets().get(0); assertEquals(1, b3Changes.getItems().length); ChangeLogSet.Entry b3Entry = b3Changes.iterator().next();
" archive '**'\n" + "}")); WorkflowRun b = r.assertBuildStatusSuccess(p.scheduleBuild2(0)); VirtualFile artifacts = b.getArtifactManager().root(); assertTrue(artifacts.child("main/file").isFile()); assertTrue(artifacts.child("other/otherfile").isFile()); r.assertLogContains("unversioned did not exist", b); m.touchAndCommit(sampleRepo, "file2"); m.touchAndCommit(otherRepo, "otherfile2"); m.notifyCommit(otherRepo); FileUtils.copyFile(p.getSCMTrigger().getLogFile(), System.out); b = r.assertBuildStatusSuccess(p.getLastBuild()); assertEquals(2, b.number); artifacts = b.getArtifactManager().root(); assertTrue(artifacts.child("main/file2").isFile()); assertTrue(artifacts.child("other/otherfile2").isFile()); assertEquals(otherRepo.toURI().toString(), ((MercurialSCM) scms.next()).getSource()); assertFalse(scms.hasNext()); List<ChangeLogSet<? extends ChangeLogSet.Entry>> changeSets = b.getChangeSets(); assertEquals(2, changeSets.size()); ChangeLogSet<? extends ChangeLogSet.Entry> changeSet = changeSets.get(0);
@Test public void stop() throws Exception { WorkflowJob p = r.createProject(WorkflowJob.class, "p"); p.setDefinition(new CpsFlowDefinition("unkillable()", true)); final WorkflowRun b = p.scheduleBuild2(0).waitForStart(); r.waitForMessage("unkillable", b); try (ACLContext context = ACL.as(Jenkins.ANONYMOUS)) { b.getExecutor().interrupt(); }; r.waitForCompletion(b); r.assertBuildStatus(Result.ABORTED, b); InterruptedBuildAction iba = b.getAction(InterruptedBuildAction.class); assertNotNull(iba); List<CauseOfInterruption> causes = iba.getCauses(); assertEquals(1, causes.size()); assertEquals(CauseOfInterruption.UserInterruption.class, causes.get(0).getClass()); r.waitForMessage("Finished: ABORTED", b); // TODO JENKINS-46076 WorkflowRun.isBuilding() can go to false before .finish has completed r.assertLogContains("never going to stop", b); r.assertLogNotContains("\tat ", b); }
@Override public void evaluate() throws Throwable { WorkflowJob p = story.j.jenkins.createProject(WorkflowJob.class, "p"); // As in loadStep, will set up a main and auxiliary script. FilePath f = story.j.jenkins.getWorkspaceFor(p).child("f.groovy"); f.write("'original text'", null); p.setDefinition(new CpsFlowDefinition("node {def t = load 'f.groovy'; echo \"got ${t}\"}", true)); WorkflowRun b1 = story.j.assertBuildStatusSuccess(p.scheduleBuild2(0)); story.j.assertLogContains("got original text", b1); // s/got/received/ on main script assertEquals(0, new CLICommandInvoker(story.j, "replay-pipeline").withStdin(IOUtils.toInputStream("node {def t = load 'f.groovy'; echo \"received ${t}\"}")).invokeWithArgs("p").returnCode()); story.j.waitUntilNoActivity(); WorkflowRun b2 = p.getLastBuild(); assertEquals(2, b2.getNumber()); story.j.assertLogContains("received original text", b2); // s/original/new/ on auxiliary script, and explicitly asking to replay #1 rather than the latest assertEquals(0, new CLICommandInvoker(story.j, "replay-pipeline").withStdin(IOUtils.toInputStream("'new text'")).invokeWithArgs("p", "-n", "1", "-s", "Script1").returnCode()); story.j.waitUntilNoActivity(); WorkflowRun b3 = p.getLastBuild(); assertEquals(3, b3.getNumber()); // Main script picked up from #1, not #2. story.j.assertLogContains("got new text", b3); } });