hudson.model.queue.QueueTaskFuture Java Examples

The following examples show how to use hudson.model.queue.QueueTaskFuture. 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: AbstractPipelineTestProject.java    From aws-codecommit-trigger-plugin with Apache License 2.0 6 votes vote down vote up
protected void subscribeProject(ProjectFixture fixture) throws Exception {
    String name = UUID.randomUUID().toString();
    WorkflowJob job = jenkinsRule.getInstance().createProject(WorkflowJob.class, name);

    String script = fixture.getPipelineScript().replace("${EmitEvent}", AbstractPipelineTestProject.class.getName() + ".emitBuildEvent()");
    CpsFlowDefinition flowDefinition = new CpsFlowDefinition(script, true);
    job.setDefinition(flowDefinition);

    QueueTaskFuture<WorkflowRun> run = job.scheduleBuild2(0);
    WorkflowRun wfRun = run.get();
    Assertions.assertThat(wfRun.getResult())
        .describedAs("Pipeline unable to start succeed")
        .isEqualTo(Result.SUCCESS);
    jenkinsRule.assertBuildStatusSuccess(wfRun);

    resetPipelineBuildEvent(fixture);

    if (!fixture.isHasTrigger()) {
        return;
    }

    final String uuid = this.sqsQueue.getUuid();
    SQSTrigger trigger = new SQSTrigger(uuid, fixture.isSubscribeInternalScm(), fixture.getScmConfigs());
    job.addTrigger(trigger);
    trigger.start(job, false);
}
 
Example #2
Source File: DockerComputerConnectorTest.java    From docker-plugin with MIT License 6 votes vote down vote up
protected void should_connect_agent(DockerTemplate template) throws IOException, ExecutionException, InterruptedException, TimeoutException {

        // FIXME on CI windows nodes don't have Docker4Windows
        Assume.assumeFalse(SystemUtils.IS_OS_WINDOWS);

        String dockerHost = SystemUtils.IS_OS_WINDOWS ? "tcp://localhost:2375" : "unix:///var/run/docker.sock";

        DockerCloud cloud = new DockerCloud(cloudName, new DockerAPI(new DockerServerEndpoint(dockerHost, null)),
                Collections.singletonList(template));

        j.jenkins.clouds.replaceBy(Collections.singleton(cloud));

        final FreeStyleProject project = j.createFreeStyleProject("test-docker-ssh");
        project.setAssignedLabel(Label.get(LABEL));
        project.getBuildersList().add(new Shell("whoami"));
        final QueueTaskFuture<FreeStyleBuild> scheduledBuild = project.scheduleBuild2(0);
        try {
            final FreeStyleBuild build = scheduledBuild.get(60L, TimeUnit.SECONDS);
            Assert.assertTrue(build.getResult() == Result.SUCCESS);
            Assert.assertTrue(build.getLog().contains("jenkins"));
        } finally {
            scheduledBuild.cancel(true);
        }
    }
 
Example #3
Source File: MattermostSendStepIntegrationTest.java    From jenkins-mattermost-plugin with MIT License 6 votes vote down vote up
@Test
  public void test_fail_on_error() throws Exception {
    WorkflowJob job = jenkinsRule.jenkins.createProject(WorkflowJob.class, "workflow");
    // just define message
	  job.setDefinition(
			  new CpsFlowDefinition(
					  "mattermostSend(message: 'message', endpoint: 'endpoint', icon: 'icon', channel: '#channel', color: 'good', failOnError: true);",
					  true));
	  //noinspection ConstantConditions
	  //job.scheduleBuild(0,new Cause.UserIdCause());
	  QueueTaskFuture<WorkflowRun> workflowRunQueueTaskFuture = job.scheduleBuild2(0);
	  //WorkflowRun workflowRun = workflowRunQueueTaskFuture.getStartCondition().get();
	  //workflowRun.getExecutionPromise().get();
	  WorkflowRun run = jenkinsRule.assertBuildStatus(Result.FAILURE, workflowRunQueueTaskFuture);
	  //jenkinsRule.assertBuildStatusSuccess(workflowRun);
	  // everything should come from step configuration
//	  String log = JenkinsRule.getLog(run);
//	  Assert.assertTrue(log.contains("Warn"));
	  //TODO jenkinsRule.assertLogContains(
	  //   "Mattermost notification failed. See Jenkins logs for details.", run);
  }
 
Example #4
Source File: DockerSimpleBuildWrapperTest.java    From yet-another-docker-plugin with MIT License 6 votes vote down vote up
@Ignore("For local experiments")
@Test
public void testWrapper() throws Exception {
    final FreeStyleProject project = jRule.createProject(FreeStyleProject.class, "freestyle");

    final DockerConnector connector = new DockerConnector("tcp://" + ADDRESS + ":2376/");
    connector.setConnectorType(JERSEY);

    final DockerSlaveConfig config = new DockerSlaveConfig();
    config.getDockerContainerLifecycle().setImage("java:8-jdk-alpine");
    config.setLauncher(new NoOpDelegatingComputerLauncher(new DockerComputerSingleJNLPLauncher()));
    config.setRetentionStrategy(new DockerOnceRetentionStrategy(10));

    final DockerSimpleBuildWrapper dockerSimpleBuildWrapper = new DockerSimpleBuildWrapper(connector, config);
    project.getBuildWrappersList().add(dockerSimpleBuildWrapper);
    project.getBuildersList().add(new Shell("sleep 30"));

    final QueueTaskFuture<FreeStyleBuild> taskFuture = project.scheduleBuild2(0);

    jRule.waitUntilNoActivity();
    jRule.pause();
}
 
Example #5
Source File: AWSDeviceFarmRecorderTest.java    From aws-device-farm-jenkins-plugin with Apache License 2.0 5 votes vote down vote up
@Test
@Issue("JENKINS-50483")
public void dataSerializationSmokeTest() throws Exception {
    FreeStyleProject p = j.createFreeStyleProject();
    AWSDeviceFarmRecorder rec = new AWSDeviceFarmRecorder(
            "TestProjectName", "TestDevicePool", null, null,
            null, null, "APPIUM_JAVA_JUNIT", false, false, null,
            null, null, null, null, null, null,
            null, null, null, null, null, null, null, null,
            null, null, null, null, null, null,
            null, null, null, null, false, false,
            null, null, null, null, null, null,
            false, false, false, 10, false, false,
            false, false, false, null
    );
    p.getPublishersList().add(rec);

    // Try to build it. It is not supposed to work, but we will filter out the JEP-200 exception
    final QueueTaskFuture<FreeStyleBuild> future = p.scheduleBuild2(0);
    final FreeStyleBuild build = future.get();
    j.assertBuildStatus(Result.FAILURE, build);
    // Currently it fails with Either IAM Role ARN or AKID/SKID must be set and does not report the serialization issue after that

    // No matter what, we should be able to save the project even after the failure
    p.save();
    build.save();
}
 
Example #6
Source File: ProvisionIntegrationTest.java    From ec2-spot-jenkins-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void should_not_convert_planned_to_node_if_state_is_not_running_and_check_state_enabled() throws Exception {
    ComputerLauncher computerLauncher = mock(ComputerLauncher.class);
    ComputerConnector computerConnector = mock(ComputerConnector.class);
    when(computerConnector.launch(anyString(), any(TaskListener.class))).thenReturn(computerLauncher);

    EC2FleetCloud cloud = new EC2FleetCloud(null, null, "credId", null, "region",
            null, "fId", "momo", null, computerConnector, false, false,
            0, 0, 10, 1, true, false,
            false, 0, 0, false,
            2, false);
    j.jenkins.clouds.add(cloud);

    mockEc2ApiToDescribeInstancesWhenModified(InstanceStateName.Pending);

    List<QueueTaskFuture> rs = getQueueTaskFutures(1);

    triggerSuggestReviewNow("momo");

    Assert.assertEquals(0, j.jenkins.getNodes().size());

    tryUntil(new Runnable() {
        @Override
        public void run() {
            Assert.assertEquals(ImmutableSet.of("master", "momo"), labelsToNames(j.jenkins.getLabels()));
            Assert.assertEquals(1, j.jenkins.getLabelAtom("momo").nodeProvisioner.getPendingLaunches().size());
            Assert.assertEquals(0, j.jenkins.getNodes().size());
        }
    });

    cancelTasks(rs);
}
 
Example #7
Source File: JenkinsRule.java    From jenkins-test-harness with MIT License 5 votes vote down vote up
/**
 * Runs specified job and asserts that in finished with given build result.
 * @since TODO
 */
@Nonnull
public <J extends Job<J,R> & ParameterizedJobMixIn.ParameterizedJob<J,R>,R extends Run<J,R> & Queue.Executable> R buildAndAssertStatus(@Nonnull Result status, @Nonnull J job) throws Exception {
    final QueueTaskFuture<R> f = new ParameterizedJobMixIn<J, R>() {
        @Override protected J asJob() {
            return job;
        }
    }.scheduleBuild2(0);
    return assertBuildStatus(status, f);
}
 
Example #8
Source File: GitHubPRRepository.java    From github-integration-plugin with MIT License 5 votes vote down vote up
@Override
public FormValidation doBuild(StaplerRequest req) throws IOException {
    FormValidation result;

    try {
        if (!job.hasPermission(Item.BUILD)) {
            return FormValidation.error("Forbidden");
        }

        final String prNumberParam = "prNumber";
        int prId = 0;
        if (req.hasParameter(prNumberParam)) {
            prId = Integer.valueOf(req.getParameter(prNumberParam));
        }

        if (prId == 0 || !getPulls().containsKey(prId)) {
            return FormValidation.error("No branch to build");
        }

        final GitHubPRPullRequest localPR = getPulls().get(prId);
        final GitHubPRCause cause = new GitHubPRCause(localPR, null, this, false, "Manual run.");

        final JobRunnerForCause runner = new JobRunnerForCause(getJob(), ghPRTriggerFromJob(getJob()));
        final QueueTaskFuture<?> queueTaskFuture = runner.startJob(cause);

        if (nonNull(queueTaskFuture)) {
            result = FormValidation.ok("Build scheduled");
        } else {
            result = FormValidation.warning("Build not scheduled");
        }
    } catch (Exception e) {
        LOG.error("Can't start build", e.getMessage());
        result = FormValidation.error(e, "Can't start build: " + e.getMessage());
    }

    return result;
}
 
Example #9
Source File: JobHelper.java    From github-integration-plugin with MIT License 5 votes vote down vote up
public static boolean rebuild(Run<?, ?> run) {
    final QueueTaskFuture queueTaskFuture = asParameterizedJobMixIn(run.getParent())
            .scheduleBuild2(
                    0,
                    run.getAction(ParametersAction.class),
                    run.getAction(CauseAction.class),
                    run.getAction(BuildBadgeAction.class)
            );
    return queueTaskFuture != null;
}
 
Example #10
Source File: GitHubBranchRepository.java    From github-integration-plugin with MIT License 5 votes vote down vote up
@RequirePOST
public FormValidation doBuild(StaplerRequest req) throws IOException {
    FormValidation result;

    try {
        if (!job.hasPermission(Item.BUILD)) {
            return FormValidation.error("Forbidden");
        }

        final String param = "branchName";
        String branchName = null;
        if (req.hasParameter(param)) {
            branchName = req.getParameter(param);
        }
        if (isNull(branchName) || !getBranches().containsKey(branchName)) {
            return FormValidation.error("No branch to build");
        }

        final GitHubBranch localBranch = getBranches().get(branchName);
        final GitHubBranchCause cause = new GitHubBranchCause(localBranch, this, "Manual run.", false);
        final JobRunnerForBranchCause runner = new JobRunnerForBranchCause(getJob(),
                ghBranchTriggerFromJob(job));
        final QueueTaskFuture<?> queueTaskFuture = runner.startJob(cause);

        if (nonNull(queueTaskFuture)) {
            result = FormValidation.ok("Build scheduled");
        } else {
            result = FormValidation.warning("Build not scheduled");
        }
    } catch (Exception e) {
        LOG.error("Can't start build", e.getMessage());
        result = FormValidation.error(e, "Can't start build: " + e.getMessage());
    }

    return result;
}
 
Example #11
Source File: JobRunnerForBranchCause.java    From github-integration-plugin with MIT License 5 votes vote down vote up
@Override
public boolean apply(GitHubBranchCause cause) {
    try {
        cause.setPollingLogFile(trigger.getPollingLogAction().getPollingLogFile());

        StringBuilder sb = new StringBuilder();
        sb.append("Jenkins queued the run (").append(cause.getReason()).append(")");

        if (trigger.isCancelQueued() && cancelQueuedBuildByBranchName(cause.getBranchName())) {
            sb.append(". Queued builds aborted");
        }

        QueueTaskFuture<?> queueTaskFuture = startJob(cause);
        if (isNull(queueTaskFuture)) {
            LOGGER.error("{} job didn't start", job.getFullName());
        }

        LOGGER.info(sb.toString());

        // remote connection
        if (trigger.isPreStatus()) {
            trigger.getRemoteRepository()
                    .createCommitStatus(cause.getCommitSha(),
                            GHCommitState.PENDING,
                            null,
                            sb.toString(),
                            job.getFullName());
        }
    } catch (IOException e) {
        LOGGER.error("Can't trigger build ({})", e.getMessage(), e);
        return false;
    }
    return true;
}
 
Example #12
Source File: JobRunnerForCauseTest.java    From github-integration-plugin with MIT License 5 votes vote down vote up
public static QueueTaskFuture schedule(Job<?, ?> job, int number, String param, int queuetPeriod) {
    ParameterizedJobMixIn jobMixIn = JobInfoHelpers.asParameterizedJobMixIn(job);
    GitHubPRCause cause = newGitHubPRCause().withNumber(number);
    ParametersAction parametersAction = new ParametersAction(
            Collections.<ParameterValue>singletonList(new StringParameterValue("value", param))
    );
    return jobMixIn.scheduleBuild2(queuetPeriod, new CauseAction(cause), parametersAction);
}
 
Example #13
Source File: DollarSecretPatternFactoryTest.java    From credentials-binding-plugin with MIT License 5 votes vote down vote up
@Issue("JENKINS-24805")
@Test
public void maskingFreeStyleSecrets() throws Exception {
    String firstCredentialsId = "creds_1";
    String firstPassword = "a$build";
    StringCredentialsImpl firstCreds = new StringCredentialsImpl(CredentialsScope.GLOBAL, firstCredentialsId, "sample1", Secret.fromString(firstPassword));

    CredentialsProvider.lookupStores(r.jenkins).iterator().next().addCredentials(Domain.global(), firstCreds);

    String secondCredentialsId = "creds_2";
    String secondPassword = "a$$b";
    StringCredentialsImpl secondCreds = new StringCredentialsImpl(CredentialsScope.GLOBAL, secondCredentialsId, "sample2", Secret.fromString(secondPassword));

    CredentialsProvider.lookupStores(r.jenkins).iterator().next().addCredentials(Domain.global(), secondCreds);

    SecretBuildWrapper wrapper = new SecretBuildWrapper(Arrays.asList(new StringBinding("PASS_1", firstCredentialsId),
            new StringBinding("PASS_2", secondCredentialsId)));

    FreeStyleProject project = r.createFreeStyleProject();

    project.setConcurrentBuild(true);
    project.getBuildersList().add(Functions.isWindows() ? new BatchFile("echo %PASS_1%") : new Shell("echo \"$PASS_1\""));
    project.getBuildersList().add(Functions.isWindows() ? new BatchFile("echo %PASS_2%") : new Shell("echo \"$PASS_2\""));
    project.getBuildersList().add(new Maven("$PASS_1 $PASS_2", "default"));
    project.getBuildWrappersList().add(wrapper);

    r.configRoundtrip((Item)project);

    QueueTaskFuture<FreeStyleBuild> future = project.scheduleBuild2(0);
    FreeStyleBuild build = future.get();
    r.assertLogNotContains(firstPassword, build);
    r.assertLogNotContains(firstPassword.replace("$", "$$"), build);
    r.assertLogNotContains(secondPassword, build);
    r.assertLogNotContains(secondPassword.replace("$", "$$"), build);
    r.assertLogContains("****", build);
}
 
Example #14
Source File: BuildPageRedirectActionTest.java    From gitlab-plugin with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void redirectToBuildUrl() throws IOException, ExecutionException, InterruptedException, TimeoutException {
    FreeStyleProject testProject = jenkins.createFreeStyleProject();
    testProject.setScm(new GitSCM(gitRepoUrl));
    testProject.setQuietPeriod(0);
    QueueTaskFuture<FreeStyleBuild> future = testProject.scheduleBuild2(0);
    FreeStyleBuild build = future.get(15, TimeUnit.SECONDS);

    getBuildPageRedirectAction(testProject).execute(response);

    verify(response).sendRedirect2(jenkins.getInstance().getRootUrl() + build.getUrl());
}
 
Example #15
Source File: BuildPageRedirectActionTest.java    From gitlab-plugin with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void redirectToBuildStatusUrl() throws IOException, ExecutionException, InterruptedException, TimeoutException {
    FreeStyleProject testProject = jenkins.createFreeStyleProject();
    testProject.setScm(new GitSCM(gitRepoUrl));
    testProject.setQuietPeriod(0);
    QueueTaskFuture<FreeStyleBuild> future = testProject.scheduleBuild2(0);
    FreeStyleBuild build = future.get(15, TimeUnit.SECONDS);

    doThrow(IOException.class).when(response).sendRedirect2(jenkins.getInstance().getRootUrl() + build.getUrl());
    getBuildPageRedirectAction(testProject).execute(response);

    verify(response).sendRedirect2(jenkins.getInstance().getRootUrl() + build.getBuildStatusUrl());
}
 
Example #16
Source File: NoteBuildActionTest.java    From gitlab-plugin with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void build_alreadyBuiltMR_alreadyBuiltMR() throws IOException, ExecutionException, InterruptedException {
    FreeStyleProject testProject = jenkins.createFreeStyleProject();
    testProject.addTrigger(trigger);
    testProject.setScm(new GitSCM(gitRepoUrl));
    QueueTaskFuture<?> future = testProject.scheduleBuild2(0, new ParametersAction(new StringParameterValue("gitlabTargetBranch", "master")));
    future.get();

    exception.expect(HttpResponses.HttpResponseException.class);
    new NoteBuildAction(testProject, getJson("NoteEvent_alreadyBuiltMR.json"), null).execute(response);

    verify(trigger).onPost(any(NoteHook.class));
}
 
Example #17
Source File: NoteBuildActionTest.java    From gitlab-plugin with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void build_alreadyBuiltMR_differentTargetBranch() throws IOException, ExecutionException, InterruptedException {
    FreeStyleProject testProject = jenkins.createFreeStyleProject();
    testProject.addTrigger(trigger);
    testProject.setScm(new GitSCM(gitRepoUrl));
    QueueTaskFuture<?> future = testProject.scheduleBuild2(0, new GitLabWebHookCause(causeData()
            .withActionType(CauseData.ActionType.NOTE)
            .withSourceProjectId(1)
            .withTargetProjectId(1)
            .withBranch("feature")
            .withSourceBranch("feature")
            .withUserName("")
            .withSourceRepoHomepage("https://gitlab.org/test")
            .withSourceRepoName("test")
            .withSourceNamespace("test-namespace")
            .withSourceRepoUrl("[email protected]:test.git")
            .withSourceRepoSshUrl("[email protected]:test.git")
            .withSourceRepoHttpUrl("https://gitlab.org/test.git")
            .withMergeRequestTitle("Test")
            .withMergeRequestId(1)
            .withMergeRequestIid(1)
            .withTargetBranch("master")
            .withTargetRepoName("test")
            .withTargetNamespace("test-namespace")
            .withTargetRepoSshUrl("[email protected]:test.git")
            .withTargetRepoHttpUrl("https://gitlab.org/test.git")
            .withTriggeredByUser("test")
            .withLastCommit("123")
            .withTargetProjectUrl("https://gitlab.org/test")
            .build()));
    future.get();

    exception.expect(HttpResponses.HttpResponseException.class);
    new NoteBuildAction(testProject, getJson("NoteEvent_alreadyBuiltMR.json"), null).execute(response);

    verify(trigger).onPost(any(NoteHook.class));
}
 
Example #18
Source File: MergeRequestBuildActionTest.java    From gitlab-plugin with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void build_acceptedMr() throws IOException, ExecutionException, InterruptedException {
    FreeStyleProject testProject = jenkins.createFreeStyleProject();
    trigger.setTriggerOnAcceptedMergeRequest(true);
    trigger.setTriggerOnMergeRequest(false);
    testProject.addTrigger(trigger);
    testProject.setScm(new GitSCM(gitRepoUrl));
    QueueTaskFuture<?> future = testProject.scheduleBuild2(0, new ParametersAction(new StringParameterValue("gitlabTargetBranch", "master")));
    future.get();

    executeMergeRequestAction(testProject, getJson("MergeRequestEvent_merged.json"));
    assertTrue(wouldFire);
}
 
Example #19
Source File: MergeRequestBuildActionTest.java    From gitlab-plugin with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void build_alreadyBuiltMR_differentTargetBranch() throws IOException, ExecutionException, InterruptedException {
    FreeStyleProject testProject = jenkins.createFreeStyleProject();
    testProject.addTrigger(trigger);
    testProject.setScm(new GitSCM(gitRepoUrl));
    QueueTaskFuture<?> future = testProject.scheduleBuild2(0, new GitLabWebHookCause(causeData()
            .withActionType(CauseData.ActionType.MERGE)
            .withSourceProjectId(1)
            .withTargetProjectId(1)
            .withBranch("feature")
            .withSourceBranch("feature")
            .withUserName("")
            .withSourceRepoHomepage("https://gitlab.org/test")
            .withSourceRepoName("test")
            .withSourceNamespace("test-namespace")
            .withSourceRepoUrl("[email protected]:test.git")
            .withSourceRepoSshUrl("[email protected]:test.git")
            .withSourceRepoHttpUrl("https://gitlab.org/test.git")
            .withMergeRequestTitle("Test")
            .withMergeRequestId(1)
            .withMergeRequestIid(1)
            .withTargetBranch("master")
            .withTargetRepoName("test")
            .withTargetNamespace("test-namespace")
            .withTargetRepoSshUrl("[email protected]:test.git")
            .withTargetRepoHttpUrl("https://gitlab.org/test.git")
            .withTriggeredByUser("test")
            .withLastCommit("123")
            .withTargetProjectUrl("https://gitlab.org/test")
            .build()));
    future.get();

    executeMergeRequestAction(testProject, getJson("MergeRequestEvent_alreadyBuiltMR_differentTargetBranch.json"));

    assertTrue(wouldFire);
}
 
Example #20
Source File: JobsTest.java    From jenkins-client-java with MIT License 5 votes vote down vote up
@Test
public void getBuildDetails() throws Exception
{

    FreeStyleProject project = j.createFreeStyleProject();
    QueueTaskFuture<FreeStyleBuild> build = project.scheduleBuild2(0);
    assertNotNull(build);
    build.waitForStart();
    j.waitForCompletion(build.get());

    BuildDetail buildDetails = jobs.getBuildDetails(project.getName(), 1);
    assertNotNull(buildDetails);
}
 
Example #21
Source File: ProvisionIntegrationTest.java    From ec2-spot-jenkins-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void should_keep_planned_node_until_node_will_not_be_online_so_jenkins_will_not_request_overprovision() throws Exception {
    ComputerLauncher computerLauncher = mock(ComputerLauncher.class);
    ComputerConnector computerConnector = mock(ComputerConnector.class);
    when(computerConnector.launch(anyString(), any(TaskListener.class))).thenReturn(computerLauncher);

    EC2FleetCloud cloud = spy(new EC2FleetCloud(null, null, "credId", null, "region",
            null, "fId", "momo", null, computerConnector, false, false,
            0, 0, 10, 1, false, false,
            false, 300, 15, false,
            2, false));

    // provide init state
    cloud.setStats(new FleetStateStats("", 0, "active",
            Collections.<String>emptySet(), Collections.<String, Double>emptyMap()));

    j.jenkins.clouds.add(cloud);

    mockEc2ApiToDescribeInstancesWhenModified(InstanceStateName.Running);

    List<QueueTaskFuture> rs = getQueueTaskFutures(1);

    final String labelString = "momo";
    triggerSuggestReviewNow(labelString);

    Thread.sleep(TimeUnit.MINUTES.toMillis(2));

    verify(cloud, times(1)).provision(any(Label.class), anyInt());

    cancelTasks(rs);
}
 
Example #22
Source File: JobsTest.java    From jenkins-client-java with MIT License 5 votes vote down vote up
@Test
public void getLastBuildDetails() throws IOException, ExecutionException, InterruptedException {
    FreeStyleProject project = j.createFreeStyleProject();
    QueueTaskFuture<FreeStyleBuild> build = project.scheduleBuild2(0);
    assertNotNull(build);
    build.waitForStart();
    j.waitForCompletion(build.get());

    BuildDetail buildDetails = jobs.getLastBuildDetails(project.getName());
    assertNotNull(buildDetails);
}
 
Example #23
Source File: PipelineNodeTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Test
@Issue("JENKINS-49297")
public void submitInputPostBlock() throws Exception {
    WorkflowJob job = j.jenkins.createProject(WorkflowJob.class, "pipeline1");
    URL resource = Resources.getResource(getClass(), "stepsFromPost.jenkinsfile");
    String jenkinsFile = Resources.toString(resource, Charsets.UTF_8);
    job.setDefinition(new CpsFlowDefinition(jenkinsFile, true));
    QueueTaskFuture<WorkflowRun> buildTask = job.scheduleBuild2(0);
    WorkflowRun run = buildTask.getStartCondition().get();
    CpsFlowExecution e = (CpsFlowExecution) run.getExecutionPromise().get();

    while (run.getAction(InputAction.class) == null) {
        e.waitForSuspension();
    }

    List<Map> nodes = get("/organizations/jenkins/pipelines/pipeline1/runs/1/nodes/", List.class);

    assertEquals(1, nodes.size());

    List<Map> steps = get("/organizations/jenkins/pipelines/pipeline1/runs/1/nodes/" + nodes.get(0).get("id") + "/steps/", List.class);

    assertEquals(3, steps.size());

    assertEquals("7", steps.get(0).get("id"));
    assertEquals("Hello World", steps.get(0).get("displayDescription"));
    assertEquals("12", steps.get(1).get("id"));
    assertEquals("Hello World from post", steps.get(1).get("displayDescription"));
    assertEquals("13", steps.get(2).get("id"));
    assertEquals("Wait for interactive input", steps.get(2).get("displayName"));
}
 
Example #24
Source File: PipelineNodeTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Test
@Issue("JENKINS-48884")
public void submitInputPostBlockWithParallelStages() throws Exception {
    WorkflowJob job = j.jenkins.createProject(WorkflowJob.class, "pipeline1");
    URL resource = Resources.getResource(getClass(), "parallelStepsFromPost.jenkinsfile");
    String jenkinsFile = Resources.toString(resource, Charsets.UTF_8);
    job.setDefinition(new CpsFlowDefinition(jenkinsFile, true));
    QueueTaskFuture<WorkflowRun> buildTask = job.scheduleBuild2(0);
    WorkflowRun run = buildTask.getStartCondition().get();
    CpsFlowExecution e = (CpsFlowExecution) run.getExecutionPromise().get();

    while (run.getAction(InputAction.class) == null) {
        e.waitForSuspension();
    }

    List<Map> nodes = get("/organizations/jenkins/pipelines/pipeline1/runs/1/nodes/", List.class);

    assertEquals(6, nodes.size());

    List<Map> steps = get("/organizations/jenkins/pipelines/pipeline1/runs/1/nodes/" + nodes.get(0).get("id") + "/steps/", List.class);

    assertEquals(4, steps.size());

    assertEquals("15", steps.get(0).get("id"));
    assertEquals("exit 1", steps.get(0).get("displayDescription"));
    assertEquals("17", steps.get(1).get("id"));
    assertEquals("hello stable", steps.get(1).get("displayDescription"));
    assertEquals("47", steps.get(2).get("id"));
    assertEquals("Hello World from post", steps.get(2).get("displayDescription"));
    assertEquals("48", steps.get(3).get("id"));
    assertEquals("Wait for interactive input", steps.get(3).get("displayName"));
}
 
Example #25
Source File: IntegrationTest.java    From ec2-spot-jenkins-plugin with Apache License 2.0 5 votes vote down vote up
protected List<QueueTaskFuture> getQueueTaskFutures(int count) throws IOException {
    final LabelAtom label = new LabelAtom("momo");

    final List<QueueTaskFuture> rs = new ArrayList<>();
    for (int i = 0; i < count; i++) {
        final FreeStyleProject project = j.createFreeStyleProject();
        project.setAssignedLabel(label);
        project.getBuildersList().add(Functions.isWindows() ? new BatchFile("Ping -n " + JOB_SLEEP_TIME + " 127.0.0.1 > nul") : new Shell("sleep " + JOB_SLEEP_TIME));
        rs.add(project.scheduleBuild2(0));
    }
    return rs;
}
 
Example #26
Source File: NoDelayProvisionStrategyPerformanceTest.java    From ec2-spot-jenkins-plugin with Apache License 2.0 5 votes vote down vote up
private static void waitTasksFinish(List<QueueTaskFuture> tasks) {
    for (final QueueTaskFuture<FreeStyleBuild> task : tasks) {
        try {
            task.get();
        } catch (InterruptedException | ExecutionException e) {
            throw new RuntimeException(e);
        }
    }
}
 
Example #27
Source File: AutoResubmitIntegrationTest.java    From ec2-spot-jenkins-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void should_successfully_resubmit_freestyle_task() throws Exception {
    EC2FleetCloud cloud = new EC2FleetCloud(null, null, "credId", null, "region",
            null, "fId", "momo", null, new LocalComputerConnector(j), false, false,
            0, 0, 10, 1, false, false,
            false, 0, 0, false,
            10, false);
    j.jenkins.clouds.add(cloud);

    List<QueueTaskFuture> rs = getQueueTaskFutures(1);

    System.out.println("check if zero nodes!");
    Assert.assertEquals(0, j.jenkins.getNodes().size());

    assertAtLeastOneNode();

    final Node node = j.jenkins.getNodes().get(0);
    assertQueueIsEmpty();

    System.out.println("disconnect node");
    node.toComputer().disconnect(new OfflineCause.ChannelTermination(new UnsupportedOperationException("Test")));

    // due to test nature job could be failed if started or aborted as we call disconnect
    // in prod code it's not matter
    assertLastBuildResult(Result.FAILURE, Result.ABORTED);

    node.toComputer().connect(true);
    assertNodeIsOnline(node);
    assertQueueAndNodesIdle(node);

    Assert.assertEquals(1, j.jenkins.getProjects().size());
    Assert.assertEquals(Result.SUCCESS, j.jenkins.getProjects().get(0).getLastBuild().getResult());
    Assert.assertEquals(2, j.jenkins.getProjects().get(0).getBuilds().size());

    cancelTasks(rs);
}
 
Example #28
Source File: AutoResubmitIntegrationTest.java    From ec2-spot-jenkins-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void should_not_resubmit_if_disabled() throws Exception {
    EC2FleetCloud cloud = new EC2FleetCloud(null, null, "credId", null, "region",
            null, "fId", "momo", null, new LocalComputerConnector(j), false, false,
            0, 0, 10, 1, false, false,
            true, 0, 0, false, 10, false);
    j.jenkins.clouds.add(cloud);

    List<QueueTaskFuture> rs = getQueueTaskFutures(1);

    System.out.println("check if zero nodes!");
    Assert.assertEquals(0, j.jenkins.getNodes().size());

    assertAtLeastOneNode();

    final Node node = j.jenkins.getNodes().get(0);
    assertQueueIsEmpty();

    System.out.println("disconnect node");
    node.toComputer().disconnect(new OfflineCause.ChannelTermination(new UnsupportedOperationException("Test")));

    assertLastBuildResult(Result.FAILURE, Result.ABORTED);

    node.toComputer().connect(true);
    assertNodeIsOnline(node);
    assertQueueAndNodesIdle(node);

    Assert.assertEquals(1, j.jenkins.getProjects().size());
    Assert.assertEquals(Result.FAILURE, j.jenkins.getProjects().get(0).getLastBuild().getResult());
    Assert.assertEquals(1, j.jenkins.getProjects().get(0).getBuilds().size());

    cancelTasks(rs);
}
 
Example #29
Source File: ProvisionIntegrationTest.java    From ec2-spot-jenkins-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void should_add_planned_if_capacity_required_but_not_described_yet() throws Exception {
    ComputerLauncher computerLauncher = mock(ComputerLauncher.class);
    ComputerConnector computerConnector = mock(ComputerConnector.class);
    when(computerConnector.launch(anyString(), any(TaskListener.class))).thenReturn(computerLauncher);

    mockEc2ApiToDescribeFleetNotInstanceWhenModified();

    EC2FleetCloud cloud = new EC2FleetCloud(null, null, "credId", null, "region",
            null, "fId", "momo", null, computerConnector, false, false,
            0, 0, 10, 1, false, false,
            false, 0, 0, false,
            2, false);
    j.jenkins.clouds.add(cloud);

    List<QueueTaskFuture> rs = getQueueTaskFutures(1);

    triggerSuggestReviewNow("momo");

    Assert.assertEquals(0, j.jenkins.getNodes().size());

    tryUntil(new Runnable() {
        @Override
        public void run() {
            Assert.assertEquals(0, j.jenkins.getNodes().size());
            Assert.assertEquals(2, j.jenkins.getLabels().size());
            Assert.assertEquals(1, j.jenkins.getLabelAtom("momo").nodeProvisioner.getPendingLaunches().size());
        }
    });

    cancelTasks(rs);
}
 
Example #30
Source File: DashboardView.java    From jenkins-deployment-dashboard-plugin with MIT License 4 votes vote down vote up
@JavaScriptMethod
public String deploy(String version, String environment) {
    LOGGER.info("Deploy version " + version + " to environment " + environment);

    // Get the environment with corresponding build-job
    Environment buildEnvironment = null;
    for (Environment env : environments) {
        if (env.getAwsInstance().equals(environment)) {
            buildEnvironment = env;
            break;
        }
    }

    final AbstractProject buildJob = Jenkins.getInstance().getItemByFullName(buildEnvironment.getBuildJob(), AbstractProject.class);
    LOGGER.info("Executing job: " + buildJob);

    if (buildJob == null) {
        return String.format(Messages.DashboardView_buildJobNotFound(), buildEnvironment.getName());
    }

    if ((!buildJob.isBuildable()) || (!buildJob.isParameterized())) {
        return Messages.DashboardView_deploymentCannotBeExecuted();
    }

    final ParametersAction versionParam = new ParametersAction(new StringParameterValue(PARAM_VERSION, version));
    final ParametersAction environmentParam = new ParametersAction(new StringParameterValue(PARAM_ENVIRONMENT, environment));
    final ParametersAction ec2RegionParam = new ParametersAction(new StringParameterValue(PARAM_EC2_REGION, environment));
    final ParametersAction awsKeyParam = new ParametersAction(new StringParameterValue(PARAM_AWS_KEY, environment));

    List<ParametersAction> actions = Arrays.asList(versionParam, environmentParam, ec2RegionParam, awsKeyParam);
    QueueTaskFuture<AbstractBuild> scheduledBuild = buildJob.scheduleBuild2(2, new Cause.UserIdCause(), actions);

    Result result = Result.FAILURE;
    try {
        AbstractBuild finishedBuild = scheduledBuild.get();
        result = finishedBuild.getResult();
        LOGGER.info("Build finished with result: " + result + " completed in: " + finishedBuild.getDurationString() + ". ");
    } catch (Exception e) {
        LOGGER.severe("Error while waiting for build " + scheduledBuild.toString() + ".");
        LOGGER.severe(e.getMessage());
        LOGGER.severe(ExceptionUtils.getFullStackTrace(e));
        return String.format(Messages.DashboardView_buildJobFailed(), buildJob.getName());
    }
    if (result == Result.SUCCESS) {
        return String.format(Messages.DashboardView_buildJobScheduledSuccessfully(), buildJob.getName());
    }
    return String.format(Messages.DashboardView_buildJobSchedulingFailed(), buildJob.getName());
}