/** * Retrieves variables describing the Run cause. * @param run Run * @return Set of environment variables, which depends on the cause type. */ @Nonnull public static Map<String, String> getCauseEnvVars(@Nonnull Run<?, ?> run) { CauseAction causeAction = run.getAction(CauseAction.class); Map<String, String> env = new HashMap<>(); List<String> directCauseNames = new ArrayList<>(); Set<String> rootCauseNames = new LinkedHashSet<>(); if (causeAction != null) { List<Cause> buildCauses = causeAction.getCauses(); for (Cause cause : buildCauses) { directCauseNames.add(CauseHelper.getTriggerName(cause)); CauseHelper.insertRootCauseNames(rootCauseNames, cause, 0); } } else { directCauseNames.add("UNKNOWN"); rootCauseNames.add("UNKNOWN"); } env.putAll(CauseHelper.buildCauseEnvironmentVariables(ENV_CAUSE, directCauseNames)); env.putAll(CauseHelper.buildCauseEnvironmentVariables(ENV_ROOT_CAUSE, rootCauseNames)); return env; }
/** * Inserts root cause names to the specified target container. * @param causeNamesTarget Target set. May receive null items * @param cause Cause to be added. For {@code Cause.UstreamCause} there will be in-depth search * @param depth Current search depth. {@link #MAX_UPSTREAM_DEPTH} is a limit */ static void insertRootCauseNames(@Nonnull Set<String> causeNamesTarget, @CheckForNull Cause cause, int depth) { if (cause instanceof Cause.UpstreamCause) { if (depth == MAX_UPSTREAM_DEPTH) { causeNamesTarget.add("DEEPLYNESTEDCAUSES"); } else { Cause.UpstreamCause c = (Cause.UpstreamCause) cause; List<Cause> upstreamCauses = c.getUpstreamCauses(); for (Cause upstreamCause : upstreamCauses) insertRootCauseNames(causeNamesTarget, upstreamCause, depth + 1); } } else { //TODO: Accordig to the current design this list may receive null for unknown trigger. Bug? // Should actually return UNKNOWN causeNamesTarget.add(getTriggerName(cause)); } }
@CheckForNull @SuppressWarnings(value = "deprecation") static String getTriggerName(Cause cause) { if (SCMTrigger.SCMTriggerCause.class.isInstance(cause)) { return "SCMTRIGGER"; } else if (TimerTrigger.TimerTriggerCause.class.isInstance(cause)) { return "TIMERTRIGGER"; } else if (Cause.UserIdCause.class.isInstance(cause)) { return "MANUALTRIGGER"; } else if (Cause.UserCause.class.isInstance(cause)) { return "MANUALTRIGGER"; } else if (Cause.UpstreamCause.class.isInstance(cause)) { return "UPSTREAMTRIGGER"; } else if (cause != null) { return cause.getClass().getSimpleName().toUpperCase(Locale.ENGLISH); } return null; }
@Test public void downstreamJobTriggerByRestrictedUser() throws Exception { String allowedUsername = "foo"; UserSelector selector = new UserSelector(allowedUsername); JobRestriction restriction = new StartedByUserRestriction(singletonList(selector), false, false, false); setUpDiskPoolRestriction(restriction); authenticate(allowedUsername); WorkflowRun upstreamRun = createWorkflowJobAndRun(); j.assertBuildStatusSuccess(upstreamRun); j.assertLogContains(format("Selected Disk ID '%s' from the Disk Pool ID '%s'", DISK_ID_ONE, DISK_POOL_ID), upstreamRun); String notAllowedUsername = "bar"; authenticate(notAllowedUsername); WorkflowJob downstreamJob = j.jenkins.createProject(WorkflowJob.class, randomAlphanumeric(7)); downstreamJob.setDefinition(new CpsFlowDefinition(format("" + "def run = selectRun '%s' \n" + "exwsAllocate selectedRun: run", upstreamRun.getParent().getFullName()))); WorkflowRun downstreamRun = downstreamJob.scheduleBuild2(0, new CauseAction(new Cause.UserIdCause())).get(); j.assertBuildStatus(Result.FAILURE, downstreamRun); j.assertLogContains(format("Disk Pool identified by '%s' is not accessible due to the applied Disk Pool restriction: Started By User", DISK_POOL_ID), downstreamRun); }
/** * Also accepts variable expression. */ @Test public void testVariableExpression() throws Exception { FreeStyleProject jobToSelect = j.createFreeStyleProject(); Run runToSelect = j.assertBuildStatusSuccess(jobToSelect.scheduleBuild2(0)); FreeStyleProject selecter = j.createFreeStyleProject(); RunSelector selector = new ParameterizedRunSelector("${SELECTOR}"); Run run = j.assertBuildStatusSuccess(selecter.scheduleBuild2( 0, (Cause) null, new ParametersAction(new StringParameterValue( "SELECTOR", "<StatusRunSelector><buildStatus>STABLE</buildStatus></StatusRunSelector>" )) )); Run selectedRun = selector.select(jobToSelect, new RunSelectorContext(j.jenkins, run, TaskListener.NULL)); assertThat(selectedRun, is(runToSelect)); }
@Override public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException { for (Cause.UpstreamCause c: Util.filter(build.getCauses(), Cause.UpstreamCause.class)) { Job<?,?> upstreamProject = Jenkins.getInstance().getItemByFullName(c.getUpstreamProject(), Job.class); if (upstreamProject == null) { listener.getLogger().println(String.format("Not Found: %s", c.getUpstreamProject())); continue; } Run<?,?> upstreamBuild = upstreamProject.getBuildByNumber(c.getUpstreamBuild()); if (upstreamBuild == null) { listener.getLogger().println(String.format("Not Found: %s - %d", upstreamProject.getFullName(), c.getUpstreamBuild())); continue; } listener.getLogger().println(String.format("Removed: %s - %s", upstreamProject.getFullName(), upstreamBuild.getFullDisplayName())); upstreamBuild.delete(); } return true; }
@SuppressFBWarnings("SE_BAD_FIELD") public static boolean cancelQueuedBuild(WorkflowJob job, Build build) { String buildUid = build.getMetadata().getUid(); final Queue buildQueue = Jenkins.getActiveInstance().getQueue(); for (final Queue.Item item : buildQueue.getItems()) { for (Cause cause : item.getCauses()) { if (cause instanceof BuildCause && ((BuildCause) cause).getUid().equals(buildUid)) { return ACL.impersonate(ACL.SYSTEM, new NotReallyRoleSensitiveCallable<Boolean, RuntimeException>() { @Override public Boolean call() throws RuntimeException { buildQueue.cancel(item); return true; } }); } } } return cancelNotYetStartedBuild(job, build); }
public void started(AbstractBuild build) { CauseAction causeAction = build.getAction(CauseAction.class); if (causeAction != null) { Cause scmCause = causeAction.findCause(SCMTrigger.SCMTriggerCause.class); if (scmCause == null) { MessageBuilder message = new MessageBuilder(notifier, build); message.append(causeAction.getShortDescription()); notifyStart(build, message.appendOpenLink().toString()); // Cause was found, exit early to prevent double-message return; } } String changes = getChanges(build, notifier.includeCustomMessage()); if (changes != null) { notifyStart(build, changes); } else { notifyStart(build, getBuildStatusMessage(build, false, false,notifier.includeCustomMessage())); } }
private static Cause.UpstreamCause getUpstreamCause(Run run) { if (run == null) { return null; } List<Cause> causes = run.getCauses(); for (Cause cause : causes) { if (cause instanceof Cause.UpstreamCause) { return (Cause.UpstreamCause)cause; } } return null; }
public void doParamsSubmit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { List<BuildTargetParameter> buildTargetParams; TargetParameterBuildAction paramAction; JSONObject jsonObject; TargetBuildParameterUtil buildParamUtil = new TargetBuildParameterUtil(); jsonObject = req.getSubmittedForm(); buildTargetParams = buildParamUtil.parse(jsonObject); if (buildTargetParams == null) { rsp.sendRedirect(400, "Invalid Parameters - All Fields must be filed"); return; } else { paramAction = new TargetParameterBuildAction(); paramAction.setBaseBranch(jsonObject.getString("baseBranch")); paramAction.setParameters(buildTargetParams); Hudson.getInstance().getQueue().schedule2(project, 0, paramAction, new CauseAction(new Cause.UserIdCause())); } rsp.sendRedirect("../"); }
public void started(AbstractBuild build) { //AbstractProject<?, ?> project = build.getProject(); CauseAction causeAction = build.getAction(CauseAction.class); if (causeAction != null) { Cause scmCause = causeAction.findCause(SCMTrigger.SCMTriggerCause.class); if (scmCause == null) { MessageBuilder message = new MessageBuilder(notifier, build); message.append(causeAction.getShortDescription()); notifyStart(build, message.appendOpenLink().toString()); // Cause was found, exit early to prevent double-message return; } } String changes = getChanges(build, notifier.includeCustomAttachmentMessage()); if (changes != null) { notifyStart(build, changes); } else { notifyStart(build, getBuildStatusMessage(build, false, notifier.includeCustomAttachmentMessage())); } }
@Override public boolean isUnblocked(Queue.Item item) { final List<Cause> causes = item.getCauses(); for (Cause cause : causes) { if (cause instanceof GitHubPRCause) { final GitHubPRCause gitHubPRCause = (GitHubPRCause) cause; final Set<String> causeLabels = gitHubPRCause.getLabels(); if (getLabel() != null) { if (causeLabels.containsAll(label.getLabelsSet())) { if (item.task instanceof Job<?, ?>) { final Job<?, ?> job = (Job<?, ?>) item.task; LOGGER.debug("Unblocking job item {} with matched labels {}", job.getFullName(), label.getLabelsSet()); } return true; } } } } return false; }
/** * Cancel previous builds for specified PR id. */ private static boolean cancelQueuedBuildByBranchName(final String branch) { Queue queue = getJenkinsInstance().getQueue(); for (Queue.Item item : queue.getApproximateItemsQuickly()) { Optional<Cause> cause = from(item.getAllActions()) .filter(instanceOf(CauseAction.class)) .transformAndConcat(new CausesFromAction()) .filter(instanceOf(GitHubBranchCause.class)) .firstMatch(new CauseHasBranch(branch)); if (cause.isPresent()) { queue.cancel(item); return true; } } return false; }
@Test public void testSimpleWithDefaultParameter() throws Exception { writeResourceToFile("param.yaml"); assertEquals(0, underTest.getItems().size()); YamlBuild build = underTest.scheduleBuild2(0, new Cause.LegacyCodeCause()).get(); dumpLog(build); assertEquals(Result.SUCCESS, build.getResult()); assertThat(CharStreams.toString(new InputStreamReader( build.getLogInputStream())), // Check that we wrote the default value. containsString("bar")); }
@Test public void testSimpleWithParameter() throws Exception { writeResourceToFile("param.yaml"); assertEquals(0, underTest.getItems().size()); ParametersAction parameters = new ParametersAction( new StringParameterValue("foo", "baz")); YamlBuild build = underTest.scheduleBuild2(0, new Cause.LegacyCodeCause(), parameters).get(); dumpLog(build); assertEquals(Result.SUCCESS, build.getResult()); assertThat(CharStreams.toString(new InputStreamReader( build.getLogInputStream())), // Check that we wrote the passed in parameter instead // of the default value. containsString("baz")); }
/** {@inheritDoc} */ @Override protected Result doRun(BuildListener listener) throws IOException, InterruptedException { // Attach an SCMRevisionAction with our revision { final SCMHead head = getParent().getBranch().getHead(); final SCMSource source = getParent().getSource(); final SCMRevision revision = source.fetch(head, listener); TestBuild.this.addAction(new SCMRevisionAction(checkNotNull(revision))); } try { project.innerItem.scheduleBuild2(0, new Cause.UpstreamCause(TestBuild.this)).get(); } catch (ExecutionException e) { return Result.FAILURE; } return Result.SUCCESS; }
private static List<GitLabBranchBuild> findBuildsFromUpstreamCauses(List<Cause> causes) { for (Cause cause : causes) { if (cause instanceof UpstreamCause) { List<Cause> upCauses = ((UpstreamCause) cause).getUpstreamCauses(); // Non null, returns empty list when none are set for (Cause upCause : upCauses) { if (upCause instanceof GitLabWebHookCause) { GitLabWebHookCause gitlabCause = (GitLabWebHookCause) upCause; return Collections.singletonList( new GitLabBranchBuild(gitlabCause.getData().getSourceProjectId().toString(), gitlabCause.getData().getLastCommit())); } } List<GitLabBranchBuild> builds = findBuildsFromUpstreamCauses(upCauses); if (!builds.isEmpty()) { return builds; } } } return Collections.emptyList(); }
@Test public void shouldNotTriggerJobIfNoChange() throws Exception { FreeStyleProject project = jenkins.createFreeStyleProject("NotTriggerJobIfNoChange"); StaticWorkspaceImpl workspace = new StaticWorkspaceImpl("none", false, defaultClient()); Populate populate = new AutoCleanImpl(true, true, false, false, null, null); PerforceScm scm = new PerforceScm(auth.getId(), workspace, populate); project.setScm(scm); P4Trigger trigger = new P4Trigger(); trigger.start(project, false); project.addTrigger(trigger); project.save(); // Run once jenkins.assertBuildStatusSuccess(project.scheduleBuild2(0, new Cause.UserIdCause())); // Test trigger trigger.poke(project, auth.getP4port()); TimeUnit.SECONDS.sleep(project.getQuietPeriod()); jenkins.waitUntilNoActivity(); assertEquals("Shouldn't have triggered a build if no change", 1, project.getLastBuild().getNumber()); }
@Test public void testFreeStyleProject_buildCounter() throws Exception { FreeStyleProject project = jenkins.createFreeStyleProject("BuildCounter"); StaticWorkspaceImpl workspace = new StaticWorkspaceImpl("none", false, defaultClient()); String pin = "testCounter"; Populate populate = new AutoCleanImpl(false, false, false, true, pin, null); PerforceScm scm = new PerforceScm(CREDENTIAL, workspace, populate); project.setScm(scm); project.save(); // Log in and create counter for test P4PasswordImpl admin = createCredentials("admin", "Password", p4d); ClientHelper p4 = new ClientHelper(admin, null, "manual.ws", "utf8"); IOptionsServer iserver = p4.getConnection(); CounterOptions opts = new CounterOptions(); iserver.setCounter("testCounter", "9", opts); Cause.UserIdCause cause = new Cause.UserIdCause(); FreeStyleBuild build = project.scheduleBuild2(0, cause).get(); assertEquals(Result.SUCCESS, build.getResult()); List<String> log = build.getLog(LOG_LIMIT); assertTrue(log.contains("P4 Task: syncing files at change: 9")); }
@Test public void testFreeStyleProject_buildHead() throws Exception { FreeStyleProject project = jenkins.createFreeStyleProject("BuildHead"); Workspace workspace = new StaticWorkspaceImpl("none", false, defaultClient()); Populate populate = new AutoCleanImpl(); PerforceScm scm = new PerforceScm(CREDENTIAL, workspace, populate); project.setScm(scm); project.save(); FreeStyleBuild build; UserIdCause cause = new Cause.UserIdCause(); build = project.scheduleBuild2(0, cause).get(); assertEquals(Result.SUCCESS, build.getResult()); List<String> log = build.getLog(LOG_LIMIT); assertTrue(log.contains("P4 Task: syncing files at change: 40")); CredentialsDescriptor desc = auth.getDescriptor(); assertNotNull(desc); assertEquals("Perforce Password Credential", desc.getDisplayName()); P4PasswordImpl.DescriptorImpl impl = (P4PasswordImpl.DescriptorImpl) desc; FormValidation form = impl.doTestConnection(p4d.getRshPort(), "false", null, null, "jenkins", "jenkins", false); assertEquals(FormValidation.Kind.OK, form.kind); }
@Test public void should_get_cause_from_dbObject() throws Exception { BasicDBObject cause1DbObject = new BasicDBObject("cause1", "cause1"); DBObject causes = new BasicDBObjectBuilder().add("causes", Arrays.asList(cause1DbObject)).get(); Mapper mapper = Mockito.mock(Mapper.class); Cause cause1 = new NullBuildCause(); when(mapper.fromDBObject(null, cause1DbObject, null)).thenReturn(cause1); CauseActionConverter converter = new CauseActionConverter(); converter.setMapper(mapper); CauseAction action = converter.decode(CauseAction.class, causes, Mockito.mock(MappedField.class)); Assert.assertEquals(1, action.getCauses().size()); Assert.assertEquals(cause1, action.getCauses().get(0)); }
@Test public void should_convert_cause_action_to_old_format() throws Exception { Cause cause1 = new NullBuildCause(); Mapper mapper = Mockito.mock(Mapper.class); when(mapper.toDBObject(cause1)).thenReturn(new BasicDBObject("cause1", "cause1")); CauseAction causeAction = new CauseAction(cause1); CauseActionConverter converter = new CauseActionConverter(); converter.setMapper(mapper); DBObject dbObject = (DBObject) converter.encode(causeAction, null); Assert.assertEquals(dbObject.get("className"), CauseAction.class.getName()); Assert.assertNotNull(dbObject.get("causes")); List dbCauses = ((List) dbObject.get("causes")); Assert.assertEquals(1, dbCauses.size()); Assert.assertEquals("cause1", ((BasicDBObject) dbCauses.get(0)).get("cause1")); }
@Override public void triggerRebuild(String projectName, String buildId) { AbstractProject project = ProjectUtil.getProject(projectName, Jenkins.getInstance()); if (!project.hasPermission(Item.BUILD)) { throw new BadCredentialsException("Not authorized to trigger build"); } AbstractBuild build = project.getBuildByNumber(Integer.parseInt(buildId)); @SuppressWarnings("unchecked") List<Cause> prevCauses = build.getCauses(); List<Cause> newCauses = new ArrayList<>(); for (Cause cause : prevCauses) { if (!(cause instanceof Cause.UserIdCause)) { newCauses.add(cause); } } newCauses.add(new Cause.UserIdCause()); CauseAction causeAction = new CauseAction(newCauses); project.scheduleBuild2(project.getQuietPeriod(),null, causeAction, build.getAction(ParametersAction.class)); }
public static boolean isQueued(AbstractProject project, AbstractBuild firstBuild) { if (!project.isInQueue()) { return false; } else if (firstBuild == null) { return true; } List<Cause.UpstreamCause> causes = Util.filter(project.getQueueItem().getCauses(), Cause.UpstreamCause.class); @SuppressWarnings("unchecked") List<AbstractProject<?,?>> upstreamProjects = project.getUpstreamProjects(); for (AbstractProject<?, ?> upstreamProject : upstreamProjects) { AbstractBuild upstreamBuild = BuildUtil.match(upstreamProject.getBuilds(), firstBuild); if (upstreamBuild != null) { for (Cause.UpstreamCause upstreamCause : causes) { if (upstreamBuild.getNumber() == upstreamCause.getUpstreamBuild() && upstreamProject.getRelativeNameFrom(JenkinsUtil.getInstance()).equals( upstreamCause.getUpstreamProject())) { return true; } } } } return false; }
@CheckForNull public static AbstractBuild getUpstreamBuild(AbstractBuild build) { List<CauseAction> actions = build.getActions(CauseAction.class); for (CauseAction action : actions) { List<Cause.UpstreamCause> causes = Util.filter(action.getCauses(), Cause.UpstreamCause.class); if (!causes.isEmpty()) { Cause.UpstreamCause upstreamCause = causes.get(0); AbstractProject upstreamProject = JenkinsUtil.getInstance().getItemByFullName( upstreamCause.getUpstreamProject(), AbstractProject.class); //Due to https://issues.jenkins-ci.org/browse/JENKINS-14030 when a project has been renamed triggers // are not updated correctly if (upstreamProject == null) { return null; } return upstreamProject.getBuildByNumber(upstreamCause.getUpstreamBuild()); } } return null; }
public static List<TriggerCause> getTriggeredBy(Job project, Run<?, ?> build) { Set<TriggerCause> result = new HashSet<>(); List<Cause> causes; if (build == null && project.isInQueue()) { causes = project.getQueueItem().getCauses(); } else { if (build != null) { causes = build.getCauses(); } else { return new ArrayList<>(); } } for (Cause cause : causes) { result.add(CauseResolver.getTrigger(cause)); } return new ArrayList<>(result); }
@Test public void testGetTriggeredByUpStreamJob() throws Exception { FreeStyleProject upstream = jenkins.createFreeStyleProject("up"); jenkins.setQuietPeriod(0); jenkins.buildAndAssertSuccess(upstream); FreeStyleProject project = jenkins.createFreeStyleProject("build"); FakeRepositoryBrowserSCM scm = new FakeRepositoryBrowserSCM(); scm.addChange().withAuthor("test-user").withMsg("Fixed bug"); project.setScm(scm); project.scheduleBuild(new Cause.UpstreamCause((Run)upstream.getLastBuild())); jenkins.waitUntilNoActivity(); List<TriggerCause> triggeredBy = TriggerCause.getTriggeredBy(project, project.getLastBuild()); assertEquals(1, triggeredBy.size()); assertEquals(TriggerCause.TYPE_UPSTREAM, triggeredBy.iterator().next().getType()); assertEquals("upstream project up build #1", triggeredBy.iterator().next().getDescription()); }
/** * Return the current build user. * * @param causes * build causes. * @return user name. */ protected static String prepareBuildUser(List<Cause> causes) { String buildUser = "anonymous"; if (causes != null && causes.size() > 0) { if (causes.get(0) instanceof UserIdCause) { buildUser = ((UserIdCause) causes.get(0)).getUserName(); } else if (causes.get(0) instanceof UpstreamCause) { List<Cause> upstreamCauses = ((UpstreamCause) causes.get(0)).getUpstreamCauses(); prepareBuildUser(upstreamCauses); } } return buildUser; }
private void startJob() { Cause cause = new Cause.RemoteCause("SQSTrigger", String.format("User invoked: %s", this.userarns)); //Job Build can be triggered by 1+ SQS messages because of quiet-period in Jenkins, @see https://jenkins.io/blog/2010/08/11/quiet-period-feature/ boolean scheduled = job.scheduleBuild(cause); this.log.info("The build is scheduled? %s by Message: %s", scheduled, this.messageId); }
@Test public void shouldPassIt() throws Exception { this.mockAwsSqs.sendMessage(this.fixture.getSqsMessage()); this.submitAndAssertFixture(this.fixture); Cause cause = this.fixture.getLastBuild().getCauses().get(0); Assertions.assertThat(cause).isNotNull(); Assertions.assertThat(cause.getShortDescription()).contains("User invoked:"); }
/** * Return the current build user. * * @param causes build causes. * @return user name. */ protected static String prepareBuildUser(List<Cause> causes) { String buildUser = "anonymous"; if (causes != null && causes.size() > 0) { if (causes.get(0) instanceof UserIdCause) { buildUser = ((UserIdCause) causes.get(0)).getUserId(); } else if (causes.get(0) instanceof UpstreamCause) { List<Cause> upstreamCauses = ((UpstreamCause) causes.get(0)).getUpstreamCauses(); prepareBuildUser(upstreamCauses); } } return Util.fixEmpty(buildUser) == null ? "anonymous" : buildUser; }
/** * Return the current build user. * * @param causes build causes. * @return user name. */ protected static String prepareBuildUser(List<Cause> causes) { String buildUser = "anonymous"; if (causes != null && causes.size() > 0) { if (causes.get(0) instanceof UserIdCause) { buildUser = ((UserIdCause) causes.get(0)).getUserName(); } else if (causes.get(0) instanceof UpstreamCause) { List<Cause> upstreamCauses = ((UpstreamCause) causes.get(0)).getUpstreamCauses(); prepareBuildUser(upstreamCauses); } } return buildUser; }
private static WorkflowRun createWorkflowJobAndRun(String jobName) throws Exception { WorkflowJob job = j.jenkins.createProject(WorkflowJob.class, jobName); job.setDefinition(new CpsFlowDefinition(format("exwsAllocate diskPoolId: '%s'", DISK_POOL_ID))); Future<WorkflowRun> runFuture = job.scheduleBuild2(0, new CauseAction(new Cause.UserIdCause())); assertThat(runFuture, notNullValue()); return runFuture.get(); }
@Test public void testDisplayName() throws Exception { jobToSelect.getBuildByNumber(2).setDisplayName("RC1"); FreeStyleProject selecter = j.createFreeStyleProject(); RunSelector selector = new StatusRunSelector(); RunFilter filter = new DisplayNameRunFilter("$NUM"); Run run = j.assertBuildStatusSuccess(selecter.scheduleBuild2( 0, new Cause.UserIdCause(), new ParametersAction( new StringParameterValue("NUM", "RC1") ) )); Run selectedRun = selector.select(jobToSelect, new RunSelectorContext(j.jenkins, run, TaskListener.NULL, filter)); assertThat(selectedRun.getNumber(), is(2)); run = j.assertBuildStatusSuccess(selecter.scheduleBuild2( 0, new Cause.UserIdCause(), new ParametersAction( new StringParameterValue("NUM", "RC2") ) )); selectedRun = selector.select(jobToSelect, new RunSelectorContext(j.jenkins, run, TaskListener.NULL, filter)); assertThat(selectedRun, nullValue()); }
public static void cancelQueuedBuilds(WorkflowJob job, String bcUid) { Queue buildQueue = Jenkins.getActiveInstance().getQueue(); for (Queue.Item item : buildQueue.getItems()) { for (Cause cause : item.getCauses()) { if (cause instanceof BuildCause) { BuildCause buildCause = (BuildCause) cause; if (buildCause.getBuildConfigUid().equals(bcUid)) { Build build = new BuildBuilder().withNewMetadata().withNamespace(buildCause.getNamespace()) .withName(buildCause.getName()).and().build(); cancelQueuedBuild(job, build); } } } } }
private static boolean isOpenShiftBuildCause(List<Action> actions) { for (Action action : actions) { if (action instanceof CauseAction) { CauseAction causeAction = (CauseAction) action; for (Cause cause : causeAction.getCauses()) { if (cause instanceof BuildCause) { return true; } } } } return false; }
private static CauseAction dumpCause(List<Action> actions) { for (Action action : actions) { if (action instanceof CauseAction) { CauseAction causeAction = (CauseAction) action; if (LOGGER.isLoggable(Level.FINE)) for (Cause cause : causeAction.getCauses()) { LOGGER.fine("cause: " + cause.getShortDescription()); } return causeAction; } } return null; }
public GogsResults triggerJobs(String jobName, String deliveryID) { SecurityContext saveCtx = null; GogsResults result = new GogsResults(); try { saveCtx = SecurityContextHolder.getContext(); Jenkins instance = Jenkins.getActiveInstance(); if (instance!=null) { ACL acl = instance.getACL(); acl.impersonate(ACL.SYSTEM); BuildableItem project = GogsUtils.find(jobName, BuildableItem.class); if (project != null) { Cause cause = new GogsCause(deliveryID); project.scheduleBuild(0, cause); result.setMessage(String.format("Job '%s' is executed",jobName)); } else { String msg = String.format("Job '%s' is not defined in Jenkins",jobName); result.setStatus(404, msg); LOGGER.warning(msg); } } } catch (Exception e) { } finally { SecurityContextHolder.setContext(saveCtx); } return result; }