/** * 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; }
@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); }
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())); } }
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())); } }
/** * 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 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)); }
@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; }
@Test @Issue("JENKINS-22611") public void testGetTriggeredByMultipleSCMChange() throws Exception { FreeStyleProject project = jenkins.createFreeStyleProject("build"); FakeRepositoryBrowserSCM scm = new FakeRepositoryBrowserSCM(); scm.addChange().withAuthor("test-user").withMsg("Fixed bug"); project.setScm(scm); jenkins.setQuietPeriod(0); CauseAction action = new CauseAction(new SCMTrigger.SCMTriggerCause("")); action.getCauses().add(new SCMTrigger.SCMTriggerCause("")); action.getCauses().add(new SCMTrigger.SCMTriggerCause("")); action.getCauses().add(new SCMTrigger.SCMTriggerCause("")); project.scheduleBuild(0, null, action); jenkins.waitUntilNoActivity(); List<TriggerCause> triggeredBy = TriggerCause.getTriggeredBy(project, project.getLastBuild()); assertEquals(1, triggeredBy.size()); assertEquals(TriggerCause.TYPE_SCM, triggeredBy.iterator().next().getType()); }
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(); }
static synchronized void initialize() { if (buildToParametersMap == null) { buildToParametersMap = new ConcurrentHashMap<String, ParametersAction>(); } if (buildToCauseMap == null) { buildToCauseMap = new ConcurrentHashMap<String, CauseAction>(); } }
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; }
@VisibleForTesting static Run<?, ?> getUpstreamRun(AbstractBuild build) { CauseAction action = build.getAction(hudson.model.CauseAction.class); if (action != null) { Cause.UpstreamCause upstreamCause = action.findCause(hudson.model.Cause.UpstreamCause.class); if (upstreamCause != null) { return upstreamCause.getUpstreamRun(); } } return null; }
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; }
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); }
/** * Potentially recursively walk the upstream builds until we find one that * originates from {@code parentProject}. * * @param parentProject The containing project from which we inherit our * actual {@link SCM} * @param build The build we are tracing back to its possible origin at * {@code parentProject}. * @return The build of {@code parentProject} that (possibly transititvely) * caused {@code build}. */ private AbstractBuild getParentBuild(T parentProject, AbstractBuild build) { for (final CauseAction action : build.getActions(CauseAction.class)) { for (final Cause cause : action.getCauses()) { if (!(cause instanceof Cause.UpstreamCause)) { continue; } final Cause.UpstreamCause upstreamCause = (Cause.UpstreamCause) cause; // If our parent project caused this build, then return its build that // triggered this. final String upstreamProjectName = parentProject.getFullName(); final AbstractProject causeProject = ((AbstractProject) checkNotNull(Jenkins.getInstance()) .getItemByFullName(upstreamCause.getUpstreamProject())); if (causeProject == null) { throw new IllegalStateException( "Unable to lookup upstream cause project"); } AbstractBuild causeBuild = causeProject.getBuildByNumber( upstreamCause.getUpstreamBuild()); if (upstreamCause.getUpstreamProject().equals(upstreamProjectName)) { return causeBuild; } // Otherwise, see if the build that triggered our build was triggered by // our parent project (transitively) causeBuild = getParentBuild(parentProject, causeBuild); if (causeBuild != null) { return causeBuild; } } } throw new IllegalStateException(Messages.DelegateSCM_NoParentBuild()); }
private void handleMergeRequest(Job<?, ?> job, PushHook hook, boolean ciSkip, BranchFilter branchFilter, GitLabClient client, MergeRequest mergeRequest) { if (ciSkip && mergeRequest.getDescription() != null && mergeRequest.getDescription().contains("[ci-skip]")) { LOGGER.log(Level.INFO, "Skipping MR " + mergeRequest.getTitle() + " due to ci-skip."); return; } Boolean workInProgress = mergeRequest.getWorkInProgress(); if (skipWorkInProgressMergeRequest && workInProgress != null && workInProgress) { LOGGER.log(Level.INFO, "Skip WIP Merge Request #{0} ({1})", toArray(mergeRequest.getIid(), mergeRequest.getTitle())); return; } String targetBranch = mergeRequest.getTargetBranch(); String sourceBranch = mergeRequest.getSourceBranch(); if (targetBranch != null && branchFilter.isBranchAllowed(targetBranch) && hook.getRef().equals("refs/heads/"+targetBranch) && sourceBranch != null) { LOGGER.log(Level.INFO, "{0} triggered for push to target branch of open merge request #{1}.", LoggerUtil.toArray(job.getFullName(), mergeRequest.getId())); Branch branch = client.getBranch(mergeRequest.getSourceProjectId().toString(), sourceBranch); Project project = client.getProject(mergeRequest.getSourceProjectId().toString()); String commit = branch.getCommit().getId(); setCommitStatusPendingIfNecessary(job, mergeRequest.getSourceProjectId(), commit, branch.getName()); List<Action> actions = Arrays.<Action>asList(new CauseAction(new GitLabWebHookCause(retrieveCauseData(hook, project, mergeRequest, branch))), new RevisionParameterAction(commit, retrieveUrIish(hook))); scheduleBuild(job, actions.toArray(new Action[actions.size()])); } }
protected Action[] createActions(Job<?, ?> job, H hook) { ArrayList<Action> actions = new ArrayList<>(); actions.add(new CauseAction(new GitLabWebHookCause(retrieveCauseData(hook)))); try { SCMTriggerItem item = SCMTriggerItem.SCMTriggerItems.asSCMTriggerItem(job); GitSCM gitSCM = getGitSCM(item); actions.add(createRevisionParameter(hook, gitSCM)); } catch (NoRevisionToBuildException e) { LOGGER.log(Level.WARNING, "unknown handled situation, dont know what revision to build for req {0} for job {1}", new Object[]{hook, (job != null ? job.getFullName() : null)}); } return actions.toArray(new Action[actions.size()]); }
public void doBuild(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { project.checkPermission(AbstractProject.BUILD); List<ParameterValue> values = new ArrayList<ParameterValue>(); List<ParameterDefinition> defs = new ArrayList<ParameterDefinition>(); Enumeration<?> names = req.getParameterNames(); while (names.hasMoreElements()) { String name = (String) names.nextElement(); defs.add(new StringParameterDefinition(name, null)); } for (ParameterDefinition d : defs) { StringParameterValue value = (StringParameterValue) d.createValue(req); if (value != null && value.value != null && !value.value.isEmpty()) { values.add(value); } } // Schedule build TimeDuration delay = new TimeDuration(project.getQuietPeriod()); CauseAction cause = new CauseAction(new Cause.UserIdCause()); List<ParameterValue> internalParams = extractAndRemoveInternalParameters(values); ParametersAction params = new SafeParametersAction(values, internalParams); Jenkins j = Jenkins.getInstance(); if (j != null) { Queue queue = j.getQueue(); queue.schedule(project, delay.getTime(), params, cause); // send the user back to the job top page. rsp.sendRedirect("../"); } }
@Override public CauseAction decode(final Class targetClass, final Object fromDBObject, final MappedField optionalExtraInfo) { try (ACLContext _ = ACL.as(Jenkins.ANONYMOUS)) { if (fromDBObject == null) return null; final List causes = new ArrayList(); final List rawList = (List) ((DBObject) fromDBObject).get("causes"); for (final Object obj : rawList) { final DBObject dbObj = (DBObject) obj; final Object cause = getMapper().fromDBObject(optionalExtraInfo.getSubClass(), dbObj, getMapper().createEntityCache()); causes.add(cause); } return new CauseAction(causes); } }
@Override public Object encode(final Object value, final MappedField optionalExtraInfo) { if (value == null) return null; final CauseAction action = (CauseAction) value; final List causes = new BasicDBList(); for (final Object obj : action.getCauses()) { causes.add(getMapper().toDBObject(obj)); } return BasicDBObjectBuilder.start("causes", causes).add("className", CauseAction.class.getName()).get(); }
private Class getClass(final DBObject dbObj) { // see if there is a className value final String className = (String) dbObj.get(Mapper.CLASS_NAME_FIELDNAME); if (className != null && className.equals(CauseAction.class.getName())) { // try to Class.forName(className) as defined in the dbObject first, // otherwise return the entityClass try { return Class.forName(className, true, getClassLoaderForClass(className, dbObj)); } catch (final ClassNotFoundException e) { //Ignore if notfound } } return null; }
public void addCause(final Cause manualCause) { final List<Cause> exisitingCauses = this.getAction(CauseAction.class).getCauses(); final ArrayList<Cause> causes = new ArrayList<>(); causes.add(manualCause); causes.addAll(exisitingCauses); this.replaceAction(new CauseAction(causes)); }
public boolean scheduleBuild(final List<? extends Action> actions, final Cause c) { final List<Action> allActions = new ArrayList<>(); if (actions != null) { allActions.addAll(actions); } allActions.add(new CauseAction(c)); return Jenkins.getInstance().getQueue().schedule(this, getQuietPeriod(), allActions) != null; }
@Test public void should_set_building_status_on_queue_enter() throws IOException { final GHRepository githubRepository = mock(GHRepository.class); final CommitStatusUpdateQueueListener commitStatusUpdateQueueListener = new CommitStatusUpdateQueueListener() { @Override protected GHRepository getGithubRepository(final DynamicProject project) { return githubRepository; } @Override protected String getJenkinsRootUrl() { return "jenkins.root.url"; } }; final BuildCause buildCause = mock(BuildCause.class); final ArrayList<Action> causeActions = new ArrayList<>(); causeActions.add(new CauseAction(buildCause)); final Queue.WaitingItem queueItem = new Queue.WaitingItem(null, mock(DynamicProject.class), causeActions); when(buildCause.getSha()).thenReturn("sha"); commitStatusUpdateQueueListener.onEnterWaiting(queueItem); verify(githubRepository).createCommitStatus("sha", GHCommitState.PENDING, "jenkins.root.url", "Build in queue.", "DotCi/push"); }
@Test public void testGetUpstreamBuildProjectRenamed() { AbstractBuild build = mock(AbstractBuild.class); List<CauseAction> causeActions = new ArrayList<>(); Cause.UpstreamCause cause = mock(Cause.UpstreamCause.class); when(cause.getUpstreamProject()).thenReturn("thisprojectdontexists"); causeActions.add(new CauseAction(cause)); when(build.getActions(CauseAction.class)).thenReturn(causeActions); assertNull(BuildUtil.getUpstreamBuild(build)); }
public boolean isForced() { for (Action action : build.getActions()) { if (action instanceof CauseAction) { for (Object cause : ((CauseAction) action).getCauses()) { if (cause instanceof Cause.UserCause) { return true; } } } } return false; }
static synchronized void addCauseAction(String buildId, CauseAction cause) { buildToCauseMap.put(buildId, cause); }
static synchronized CauseAction removeCauseAction(String buildId) { return buildToCauseMap.remove(buildId); }
@Override public boolean shouldSchedule(Queue.Task p, List<Action> actions) { if (p instanceof WorkflowJob && !isOpenShiftBuildCause(actions)) { WorkflowJob wj = (WorkflowJob) p; BuildConfigProjectProperty buildConfigProjectProperty = wj .getProperty(BuildConfigProjectProperty.class); if (buildConfigProjectProperty != null && StringUtils.isNotBlank(buildConfigProjectProperty .getNamespace()) && StringUtils.isNotBlank(buildConfigProjectProperty .getName())) { String namespace = buildConfigProjectProperty.getNamespace(); String jobURL = joinPaths( getJenkinsURL(getAuthenticatedOpenShiftClient(), namespace), wj.getUrl()); Build ret = getAuthenticatedOpenShiftClient() .buildConfigs() .inNamespace(namespace) .withName(buildConfigProjectProperty.getName()) .instantiate( new BuildRequestBuilder() .withNewMetadata() .withName( buildConfigProjectProperty .getName()) .and() .addNewTriggeredBy() .withMessage( "Triggered by Jenkins job at " + jobURL).and().build()); ParametersAction params = dumpParams(actions); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("ParametersAction: " + params.toString()); } if (params != null && ret != null) BuildToActionMapper.addParameterAction(ret.getMetadata() .getName(), params); CauseAction cause = dumpCause(actions); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("get CauseAction: " + cause.getDisplayName()); for (Cause c : cause.getCauses()) { LOGGER.fine("Cause: " + c.getShortDescription()); } } if (cause != null && ret != null) BuildToActionMapper.addCauseAction(ret.getMetadata() .getName(), cause); return false; } } return true; }
/** * The maven-war-app has a dependency on the maven-jar-app */ @Test public void verify_downstream_multi_branch_pipeline_trigger() throws Exception { System.out.println("gitRepoRule: " + gitRepoRule); loadMavenJarProjectInGitRepo(this.gitRepoRule); System.out.println("downstreamArtifactRepoRule: " + downstreamArtifactRepoRule); loadMavenWarProjectInGitRepo(this.downstreamArtifactRepoRule); String script = "node('master') {\n" + " checkout scm\n" + " withMaven() {\n" + " sh 'mvn install'\n" + " }\n" + "}"; gitRepoRule.write("Jenkinsfile", script); gitRepoRule.git("add", "Jenkinsfile"); gitRepoRule.git("commit", "--message=jenkinsfile"); downstreamArtifactRepoRule.write("Jenkinsfile", script); downstreamArtifactRepoRule.git("add", "Jenkinsfile"); downstreamArtifactRepoRule.git("commit", "--message=jenkinsfile"); // TRIGGER maven-jar#1 to record that "build-maven-jar" generates this jar and install this maven jar in the local maven repo WorkflowMultiBranchProject mavenJarPipeline = jenkinsRule.createProject(WorkflowMultiBranchProject.class, "build-maven-jar"); mavenJarPipeline.addTrigger(new WorkflowJobDependencyTrigger()); mavenJarPipeline.getSourcesList().add(new BranchSource(new GitSCMSource(null, gitRepoRule.toString(), "", "*", "", false))); System.out.println("trigger maven-jar#1..."); WorkflowJob mavenJarPipelineMasterPipeline = WorkflowMultibranchProjectTestsUtils.scheduleAndFindBranchProject(mavenJarPipeline, "master"); assertEquals(1, mavenJarPipeline.getItems().size()); System.out.println("wait for maven-jar#1..."); jenkinsRule.waitUntilNoActivity(); assertThat(mavenJarPipelineMasterPipeline.getLastBuild().getNumber(), is(1)); // TODO check in DB that the generated artifact is recorded // TRIGGER maven-war#1 to record that "build-maven-war" has a dependency on "build-maven-jar" WorkflowMultiBranchProject mavenWarPipeline = jenkinsRule.createProject(WorkflowMultiBranchProject.class, "build-maven-war"); mavenWarPipeline.addTrigger(new WorkflowJobDependencyTrigger()); mavenWarPipeline.getSourcesList().add(new BranchSource(new GitSCMSource(null, downstreamArtifactRepoRule.toString(), "", "*", "", false))); System.out.println("trigger maven-war#1..."); WorkflowJob mavenWarPipelineMasterPipeline = WorkflowMultibranchProjectTestsUtils.scheduleAndFindBranchProject(mavenWarPipeline, "master"); assertEquals(1, mavenWarPipeline.getItems().size()); System.out.println("wait for maven-war#1..."); jenkinsRule.waitUntilNoActivity(); WorkflowRun mavenWarPipelineFirstRun = mavenWarPipelineMasterPipeline.getLastBuild(); // TODO check in DB that the dependency on the war project is recorded // TRIGGER maven-jar#2 so that it triggers "maven-war" and creates maven-war#2 System.out.println("trigger maven-jar#2..."); Future<WorkflowRun> mavenJarPipelineMasterPipelineSecondRunFuture = mavenJarPipelineMasterPipeline.scheduleBuild2(0, new CauseAction(new Cause.RemoteCause("127.0.0.1", "junit test"))); System.out.println("wait for maven-jar#2..."); mavenJarPipelineMasterPipelineSecondRunFuture.get(); jenkinsRule.waitUntilNoActivity(); WorkflowRun mavenWarPipelineLastRun = mavenWarPipelineMasterPipeline.getLastBuild(); System.out.println("mavenWarPipelineLastBuild: " + mavenWarPipelineLastRun + " caused by " + mavenWarPipelineLastRun.getCauses()); assertThat(mavenWarPipelineLastRun.getNumber(), is(mavenWarPipelineFirstRun.getNumber() + 1)); Cause.UpstreamCause upstreamCause = mavenWarPipelineLastRun.getCause(Cause.UpstreamCause.class); assertThat(upstreamCause, notNullValue()); }
/** * Cancel previous builds for specified PR id. */ public int cancelQueuedBuildByPrNumber(final int id) { int canceled = 0; SecurityContext old = impersonate(ACL.SYSTEM); try { final Queue queue = getJenkinsInstance().getQueue(); final Queue.Item[] items = queue.getItems(); //todo replace with stream? for (Queue.Item item : items) { if (!(item.task instanceof Job)) { LOGGER.debug("Item {} not instanceof job", item); continue; } final Job<?, ?> jobTask = (Job<?, ?>) item.task; if (!jobTask.getFullName().equals(job.getFullName())) { LOGGER.debug("{} != {}", jobTask.getFullName(), job.getFullName()); continue; } final CauseAction action = item.getAction(CauseAction.class); if (isNull(action)) { LOGGER.debug("Cause action is null for {}", jobTask.getFullName()); continue; } Optional<Cause> cause = from(action.getCauses()) .filter(instanceOf(GitHubPRCause.class)) .firstMatch(new CauseHasPRNum(id)); if (cause.isPresent()) { LOGGER.debug("Cancelling {}", item); queue.cancel(item); canceled++; } } } finally { SecurityContextHolder.setContext(old); } return canceled; }
@Override public Iterable<Cause> apply(Action input) { return ((CauseAction) input).getCauses(); }
@Test public void testAggregate() throws Exception { FreeStyleProject project = jenkins.createFreeStyleProject("project"); List<FlakyTestResultAction> flakyTestResultActions = setUpFlakyTestResultAction(); List<FlakyTestResultAction> flakyTestResultActionList = new ArrayList<FlakyTestResultAction>( flakyTestResultActions); // First non-deflake build AbstractBuild firstBuild = (AbstractBuild) project .scheduleBuild2(0, flakyTestResultActionList.get(0)).get(); while (firstBuild.isBuilding()) { Thread.sleep(100); } // Second deflake build AbstractBuild secondBuild = (AbstractBuild) project .scheduleBuild2(0, flakyTestResultActionList.get(1), new CauseAction(new DeflakeCause(firstBuild))).get(); while (secondBuild.isBuilding()) { Thread.sleep(100); } // Third deflake build with HistoryAggregatedFlakyTestResultAction AbstractBuild thirdBuild = (AbstractBuild) project .scheduleBuild2(0, flakyTestResultActionList.get(2), new HistoryAggregatedFlakyTestResultAction(project)).get(); while (thirdBuild.isBuilding()) { Thread.sleep(100); } HistoryAggregatedFlakyTestResultAction action = thirdBuild .getAction(HistoryAggregatedFlakyTestResultAction.class); action.aggregate(); Map<String, SingleTestFlakyStats> aggregatedFlakyStatsMap = action.getAggregatedFlakyStats(); // Make sure revisions are inserted in the order of their appearance Map<String, SingleTestFlakyStats> revisionMap = action.getAggregatedTestFlakyStatsWithRevision() .get(TEST_ONE); assertArrayEquals("Incorrect revision history", new String[]{REVISION_ONE, REVISION_TWO}, revisionMap.keySet().toArray(new String[revisionMap.size()])); assertEquals("wrong number of entries for flaky stats", 4, aggregatedFlakyStatsMap.size()); SingleTestFlakyStats testOneStats = aggregatedFlakyStatsMap.get(TEST_ONE); SingleTestFlakyStats testTwoStats = aggregatedFlakyStatsMap.get(TEST_TWO); SingleTestFlakyStats testThreeStats = aggregatedFlakyStatsMap.get(TEST_THREE); SingleTestFlakyStats testFourStats = aggregatedFlakyStatsMap.get(TEST_FOUR); assertEquals("wrong number passes", 1, testOneStats.getPass()); assertEquals("wrong number fails", 0, testOneStats.getFail()); assertEquals("wrong number flakes", 1, testOneStats.getFlake()); assertEquals("wrong number passes", 1, testTwoStats.getPass()); assertEquals("wrong number fails", 0, testTwoStats.getFail()); assertEquals("wrong number flakes", 1, testTwoStats.getFlake()); assertEquals("wrong number passes", 0, testThreeStats.getPass()); assertEquals("wrong number fails", 1, testThreeStats.getFail()); assertEquals("wrong number flakes", 1, testThreeStats.getFlake()); assertEquals("wrong number passes", 1, testFourStats.getPass()); assertEquals("wrong number fails", 0, testFourStats.getFail()); assertEquals("wrong number flakes", 1, testFourStats.getFlake()); }
/** * @return whether the given action type should be preserved from our build, * vs. extracted from our delegate build. */ private static boolean preservedAction(Action a) { return SCMRevisionAction.class.isInstance(a) || CauseAction.class.isInstance(a); }
public CauseActionConverter() { super(CauseAction.class); }