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}", AbstractPipelineIT.class.getName() + ".emitBuildEvent()"); CpsFlowDefinition flowDefinition = new CpsFlowDefinition(script, true); job.setDefinition(flowDefinition); QueueTaskFuture<WorkflowRun> run = job.scheduleBuild2(0); jenkinsRule.assertBuildStatusSuccess(run.get()); 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); }
public static QueuedJob triggerJob(BuildContext context, String jobName, Map<String, String> params) throws InterruptedException, ExecutionException { boolean foundJob = false; for (AbstractProject proj : Jenkins.getInstance().getAllItems(AbstractProject.class)) { if (proj.getName().equals(jobName)) { context.listener.getLogger().println("Triggering build '" + HyperlinkNote.encodeTo("/" + proj.getUrl(), proj.getFullDisplayName()) + "'..."); // add parameters if specified List<Action> actions = new ArrayList<Action>(); if (params != null) { List<ParameterValue> paramValues = new ArrayList<ParameterValue>(); for (Map.Entry<String, String> param : params.entrySet()) { context.listener.getLogger().println(" Adding parameter: '" + param.getKey() + "' = '" + param.getValue() + "'"); paramValues.add(new StringParameterValue(param.getKey(), param.getValue())); } actions.add(new ParametersAction(paramValues)); } QueueTaskFuture scheduled = proj.scheduleBuild2(proj.getQuietPeriod(), new Cause.UpstreamCause((Run<?, ?>) context.build), actions); return new QueuedJob(proj, scheduled); } } context.listener.fatalError("No project matched job: '" + jobName + "'"); throw new BuildResultException(Result.FAILURE); }
@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(); }
@Before @SuppressWarnings("unused") public void setUp() throws Exception { AbstractProject<?, ?> project = jenkinsRule.createFreeStyleProject("GhprcRepoTest"); trigger = spy(GhprcTestUtil.getTrigger(null)); doReturn(mock(QueueTaskFuture.class)).when(trigger).startJob(any(GhprcCause.class), any(GhprcRepository.class)); initGHPRWithTestData(); // Mock github API given(helper.getGitHub()).willReturn(gitHub); given(gitHub.get()).willReturn(gt); given(gt.getRepository(anyString())).willReturn(ghRepository); // Mock rate limit given(gt.getRateLimit()).willReturn(ghRateLimit); increaseRateLimitToDefaults(); addSimpleStatus(); }
@Ignore("Unit test fails when performing a release. The queue has a race condition" + "which is resolved in 1.607+ (TODO).") @Test public void verifyMinimumBuildQueue() throws Exception { // Given QueueTaskFuture<FreeStyleBuild> build; String assignedLabel = "foo"; FreeStyleProject p = j.createFreeStyleProject("bar"); p.setAssignedLabel(new LabelAtom(assignedLabel)); BuildQueue queue = new BuildQueue(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); // When build = p.scheduleBuild2(0); queue.addContents(createContainer(baos)); // Then build.cancel(true); List<String> output = new ArrayList<String>(Arrays.asList(baos.toString().split("\n"))); assertContains(output, "1 item"); assertContains(output, p.getDisplayName()); assertContains(output, "Waiting for next available executor"); }
private WorkflowRun runWorkflowJob(WorkflowJob job) throws ExecutionException, InterruptedException { QueueTaskFuture<WorkflowRun> runFuture = job.scheduleBuild2(0); assertThat(runFuture, notNullValue()); run = runFuture.get(); return run; }
public static WorkflowRun createWorkflowJobAndRun(Jenkins jenkins, String script) throws Exception { WorkflowJob job = jenkins.createProject(WorkflowJob.class, RandomStringUtils.randomAlphanumeric(7)); job.setDefinition(new CpsFlowDefinition(script)); QueueTaskFuture<WorkflowRun> runFuture = job.scheduleBuild2(0); assertThat(runFuture, notNullValue()); return runFuture.get(); }
private static WorkflowRun createWorkflowJobAndRun(String script) throws Exception { WorkflowJob job = j.jenkins.createProject(WorkflowJob.class, RandomStringUtils.randomAlphanumeric(7)); job.setDefinition(new CpsFlowDefinition(script)); QueueTaskFuture<WorkflowRun> runFuture = job.scheduleBuild2(0); assertThat(runFuture, notNullValue()); return runFuture.get(); }
/** * Invoked when a tag-related event is received. * * @param cause build cause * @return task future, or {@code null} if it could not be scheduled. */ public QueueTaskFuture startJob(@Nonnull TagCause cause) { LOGGER.info(cause.getShortDescription()); ArrayList<ParameterValue> values = getDefaultParameters(); values.add(new StringParameterValue("GH_PUSHER", cause.getPusher())); values.add(new StringParameterValue("GIT_TAG", cause.getTag())); values.add(new StringParameterValue("GIT_REF", cause.getRef())); ParameterizedJobMixIn pjob = asParameterizedJobMixIn(job); return pjob.scheduleBuild2(3, new CauseAction(cause), new ParametersAction(values)); }
@Override public FormValidation doBuild(StaplerRequest req) throws IOException { FormValidation result; try { Jenkins instance = GitHubWebHook.getJenkinsInstance(); if (!instance.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, 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; }
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; }
@RequirePOST public FormValidation doBuild(StaplerRequest req) throws IOException { FormValidation result; try { Jenkins instance = GitHubWebHook.getJenkinsInstance(); if (!instance.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(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; }
@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; }
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); }
public QueueTaskFuture<?> startJob(GhprcCause cause, GhprcRepository repo) { ArrayList<ParameterValue> values = getDefaultParameters(); final String commitSha = cause.isMerged() ? "origin/pr/" + cause.getPullID() + "/merge" : cause.getCommit(); values.add(new StringParameterValue("sha1", commitSha)); values.add(new StringParameterValue("ghprcActualCommit", cause.getCommit())); setCommitAuthor(cause, values); final StringParameterValue pullIdPv = new StringParameterValue("ghprcPullId", String.valueOf(cause.getPullID())); values.add(pullIdPv); values.add(new StringParameterValue("ghprcTargetBranch", String.valueOf(cause.getTargetBranch()))); values.add(new StringParameterValue("ghprcSourceBranch", String.valueOf(cause.getSourceBranch()))); values.add(new StringParameterValue("GIT_BRANCH", String.valueOf(cause.getSourceBranch()))); // it's possible the GHUser doesn't have an associated email address values.add(new StringParameterValue("ghprcPullAuthorEmail", getString(cause.getAuthorEmail(), ""))); values.add(new StringParameterValue("ghprcPullDescription", String.valueOf(cause.getShortDescription()))); values.add(new StringParameterValue("ghprcPullTitle", String.valueOf(cause.getTitle()))); values.add(new StringParameterValue("ghprcPullLink", String.valueOf(cause.getUrl()))); values.add(new StringParameterValue("ghprcOutputFile", getDescriptor().getOutputFile())); try { values.add(new StringParameterValue("ghprcTargetCommit", repo.getGitHubRepo().getBranches().get(cause.getTargetBranch()).getSHA1())); } catch (IOException e) { logger.log(Level.SEVERE, "Unable to get branches from github repo", e); } // add the previous pr BuildData as an action so that the correct change log is generated by the GitSCM plugin // note that this will be removed from the Actions list after the job is completed so that the old (and incorrect) // one isn't there return this.job.scheduleBuild2(job.getQuietPeriod(), cause, new ParametersAction(values), findPreviousBuildForPullId(pullIdPv)); }
public QueueTaskFuture<?> startJob(BitbucketCause cause) { Map<String, ParameterValue> values = this.getDefaultParameters(); if (getCancelOutdatedJobs()) { cancelPreviousJobsInQueueThatMatch(cause); abortRunningJobsThatMatch(cause); } return retrieveScheduleJob(this.job).scheduleBuild2(0, new CauseAction(cause), new ParametersAction(new ArrayList(values.values())), new RevisionParameterAction(cause.getSourceCommitHash())); }
@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()); }
@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(5, 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()); }
@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)); }
@Test public void skip_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 MergeRequestBuildAction(testProject, getJson("MergeRequestEvent_alreadyBuiltMR.json"), null).execute(response); verify(trigger, never()).onPost(any(MergeRequestHook.class)); }
public QueueTaskFuture<?> startJob(GhprbCause cause){ ArrayList<ParameterValue> values = getDefaultParameters(); values.add(new StringParameterValue("sha1", cause.isMerged() ? "origin/pr/" + cause.getPullID() + "/merge" : cause.getCommit())); values.add(new StringParameterValue("ghprbActualCommit",cause.getCommit())); final StringParameterValue pullIdPv = new StringParameterValue("ghprbPullId",String.valueOf(cause.getPullID())); values.add(pullIdPv); values.add(new StringParameterValue("ghprbTargetBranch",String.valueOf(cause.getTargetBranch()))); // it's possible the GHUser doesn't have an associated email address values.add(new StringParameterValue("ghprbPullAuthorEmail",cause.getAuthorEmail() != null ? cause.getAuthorEmail() : "")); // add the previous pr BuildData as an action so that the correct change log is generated by the GitSCM plugin // note that this will be removed from the Actions list after the job is completed so that the old (and incorrect) // one isn't there return this.job.scheduleBuild2(0,cause,new ParametersAction(values),findPreviousBuildForPullId(pullIdPv)); }
/** * @param sleep * @param eps * @param parallel * @param p */ private void buildTwoandCheckOrder(long sleep, double eps, boolean parallel, InheritanceProject p) { try { /* Scheduling the builds. * We need to give the gpp a random parameter, to avoid Jenkins * from mercilessly killing our duplicated jobs, if two of them * happen to be simultaneously in the queue. */ QueueTaskFuture<InheritanceBuild> f1 = p.scheduleBuild2( 0, new UserIdCause(), new ParametersAction( new StringParameterValue("RNG", UUID.randomUUID().toString()) ) ); QueueTaskFuture<InheritanceBuild> f2 = p.scheduleBuild2( 0, new UserIdCause(), new ParametersAction( new StringParameterValue("RNG", UUID.randomUUID().toString()) ) ); assertNotNull("First build failed to start, miserably", f1); assertNotNull("Second build failed to start, miserably", f2); InheritanceBuild[] builds = { f1.get(), f2.get() }; assertNotNull("First build failed to evaluate", builds[0]); assertNotNull("Second build failed to evaluate", builds[1]); checkBuildOrder((long)eps*sleep, parallel, builds); } catch (Exception ex) { fail(ex.getMessage()); } }
public void subTestParameterMode(XmlProject A, XmlProject B) throws IOException { //Alter the parameter in A to be "extend" instead of "overwrite" A.setParameter(new InheritableStringParameterDefinition( "P", "A", IModes.EXTENSIBLE, false, false, WhitespaceMode.KEEP, false )); B.setParameter(new InheritableStringParameterDefinition( "P", "B", IModes.OVERWRITABLE, false, false, WhitespaceMode.KEEP, false )); //Build and check value buildAndAssertValue(B, "P", "AB"); //Test the reverse; overwrite followed by extend A.setParameter(new InheritableStringParameterDefinition( "P", "A", IModes.OVERWRITABLE, false, false, WhitespaceMode.KEEP, false )); B.setParameter(new InheritableStringParameterDefinition( "P", "B", IModes.EXTENSIBLE, false, false, WhitespaceMode.KEEP, false )); buildAndAssertValue(B, "P", "B"); //Test fixed mode B.setParameter(new InheritableStringParameterDefinition( "P", "B", IModes.FIXED, false, false, WhitespaceMode.KEEP, false )); buildAndAssertValue(B, "P", "B"); //Also fix 'A', this should lead to a failed build A.setParameter(new InheritableStringParameterDefinition( "P", "A", IModes.FIXED, false, false, WhitespaceMode.KEEP, false )); //The build must even fail to queue in this case QueueTaskFuture<InheritanceBuild> qtf = B.project.scheduleBuild2(0); Assert.assertNull("Building 'B' with 2 fixed parameters should have failed to schedule!", qtf); }
@Test public void provisionAndLaunch() throws Exception { FreeStyleProject p = j.createFreeStyleProject(); p.setAssignedLabel(Label.get("label")); QueueTaskFuture<FreeStyleBuild> build = p.scheduleBuild2(0); j.jenkins.clouds.add(new TestCloud("dummy", j, new LaunchSuccessfully())); triggerProvisioning(); List<ProvisioningActivity> activities; for (;;) { activities = CloudStatistics.get().getActivities(); if (activities.size() > 0) break; } for (ProvisioningActivity a : activities) { assertEquals(activities.toString(), "dummy", a.getId().getCloudName()); assertThat(activities.toString(), a.getId().getNodeName(), startsWith("dummy-slave-")); assertThat(activities.toString(), a.getName(), startsWith("dummy-slave-")); } ProvisioningActivity activity = activities.get(0); assertNotNull(activity.getPhaseExecution(PROVISIONING)); assertEquals(activity.getPhaseExecution(PROVISIONING).getAttachments().toString(), OK, activity.getStatus()); // It can take a bit while (j.jenkins.getComputer(activity.getId().getNodeName()) == null) { System.out.println("Waiting for node"); Thread.sleep(100); } Computer computer = j.jenkins.getComputer(activity.getId().getNodeName()); assertNotNull(computer); while (activity.getPhaseExecution(LAUNCHING) == null) { System.out.println("Waiting for launch to start"); Thread.sleep(100); } while (activity.getPhaseExecution(OPERATING) == null) { System.out.println("Waiting for slave to launch"); Thread.sleep(100); } System.out.println("Waiting for slave to launch"); computer.waitUntilOnline(); assertNull(activity.getPhaseExecution(COMPLETED)); System.out.println("Waiting for build to complete"); Computer builtOn = build.get().getBuiltOn().toComputer(); assertEquals(computer, builtOn); computer.doDoDelete(); assertEquals(OK, activity.getStatus()); detectCompletionNow(); assertNotNull(activity.getCurrentPhase().toString(), activity.getPhaseExecution(COMPLETED)); }
public QueuedJob(AbstractProject<?, ?> project, QueueTaskFuture<Queue.Executable> result) { this.project = project; this.result = result; }
@Test public void testDockerShellStep() throws Throwable { jRule.getInstance().setNumExecutors(0); // jRule.createSlave(); // jRule.createSlave("my-slave", "remote-slave", new EnvVars()); final UsernamePasswordCredentialsImpl credentials = new UsernamePasswordCredentialsImpl(CredentialsScope.SYSTEM, null, "description", "vagrant", "vagrant"); CredentialsStore store = CredentialsProvider.lookupStores(jRule.getInstance()).iterator().next(); store.addCredentials(Domain.global(), credentials); final SSHLauncher sshLauncher = new SSHLauncher("192.168.33.10", 22, credentials.getId(), "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005", //jvmopts "", // String javaPath, "", // String prefixStartSlaveCmd, "", // String suffixStartSlaveCmd, 20, // Integer launchTimeoutSeconds, 1, // Integer maxNumRetries, 3// Integer retryWaitTime ); final DumbSlave dumbSlave = new DumbSlave("docker-daemon", "/home/vagrant/jenkins2", sshLauncher); jRule.getInstance().addNode(dumbSlave); await().timeout(60, SECONDS).until(() -> assertThat(dumbSlave.getChannel(), notNullValue())); // String dockerfilePath = dumbSlave.getChannel().call(new DockerBuildImageStepTest.StringThrowableCallable()); final CredentialsYADockerConnector dockerConnector = new CredentialsYADockerConnector() .withConnectorType(JERSEY) .withServerUrl("tcp://127.0.0.1:2376") .withSslConfig(new LocalDirectorySSLConfig("/home/vagrant/keys")); // .withCredentials(new DockerDaemonFileCredentials(null, "docker-cert", "", // "/home/vagrant/keys")); DockerShellStep dockerShellStep = new DockerShellStep(); dockerShellStep.setShellScript("env && pwd"); dockerShellStep.setConnector(dockerConnector); FreeStyleProject project = jRule.createFreeStyleProject("test"); project.getBuildersList().add(dockerShellStep); project.save(); QueueTaskFuture<FreeStyleBuild> taskFuture = project.scheduleBuild2(0); FreeStyleBuild freeStyleBuild = taskFuture.get(); jRule.waitForCompletion(freeStyleBuild); jRule.assertBuildStatusSuccess(freeStyleBuild); }
@Ignore @Test public void testComboBuild() throws Throwable { jRule.getInstance().setNumExecutors(0); // jRule.createSlave(); // jRule.createSlave("my-slave", "remote-slave", new EnvVars()); final UsernamePasswordCredentialsImpl credentials = new UsernamePasswordCredentialsImpl(CredentialsScope.SYSTEM, null, "description", "vagrant", "vagrant"); CredentialsStore store = CredentialsProvider.lookupStores(jRule.getInstance()).iterator().next(); store.addCredentials(Domain.global(), credentials); final SSHLauncher sshLauncher = new SSHLauncher("192.168.33.10", 22, credentials.getId(), "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005", //jvmopts "", // String javaPath, "", // String prefixStartSlaveCmd, "", // String suffixStartSlaveCmd, 20, // Integer launchTimeoutSeconds, 1, // Integer maxNumRetries, 3// Integer retryWaitTime ); final DumbSlave dumbSlave = new DumbSlave("docker-daemon", "/home/vagrant/jenkins2", sshLauncher); jRule.getInstance().addNode(dumbSlave); await().timeout(60, SECONDS).until(() -> assertThat(dumbSlave.getChannel(), notNullValue())); String dockerfilePath = dumbSlave.getChannel().call(new StringThrowableCallable()); final CredentialsYADockerConnector dockerConnector = new CredentialsYADockerConnector() .withConnectorType(JERSEY) .withServerUrl("tcp://127.0.0.1:2376") .withSslConfig(new LocalDirectorySSLConfig("/home/vagrant/keys")); // .withCredentials(new DockerDaemonFileCredentials(null, "docker-cert", "", // "/home/vagrant/keys")); DockerBuildImage buildImage = new DockerBuildImage(); buildImage.setBaseDirectory(dockerfilePath); buildImage.setPull(true); buildImage.setTags(Collections.singletonList("localhost:5000/myfirstimage")); DockerImageComboStep comboStep = new DockerImageComboStep(dockerConnector, buildImage); comboStep.setClean(true); comboStep.setPush(true); FreeStyleProject project = jRule.createFreeStyleProject("test"); project.getBuildersList().add(comboStep); project.save(); QueueTaskFuture<FreeStyleBuild> taskFuture = project.scheduleBuild2(0); FreeStyleBuild freeStyleBuild = taskFuture.get(); jRule.waitForCompletion(freeStyleBuild); jRule.assertBuildStatusSuccess(freeStyleBuild); }
@Test public void testBuild() throws Throwable { jRule.getInstance().setNumExecutors(0); // jRule.createSlave(); // jRule.createSlave("my-slave", "remote-slave", new EnvVars()); final UsernamePasswordCredentialsImpl credentials = new UsernamePasswordCredentialsImpl(CredentialsScope.SYSTEM, null, "description", "vagrant", "vagrant"); CredentialsStore store = CredentialsProvider.lookupStores(jRule.getInstance()).iterator().next(); store.addCredentials(Domain.global(), credentials); final SSHLauncher sshLauncher = new SSHLauncher("192.168.33.10", 22, credentials.getId(), "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005", //jvmopts "", // String javaPath, "", // String prefixStartSlaveCmd, "", // String suffixStartSlaveCmd, 20, // Integer launchTimeoutSeconds, 1, // Integer maxNumRetries, 3// Integer retryWaitTime ); final DumbSlave dumbSlave = new DumbSlave("docker-daemon", "/home/vagrant/jenkins2", sshLauncher); jRule.getInstance().addNode(dumbSlave); await().timeout(60, SECONDS).until(() -> assertThat(dumbSlave.getChannel(), notNullValue())); String dockerfilePath = dumbSlave.getChannel().call(new StringThrowableCallable()); final CredentialsYADockerConnector dockerConnector = new CredentialsYADockerConnector() .withConnectorType(JERSEY) .withServerUrl("tcp://127.0.0.1:2376") .withSslConfig(new LocalDirectorySSLConfig("/home/vagrant/keys")); // .withCredentials(new DockerDaemonFileCredentials(null, "docker-cert", "", // "/home/vagrant/keys")); DockerBuildImage buildImage = new DockerBuildImage(); buildImage.setBaseDirectory(dockerfilePath); buildImage.setPull(true); DockerBuildImageStep dockerBuildImageStep = new DockerBuildImageStep(dockerConnector, buildImage); FreeStyleProject project = jRule.createFreeStyleProject("test"); project.getBuildersList().add(dockerBuildImageStep); project.save(); QueueTaskFuture<FreeStyleBuild> taskFuture = project.scheduleBuild2(0); FreeStyleBuild freeStyleBuild = taskFuture.get(); jRule.waitForCompletion(freeStyleBuild); jRule.assertBuildStatusSuccess(freeStyleBuild); }
public QueueTaskFuture<?> startJob(GitHubPRCause cause) { return startJob(cause, null); }
public QueueTaskFuture<?> startJob(GitHubBranchCause cause) { return startJob(cause, null); }
@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()); }
/** * Test persisting jobs with parameters. * * @throws Exception in Jenkins rule */ @Test public void testSaveParameters() throws Exception { FreeStyleProject project = j.createFreeStyleProject(); GroovyScript scriptParam001 = new GroovyScript(new SecureGroovyScript(SCRIPT_PARAM001, false, null), new SecureGroovyScript(SCRIPT_FALLBACK_PARAM001, false, null)); ChoiceParameter param001 = new ChoiceParameter("param001", "param001 description", "random-name", scriptParam001, AbstractUnoChoiceParameter.PARAMETER_TYPE_SINGLE_SELECT, true, 1); GroovyScript scriptParam002 = new GroovyScript(new SecureGroovyScript(SCRIPT_PARAM002, false, null), new SecureGroovyScript(SCRIPT_FALLBACK_PARAM002, false, null)); CascadeChoiceParameter param002 = new CascadeChoiceParameter("param002", "param002 description", "random-name", scriptParam002, AbstractUnoChoiceParameter.PARAMETER_TYPE_SINGLE_SELECT, "param001", true, 1); ParametersDefinitionProperty param001Def = new ParametersDefinitionProperty( Arrays.<ParameterDefinition>asList(param001, param002)); project.addProperty(param001Def); QueueTaskFuture<FreeStyleBuild> future = project.scheduleBuild2(0); FreeStyleBuild build = future.get(); // even though the cascaded parameter will fail to evaluate, we should // still get a success here. assertEquals(Result.SUCCESS, build.getResult()); XmlFile configXml = project.getConfigFile(); FreeStyleProject reReadProject = (FreeStyleProject) configXml.read(); int found = 0; for (Entry<JobPropertyDescriptor, JobProperty<? super FreeStyleProject>> entry : reReadProject.getProperties() .entrySet()) { JobProperty<? super FreeStyleProject> jobProperty = entry.getValue(); if (jobProperty instanceof ParametersDefinitionProperty) { ParametersDefinitionProperty paramDef = (ParametersDefinitionProperty) jobProperty; List<ParameterDefinition> parameters = paramDef.getParameterDefinitions(); for (ParameterDefinition parameter : parameters) { if (parameter instanceof AbstractScriptableParameter) { found++; AbstractScriptableParameter choiceParam = (AbstractScriptableParameter) parameter; String scriptText = ((GroovyScript) choiceParam.getScript()).getScript().getScript(); String fallbackScriptText = ((GroovyScript) choiceParam.getScript()).getFallbackScript() .getScript(); assertTrue("Found an empty script!", StringUtils.isNotBlank(scriptText)); assertTrue("Found an empty fallback script!", StringUtils.isNotBlank(fallbackScriptText)); if (parameter.getName().equals("param001")) { assertEquals(SCRIPT_PARAM001, scriptText); assertEquals(SCRIPT_FALLBACK_PARAM001, fallbackScriptText); } else { assertEquals(SCRIPT_PARAM002, scriptText); assertEquals(SCRIPT_FALLBACK_PARAM002, fallbackScriptText); } } } } } // We have two parameters before saving. We must have two now. assertEquals("Didn't find all parameters after persisting xml", 2, found); }
public void subTestParameterFlagDefaultCheck(XmlProject A, XmlProject B) throws IOException { //Check for positive case, with two real parameters A.setParameter(new InheritableStringParameterDefinition( "P", "A", IModes.OVERWRITABLE, true, false, WhitespaceMode.KEEP, false )); B.setParameter(new InheritableStringParameterDefinition( "P", "B", IModes.OVERWRITABLE, true, false, WhitespaceMode.KEEP, false )); Entry<Boolean, String> sanity = B.project.getParameterSanity(); Assert.assertTrue("Project B should have passed the parameter sanity check", sanity.getKey()); InheritanceBuild build = buildAndAssertValue(B, "P", "B", false); Assert.assertTrue( "Build for 'B' should have succeeded", build.getResult().isBetterOrEqualTo(Result.SUCCESS) ); //Check for negative case, with two real parameters A.setParameter(new InheritableStringParameterDefinition( "P", "A", IModes.OVERWRITABLE, true, false, WhitespaceMode.KEEP, false )); B.setParameter(new InheritableStringParameterDefinition( "P", "", IModes.OVERWRITABLE, true, false, WhitespaceMode.KEEP, false )); sanity = B.project.getParameterSanity(); Assert.assertFalse("Project B should have failed the parameter sanity check", sanity.getKey()); //The build must fail to queue in this case QueueTaskFuture<InheritanceBuild> qtf = B.project.scheduleBuild2(0); Assert.assertNull("Building 'B' (with a missing default value) should have failed to schedule!", qtf); //Check for positive case, with one reference A.setParameter(new InheritableStringParameterDefinition( "P", "A", IModes.OVERWRITABLE, true, false, WhitespaceMode.KEEP, false )); B.setParameter(new InheritableStringParameterReferenceDefinition( "P", "B" )); sanity = B.project.getParameterSanity(); Assert.assertTrue("Project B should have passed the parameter sanity check", sanity.getKey()); build = buildAndAssertValue(B, "P", "B", false); Assert.assertTrue( "Build for 'B' should have succeeded", build.getResult().isBetterOrEqualTo(Result.SUCCESS) ); //Check for negative case, with to real parameters A.setParameter(new InheritableStringParameterDefinition( "P", "A", IModes.OVERWRITABLE, true, false, WhitespaceMode.KEEP, false )); B.setParameter(new InheritableStringParameterReferenceDefinition( "P", "" )); sanity = B.project.getParameterSanity(); Assert.assertFalse("Project B should have failed the parameter sanity check", sanity.getKey()); //The build must fail to queue in this case qtf = B.project.scheduleBuild2(0); Assert.assertNull("Building 'B' (with a missing default value) should have failed to schedule!", qtf); }
@Test public void testLabelCaching() throws IOException, InterruptedException { printInfo("testLabelCaching()"); //Fetch the jenkins instance; which is a valid build host Jenkins j = Jenkins.getInstance(); //Set its label to a test value j.setLabelString("test:foo"); //Create a simple job XmlProject A = new XmlProject("A"); //Assign the test:foo label A.project.setAssignedLabel(new LabelAtom("test:foo")); //Build the job; should work try { QueueTaskFuture<InheritanceBuild> future = A.project.scheduleBuild2(0); InheritanceBuild b = future.get(5, TimeUnit.SECONDS); jRule.assertBuildStatusSuccess(b); //Then, change the label on the Jenkins instance j.setLabelString("test:bar"); //Refresh the node information, to force label re-association j.setNodes(j.getNodes()); //Nuke the buffers, to force label regeneration InheritanceProject.clearBuffers(null); //Build the job again. It must not be able to start, as the labels are wrong future = A.project.scheduleBuild2(0); Thread.sleep(5*1000); Assert.assertFalse( "Job A should not have run, as no host with a correct label is online", future.isDone() ); //Now, change the label and wait for at most 15 seconds for the //label cache to clear and the job to finish j.setLabelString("test:foo"); //Refresh the node information, to force label re-association j.setNodes(j.getNodes()); b = future.get(15, TimeUnit.SECONDS); jRule.assertBuildStatusSuccess(b); } catch (Exception ex) { Assert.fail(String.format( "Got exception during execution of project 'A':\n%s", ex.getMessage() )); } }
/** * This tests the whitespace trimming modes of inheritance parameters * * @throws IOException * @throws TimeoutException * @throws ExecutionException * @throws InterruptedException */ @Test public void testWhitespaces() throws IOException, InterruptedException, ExecutionException, TimeoutException { InheritanceProject ip = jRule.jenkins.createProject( InheritanceProject.class, "WhitespaceProject" ); String pName = "VAR"; String pVal = " A B "; WhitespaceMode[] wsModes = { WhitespaceMode.KEEP, WhitespaceMode.TRIM }; for (WhitespaceMode wsMode : wsModes) { //Creating first with KEEP flag InheritableStringParameterDefinition ispd = new InheritableStringParameterDefinition( "VAR", pVal, "", IModes.OVERWRITABLE, false, false, wsMode, false ); ip.addProperty(new ParametersDefinitionProperty(ispd)); //Build once QueueTaskFuture<InheritanceBuild> future = ip.scheduleBuild2(0, new CLICause()); InheritanceBuild ib = future.get(30, TimeUnit.SECONDS); //Check if parameter kept spaces ParametersAction pa = ib.getAction(ParametersAction.class); Assert.assertNotNull(pa); ParameterValue pv = pa.getParameter(pName); Assert.assertNotNull(pv); //Now, assert the value switch(wsMode) { case KEEP: Assert.assertEquals( "Whitespaces were not kept", pVal, pv.getValue() ); break; case TRIM: Assert.assertEquals( "Whitespaces were not trimmed", StringUtils.trim(pVal), pv.getValue() ); break; default: break; } } }
/** * Used to lock the executors for each available slave assigned to this * build. <br /> * <br /> * <b>(Can be modified to get the auto-generated projects and their * builds)</b> * * @param availableNodes * the available nodes * @param build * the current build * @param stream * the printing stream * @return the locked set of nodes * @throws Exception */ private Set<Node> lockSlaveExecutors(Set<Node> availableNodes, AbstractBuild<?, ?> build, PrintStream stream) throws Exception { ArrayList<Future<FreeStyleBuild>> futureBuildList = new ArrayList<Future<FreeStyleBuild>>(); ArrayList<FreeStyleProject> projectList = new ArrayList<FreeStyleProject>(); Set<Node> nodeSet = new HashSet<Node>(); Computer c = null; for (Node n : availableNodes) { c = n.toComputer(); nodeSet.add(n); for (Executor e : c.getExecutors()) { if (e.isIdle()) { String lockProjectName = NodeUtils.getLockedProjectName( build.getProject().getName(), n, e); Jenkins jenkins = Jenkins.getInstance(); NodeUtils.deleteLockingProject(lockProjectName, stream); FreeStyleProject project = jenkins.createProject( FreeStyleProject.class, lockProjectName); final String projectName = build.getProject().getName(); project.getBuildersList().add( new DTDumbBuilder(projectName)); project.setAssignedNode(n); QueueTaskFuture<FreeStyleBuild> buildFuture = project .scheduleBuild2(0); futureBuildList.add(buildFuture); projectList.add(project); } } } return nodeSet; }