com.offbytwo.jenkins.model.Build Java Examples

The following examples show how to use com.offbytwo.jenkins.model.Build. 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: JenkinsStatusUpdater.java    From seppb with MIT License 6 votes vote down vote up
protected void updateBuild(InstanceType instanceType, Set<String> jobNames) {
	int failedCount = 0;
	JenkinsClient jenkinsClient = jenkinsClientProvider.getJenkinsClient(instanceType);
	for (String jobName : jobNames) {
		if (failedCount < 5) {
			try {
				List<Build> builds = jenkinsClient.buildsLimit(jobName, 5);
				updateBuild(jobName, jenkinsClient, builds);
			} catch (Exception e1) {
				failedCount++;
				log.error("更新{}构建结果失败:{}", jobName, e1);
			}
		}
	}
	jenkinsClient.close();

}
 
Example #2
Source File: ClassicJobApi.java    From blueocean-plugin with MIT License 6 votes vote down vote up
public void abortAllBuilds(Folder folder, String pipeline) throws IOException {
    JobWithDetails job = jenkins.getJob(getFolder(folder, false), pipeline);

    for(Build build: job.getBuilds()){
        if(build.details().getResult() == null) {
            build.details().Stop();
            logger.info("Stopped build " + folder.getPath(pipeline) + " - #" + build.getNumber());
        }
    }

    Optional<FolderJob> folderJobOptional = jenkins.getFolderJob(job);

    if(folderJobOptional.isPresent()) {
        for (String s : folderJobOptional.get().getJobs().keySet()) {
            abortAllBuilds(folder.append(pipeline), s);
        }
    }
}
 
Example #3
Source File: JenkinsServerIntegration.java    From verigreen with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateJob() throws Exception {
    final String sourceJob = "pr";
    final String jobName = "test-job-" + UUID.randomUUID().toString();

    String sourceXml = server.getJobXml(sourceJob);

    server.createJob(jobName, sourceXml);

    Map<String, Job> jobs = server.getJobs();
    assertTrue(jobs.containsKey(jobName));
    JobWithDetails thisJob = jobs.get(jobName).details();
    assertNotNull(thisJob);
    assertTrue(thisJob.getBuilds().size() == 0);
    thisJob.build(ImmutableMap.of("foo_param", "MUST_PROVIDE_VALUES_DEFAULTS_DONT_WORK"));

    // wait to see if the job finishes, but with a timeout
    Future<Void> future = executor.submit(new PerformPollingTest(server, jobName));

    // If this times out, either jenkins is slow or our test failed!
    // IME, usually takes about 10-15 seconds
    future.get(30, TimeUnit.SECONDS);

    Build b = server.getJobs().get(jobName).details().getLastSuccessfulBuild();
    assertTrue(b != null);
}
 
Example #4
Source File: DeploymentHistory.java    From seppb with MIT License 5 votes vote down vote up
public static DeploymentHistory buildToDeploymentHistory(Build build, String jobName) throws IOException {
	return DeploymentHistory.builder()
			.deployVersion(build.getNumber())
			.deployJobName(jobName)
			.deployStatus(DeploymentStatus.convertJenkinsStatus(build.details()))
			.userName("jenkins")
			.build();
}
 
Example #5
Source File: DeploymentStatusUpdater.java    From seppb with MIT License 5 votes vote down vote up
private void updateDeploymentResult(String jobName, InstanceType instanceType) {
	try (JenkinsClient jenkinsClient = jenkinsClientProvider.getJenkinsClient(instanceType)) {
		List<Build> builds = jenkinsClient.buildsLimit(jobName, 5);
		for (Build build : builds) {
			PipelineStep pipelineStep = jenkinsClient.pipelineStep(jobName, build.getNumber());
			DeploymentHistory deploymentHistory = DeploymentHistory.buildToDeploymentHistory(build, jobName);
			ObjectMapper mapper = new ObjectMapper();
			deploymentHistory.setPipelineStep(mapper.writeValueAsString(pipelineStep));
			deploymentDAO.createOrUpdate(deploymentHistory);
		}
	} catch (Exception e) {
		log.error("更新{}部署结果失败:{}", jobName, e);
	}
}
 
Example #6
Source File: JenkinsStatusUpdater.java    From seppb with MIT License 5 votes vote down vote up
private void updateBuild(String jobName, JenkinsClient jenkinsClient, Build build) throws IOException {
	PipelineStep pipelineStep = jenkinsClient.pipelineStep(jobName, build.getNumber());
	BuildWithDetails details = build.details();
	BuildHistory buildHistory = apply(build.getNumber(), details, jobName);
	String pipeline = mapper.writeValueAsString(pipelineStep);
	buildHistory.setPipelineStep(pipeline);
	buildHistoryService.createOrUpdate(buildHistory);
	deploymentStatusUpdater.updateDeploymentResult(DeploymentHistory.builder()
			.jobName(jobName)
			.deployStatus(convertJenkinsStatus(details))
			.buildVersion(build.getNumber())
			.pipelineStep(pipeline)
			.deployJobName(DEPLOY_JOB_NAME).build());
}
 
Example #7
Source File: DeploymentService.java    From seppb with MIT License 5 votes vote down vote up
/**
 * 在部署的过程中,需要选择版本号,而目前的部署是采用jenkins去做,而且构建物目前没有统一的存储地址
 * 都是以jenkins为存储仓库,所以获取版本号只用获取对应的jenkins中job的构建成功版本号即可
 *
 * @param jobName
 * @param instanceType
 * @return
 */
public List<JenkinsBuildResp> selectDeployVersion(String jobName, InstanceType instanceType) {
	try (JenkinsClient jenkinsClient = jenkinsClientProvider.getJenkinsClient(instanceType)) {
		List<Build> builds = jenkinsClient.buildsLimit(jobName, 5);
		return builds.stream().map(this::buildJenkinsBuildResp).filter(JenkinsBuildResp::canDeploy).collect(toList());
	} catch (Exception e) {
		throw new SeppClientException(String.format("无法获取%s的可以部署的版本", jobName));
	}
}
 
Example #8
Source File: DeploymentService.java    From seppb with MIT License 5 votes vote down vote up
private JenkinsBuildResp buildJenkinsBuildResp(Build build) {
	BuildWithDetails details;
	try {
		details = build.details();
	} catch (IOException e) {
		throw new SeppClientException("无法该job可以部署的版本");
	}
	return JenkinsBuildResp.apply(build.getNumber(), details.getResult());
}
 
Example #9
Source File: ForgeClientAsserts.java    From fabric8-forge with Apache License 2.0 5 votes vote down vote up
public static void dumpBuildLog(Build lastBuild, String description) throws IOException {
    String logUri = getBuildConsoleTextUrl(lastBuild, description);

    URL logURL = new URL(logUri);
    InputStream inputStream = logURL.openStream();

    printBuildLog(inputStream, description);
}
 
Example #10
Source File: ForgeClientAsserts.java    From fabric8-forge with Apache License 2.0 5 votes vote down vote up
public static String getBuildConsoleTextUrl(Build lastBuild, String description) {
    String url = lastBuild.getUrl();

    LOG.info("Build URL: " + url);
    String logUri = url + "/consoleText";
    if (logUri.indexOf("://") < 0) {
        logUri = URLUtils.pathJoin(getJenkinsURL(), logUri);
    }
    LOG.info("Tailing " + description + " at URL:" + logUri);
    return logUri;
}
 
Example #11
Source File: JenkinsVerifier.java    From verigreen with Apache License 2.0 5 votes vote down vote up
@Override
public boolean stop(String jobName, String buildIdToStop) {
    //TODO: Remove unnecessary calls to Jenkins for stopping a Build. Try to minimize the number of calls.   
    boolean ans = false;
    try {
        VerigreenLogger.get().log(
                getClass().getName(),
                RuntimeUtils.getCurrentMethodName(),
                String.format("Stopping build (%s)", buildIdToStop));
        JobWithDetails job = CollectorApi.getJenkinsServer().getJob(jobName);
        Build buildToStop = job.getBuildByNumber(Integer.parseInt(buildIdToStop));
        if (buildIdToStop != null) {
            buildToStop.Stop();
            ans = buildToStop.details().getResult().equals(BuildResult.ABORTED);
        } else {
            VerigreenLogger.get().error(
                    getClass().getName(),
                    RuntimeUtils.getCurrentMethodName(),
                    String.format(
                            "There is no build number [%s] for job [%s]",
                            buildIdToStop,
                            jobName));
        }
    } catch (Throwable e) {
        VerigreenLogger.get().error(
                getClass().getName(),
                RuntimeUtils.getCurrentMethodName(),
                String.format("Failed to stop build [%s] for job [%s]", buildIdToStop, jobName),
                e);
    }
    
    return ans;
}
 
Example #12
Source File: JenkinsStatusUpdater.java    From seppb with MIT License 4 votes vote down vote up
private void updateBuild(String jobName, JenkinsClient jenkinsClient, List<Build> builds) throws IOException {
	List<Build> buildList = builds.stream().sorted(Comparator.comparing(Build::getNumber).reversed()).limit(5).collect(toList());
	for (Build build : buildList) {
		updateBuild(jobName, jenkinsClient, build);
	}
}
 
Example #13
Source File: ForgeTestSupport.java    From fabric8-forge with Apache License 2.0 4 votes vote down vote up
protected Build assertCodeChangeTriggersWorkingBuild(final String projectName, Build firstBuild) throws Exception {
    File cloneDir = new File(getBasedir(), "target/projects/" + projectName);

    String gitUrl = asserGetAppGitCloneURL(forgeClient, projectName);
    Git git = ForgeClientAsserts.assertGitCloneRepo(gitUrl, cloneDir);

    // lets make a dummy commit...
    File readme = new File(cloneDir, "ReadMe.md");
    boolean mustAdd = false;
    String text = "";
    if (readme.exists()) {
        text = IOHelpers.readFully(readme);
    } else {
        mustAdd = true;
    }
    text += "\nupdated at: " + new Date();
    Files.writeToFile(readme, text, Charset.defaultCharset());

    if (mustAdd) {
        AddCommand add = git.add().addFilepattern("*").addFilepattern(".");
        add.call();
    }


    LOG.info("Committing change to " + readme);

    CommitCommand commit = git.commit().setAll(true).setAuthor(forgeClient.getPersonIdent()).setMessage("dummy commit to trigger a rebuild");
    commit.call();
    PushCommand command = git.push();
    command.setCredentialsProvider(forgeClient.createCredentialsProvider());
    command.setRemote("origin").call();

    LOG.info("Git pushed change to " + readme);

    // now lets wait for the next build to start
    int nextBuildNumber = firstBuild.getNumber() + 1;


    Asserts.assertWaitFor(10 * 60 * 1000, new Block() {
        @Override
        public void invoke() throws Exception {
            JobWithDetails job = assertJob(projectName);
            Build lastBuild = job.getLastBuild();
            assertThat(lastBuild.getNumber()).describedAs("Waiting for latest build for job " + projectName + " to start").isGreaterThanOrEqualTo(nextBuildNumber);
        }
    });

    return ForgeClientAsserts.assertBuildCompletes(forgeClient, projectName);
}
 
Example #14
Source File: ForgeClientAsserts.java    From fabric8-forge with Apache License 2.0 4 votes vote down vote up
/**
 * Asserts that a Build is created and that it completes successfully within the default time period
 */
public static Build assertBuildCompletes(ForgeClient forgeClient, String projectName) throws Exception {
    return assertBuildCompletes(forgeClient, projectName, DEFAULT_TIMEOUT_MILLIS);
}