@Initializer(before = InitMilestone.COMPLETED, after = InitMilestone.JOB_LOADED) public static void jobLoaded() throws IOException { m_logger.fine("Initialization milestone: All jobs have been loaded"); //$NON-NLS-1$ Jenkins jenkins = Jenkins.getInstance(); for (AbstractProject<?, ?> project : jenkins.getAllItems(AbstractProject.class)) { try { SCM scmConfig = project.getScm(); if (scmConfig instanceof AbstractConfiguration && ((AbstractConfiguration) scmConfig).isMigrated()) { project.save(); m_logger.info(String.format( "Project %s has been migrated.", //$NON-NLS-1$ project.getFullName())); } } catch (IOException e) { m_logger.log(Level.SEVERE, String.format("Failed to upgrade job %s", project.getFullName()), e); //$NON-NLS-1$ } } }
public FormValidation doCheckLocalPath(@AncestorInPath final AbstractProject project, @QueryParameter final String localPath) { final String path = Util.fixEmptyAndTrim(localPath); if (StringUtils.isBlank(path)) { return FormValidation.ok(); } try { File f = resolvePath(project, localPath); if (f != null) { return FormValidation.ok(); } } catch (Exception e) { return FormValidation.error(e.getMessage()); } return FormValidation.error("Invalid path."); }
public void testGetProjectActionHavingLastBuildGivesStarWarsAction() { AbstractProject mockProject = mock(AbstractProject.class); Build mockBuild = mock(Build.class); Quote expectedQuote = generateQuote(StarWarsResult.SUCCESS); when(mockProject.getLastBuild()).thenReturn(mockBuild); when(mockBuild.getResult()).thenReturn(Result.SUCCESS); when(mockQuotesGenerator.generate(StarWarsResult.SUCCESS)).thenReturn(expectedQuote); Action action = recorder.getProjectAction(mockProject); assertTrue(action instanceof StarWarsAction); assertEquals(StarWarsResult.SUCCESS, ((StarWarsAction) action).getResult()); assertNotNull(((StarWarsAction) action).getQuote()); }
public Ghprc(AbstractProject<?, ?> project, GhprcTrigger trigger, ConcurrentMap<Integer, GhprcPullRequest> pulls) { this.project = project; final GithubProjectProperty ghpp = project.getProperty(GithubProjectProperty.class); if (ghpp == null || ghpp.getProjectUrl() == null) { throw new IllegalStateException("A GitHub project url is required."); } String baseUrl = ghpp.getProjectUrl().baseUrl(); Matcher m = githubUserRepoPattern.matcher(baseUrl); if (!m.matches()) { throw new IllegalStateException(String.format("Invalid GitHub project url: %s", baseUrl)); } final String user = m.group(2); final String repo = m.group(3); this.trigger = trigger; this.repository = new GhprcRepository(user, repo, this, pulls); this.builds = new GhprcBuilds(trigger, repository); }
/** * support matrix plugin. * * @see JobInfoHelpers#triggerFrom(hudson.model.Job, java.lang.Class) */ @CheckForNull public static <T extends Trigger> T triggerFrom(final Job<?, ?> job, Class<T> tClass) { Job<?, ?> guessJob; if (job instanceof MatrixConfiguration) { guessJob = ((MatrixConfiguration) job).getParent(); } else { guessJob = job; } if (guessJob instanceof AbstractProject<?, ?>) { final AbstractProject<?, ?> abstractProject = (AbstractProject<?, ?>) guessJob; return abstractProject.getTrigger(tClass); } else if (guessJob instanceof ParameterizedJobMixIn.ParameterizedJob) { ParameterizedJobMixIn.ParameterizedJob pJob = (ParameterizedJobMixIn.ParameterizedJob) guessJob; for (Trigger candidate : pJob.getTriggers().values()) { if (tClass.isInstance(candidate)) { return tClass.cast(candidate); } } } return null; }
private Set<GhprcWebHook> getWebHooks() { final Set<GhprcWebHook> webHooks = new HashSet<GhprcWebHook>(); // We need this to get access to list of repositories Authentication old = SecurityContextHolder.getContext().getAuthentication(); SecurityContextHolder.getContext().setAuthentication(ACL.SYSTEM); try { for (AbstractProject<?, ?> job : Jenkins.getInstance().getAllItems(AbstractProject.class)) { GhprcTrigger trigger = job.getTrigger(GhprcTrigger.class); if (trigger == null || trigger.getWebHook() == null) { continue; } webHooks.add(trigger.getWebHook()); } } finally { SecurityContextHolder.getContext().setAuthentication(old); } if (webHooks.size() == 0) { logger.log(Level.WARNING, "No projects found using GitHub pull request trigger"); } return webHooks; }
@Override protected PollingResult compareRemoteRevisionWith( final AbstractProject<?, ?> project, final Launcher launcher, final FilePath filePath, final TaskListener listener, final SCMRevisionState revisionState) throws IOException, InterruptedException { final ActionTypeId actionTypeId = new ActionTypeId() .withCategory(actionTypeCategory) .withOwner(ActionOwner.Custom) .withProvider(actionTypeProvider) .withVersion(actionTypeVersion); LoggingHelper.log(listener, "Polling for jobs for action type id: [" + "Owner: %s, Category: %s, Provider: %s, Version: %s, ProjectName: %s]", actionTypeId.getOwner(), actionTypeId.getCategory(), actionTypeId.getProvider(), actionTypeId.getVersion(), projectName); return pollForJobs(actionTypeId, listener); }
@Nonnull private static Map<String, String> gatherEnvVarsNode(@Nonnull Job<?, ?> job, @Nonnull Node node) throws EnvInjectException { final FilePath rootPath = node.getRootPath(); if (rootPath == null) { //TODO: better than the original NPE. But maybe it's preferable to have more intelligent handling throw new EnvInjectException("Cannot retrieve Environment variables from the offline node"); } try { Map<String, String> envVars = new EnvVars(rootPath.act(new MasterToSlaveCallable<Map<String, String>, EnvInjectException>() { private static final long serialVersionUID = 1L; @Override public Map<String, String> call() throws EnvInjectException { return EnvVars.masterEnvVars; } })); envVars.put("NODE_NAME", node.getNodeName()); envVars.put("NODE_LABELS", Util.join(node.getAssignedLabels(), " ")); if (job instanceof AbstractProject) { FilePath wFilePath = ((AbstractProject)job).getSomeWorkspace(); if (wFilePath != null) { envVars.put("WORKSPACE", wFilePath.getRemote()); } } return envVars; } catch (IOException | InterruptedException ioe) { throw new EnvInjectException(ioe); } }
@Override public SQSJob createSqsJob(Job job, SQSTrigger sqsTrigger) { SQSJob sqsJob = null; if (job instanceof AbstractProject) { sqsJob = new SQSAbstractProjectJob((AbstractProject) job, sqsTrigger); } else if (job instanceof WorkflowJob) { sqsJob = new SQSWorkflowJob((WorkflowJob) job, sqsTrigger); } return sqsJob; }
@Override @SuppressWarnings("rawtypes") public boolean isApplicable(Class<? extends AbstractProject> aClass) { // Indicates that this builder can be used with all kinds of project types return true; }
/** * See documentation top of class * This function will determine the state of the artifactory server and compare it with the * local state. If there is a condition where a build needs to be triggered, trigger a build */ @Override public PollingResult compareRemoteRevisionWith(AbstractProject<?,?> project, Launcher launcher, FilePath workspace, TaskListener listener, SCMRevisionState baseline) throws IOException, InterruptedException { LOGGER.log(FINE, "Comparing remote revisions with baseline"); ArtifactoryRevisionState localState = (ArtifactoryRevisionState) baseline; ArtifactoryAPI api = new ArtifactoryAPI(getDescriptor().getArtifactoryServer()); ArtifactoryRevisionState serverState = ArtifactoryRevisionState.fromServer(repo, groupID, artifactID, versionFilter, api); //Compare server state to local state nextArtifact = ArtifactoryRevisionState.compareRevisionStates(serverState, localState); if (nextArtifact != null) { LOGGER.log(FINE, "Found new data for version: " + nextArtifact); return PollingResult.BUILD_NOW; } // Compare local state to server state nextArtifact = ArtifactoryRevisionState.compareRevisionStates(localState, serverState); if (nextArtifact != null) { LOGGER.log(FINE, "Found new data for version: " + nextArtifact); return PollingResult.BUILD_NOW; } return PollingResult.NO_CHANGES; }
@Override protected File dir() { if (item instanceof AbstractProject) { Run<?, ?> run = getAbstractProject().getLastCompletedBuild(); if (run != null) { File buildArchiveDir = getBuildArchiveDir(run); if (buildArchiveDir.exists()) { return buildArchiveDir; } } } return getProjectArchiveDir(item); }
@Test public void testUploadSource() throws Exception { SCM mockSCM = mock(SCM.class); when(mockSCM.getType()).thenReturn("SCM"); AbstractProject p = mock(AbstractProject.class); when(p.getScm()).thenReturn(mockSCM); when(build.getProject()).thenReturn(p); S3DataManager d = createDefaultSource(); File sourceFolder = new File("/tmp/jenkins/workspace/proj"); sourceFolder.mkdirs(); UploadToS3Output result = d.uploadSourceToS3(listener, testWorkSpace); assertEquals(result.getSourceLocation(), s3InputBucketName + "/" + s3InputKeyName); }
private void notifyStart(AbstractBuild build, String message) { try { AbstractProject<?, ?> project = build.getProject(); AbstractBuild<?, ?> previousBuild = project.getLastBuild().getPreviousCompletedBuild(); getTelegram(build).publish(message, getBuildColor(previousBuild)); } catch (NullPointerException npe){ getTelegram(build).publish(message, "good"); } }
public void completed(AbstractBuild r) { AbstractProject<?, ?> project = r.getProject(); if(project == null) return; Result result = r.getResult(); AbstractBuild<?, ?> previousBuild = project.getLastBuild(); if(previousBuild == null) return; do { previousBuild = previousBuild.getPreviousCompletedBuild(); } while (previousBuild != null && previousBuild.getResult() == Result.ABORTED); Result previousResult = (previousBuild != null) ? previousBuild.getResult() : Result.SUCCESS; if ((result == Result.ABORTED && notifier.getNotifyAborted()) || (result == Result.FAILURE //notify only on single failed build && previousResult != Result.FAILURE && notifier.getNotifyFailure()) || (result == Result.FAILURE //notify only on repeated failures && previousResult == Result.FAILURE && notifier.getNotifyRepeatedFailure()) || (result == Result.NOT_BUILT && notifier.getNotifyNotBuilt()) || (result == Result.SUCCESS && (previousResult == Result.FAILURE || previousResult == Result.UNSTABLE) && notifier.getNotifyBackToNormal()) || (result == Result.SUCCESS && notifier.getNotifySuccess()) || (result == Result.UNSTABLE && notifier.getNotifyUnstable())) { getTelegram(r).publish(getBuildStatusMessage(r, notifier.includeTestSummary(), notifier.getIncludeFailedTests(),notifier.includeCustomMessage()), getBuildColor(r)); } }
@SuppressWarnings("unchecked") FineGrainedNotifier getNotifier(AbstractProject project, TaskListener listener) { Map<Descriptor<Publisher>, Publisher> map = project.getPublishersList().toMap(); for (Publisher publisher : map.values()) { if (publisher instanceof TelegramNotifier) { return new ActiveNotifier((TelegramNotifier) publisher, (BuildListener)listener); } } return new DisabledNotifier(); }
/** {@inheritDoc} */ @SuppressWarnings("unchecked") @Override public boolean isApplicable(final Class<? extends AbstractProject> jobType) { return FreeStyleProject.class.isAssignableFrom(jobType); }
public FormValidation doCheckAclToken( @AncestorInPath AbstractProject<?, ?> project, @QueryParameter String value) throws IOException { if (0 == value.length()) { return FormValidation.error("Empty token, no token will be used."); } return FormValidation.ok(); }
public FormValidation doCheckHostUrl( @AncestorInPath AbstractProject<?, ?> project, @QueryParameter String value) throws IOException { if (0 == value.length()) { return FormValidation.error("Empty URL."); } return FormValidation.ok(); }
public FormValidation doCheckKey( @AncestorInPath AbstractProject<?, ?> project, @QueryParameter String value) throws IOException { if (0 == value.length()) { return FormValidation.error("Empty Key."); } return FormValidation.ok(); }
public FormValidation doCheckEnvKey( @AncestorInPath AbstractProject<?, ?> project, @QueryParameter String value) throws IOException { if (0 == value.length()) { return FormValidation.error("Empty ENV key"); } return FormValidation.ok(); }
private Node prepareExecutorFor(final AbstractProject job) throws Descriptor.FormException, IOException, InterruptedException { LOGGER.info("Creating a Container slave to host " + job.toString() + "#" + job.getNextBuildNumber()); // Immediately create a slave for this item // Real provisioning will happen later String slaveName = "Container for " + job.getName() + "#" + job.getNextBuildNumber(); String description = "Container slave for building " + job.getFullName(); HyperSlaves plugin = HyperSlaves.get(); return new HyperSlave(slaveName, description, null, plugin.createStandardJobProvisionerFactory(job)); }
public File resolvePath(final AbstractProject project, final String path) throws IOException, InterruptedException { File f = new File(path); if (f.isAbsolute() && (!f.isFile() || !f.canExecute())) { return null; } // For absolute paths FormValidation validateExec = FormValidation.validateExecutable(path); if (validateExec.kind == FormValidation.Kind.OK) { return f; } // Ant style path definitions FilePath workspace = project.getSomeWorkspace(); if (workspace != null) { File workspaceRoot = new File(workspace.toURI()); FileSet fileSet = Util.createFileSet(workspaceRoot, path); FileScanner fs = fileSet.getDirectoryScanner(); fs.setIncludes(new String[]{path}); fs.scan(); String[] includedFiles = fs.getIncludedFiles(); if (includedFiles.length > 0) { File includedFile = new File(workspaceRoot, includedFiles[0]); if (includedFile.exists() && includedFile.isFile() && includedFile.canExecute()) { return includedFile; } } } return null; }
/** * This callback validates the {@code configFilePath} specified by the user. */ public FormValidation doCheckConfigFilePath( @QueryParameter("configFilePath") final String configFilePath, @AncestorInPath AbstractProject project) throws IOException { String resolvedInput = Resolve.resolveBuiltinWithCustom(configFilePath, ImmutableMap.of("JOB_NAME", project.getName())); try { if (Strings.isNullOrEmpty(resolvedInput)) { throw FormValidation.error(Messages.AbstractCloudDeploymentDescriptor_NotEmpty()); } return FormValidation.ok(); } catch (FormValidation issue) { return reportValidationIssue(resolvedInput, issue); } }
/** * This callback validates the {@code deploymentName} specified by the user. */ public FormValidation doCheckDeploymentName( @QueryParameter("deploymentName") final String deploymentName, @AncestorInPath AbstractProject project) throws IOException { String resolvedInput = Resolve.resolveBuiltinWithCustom(deploymentName, ImmutableMap.of("JOB_NAME", project.getName())); try { validateComponentName(resolvedInput); return FormValidation.ok(); } catch (FormValidation issue) { return reportValidationIssue(resolvedInput, issue); } }
/** * Get the root upstream build which caused this build. Useful in build pipelines to * be able to extract the changes which started the pipeline in later stages of * the pipeline * * @return */ public static AbstractBuild getUpstreamBuild(AbstractBuild<?, ?> build) { logger.log(Level.FINE, "Find build upstream of " + build.getId()); Cause.UpstreamCause cause = getUpstreamCause(build); if (cause == null) { logger.log(Level.FINE, "No upstream cause, so must be upstream build: " + build.getId()); return build; } logger.log(Level.FINE, "Found upstream cause: " + cause.toString() + "(" + cause.getShortDescription() + ")"); AbstractProject project = (AbstractProject) Jenkins.getInstance().getItem(cause.getUpstreamProject(), build.getProject()); if (project == null) { logger.log(Level.WARNING, "Found an UpstreamCause (" + cause.toString() + "), but the upstream project (" + cause.getUpstreamProject() + ") does not appear to be valid!"); logger.log(Level.WARNING, "Using build [" + build.getId() + "] as the upstream build - this is likely incorrect."); return build; } AbstractBuild upstreamBuild = project.getBuildByNumber(cause.getUpstreamBuild()); if (upstreamBuild == null) { logger.log(Level.WARNING, "Found an UpstreamCause (" + cause.toString() + "), and an upstream project (" + project.getName() + "), but the build is invalid!" + cause.getUpstreamBuild()); logger.log(Level.WARNING, "Using build [" + build.getId() + "] as the upstream build - this is likely incorrect."); return build; } return getUpstreamBuild(upstreamBuild); }
/** * Gets the StarWarsAction as the project action. This is applicable for * each job and only when there's at least one build in the job. * * @param project * @return the project action */ @Override public final Action getProjectAction(final AbstractProject<?, ?> project) { Action action = null; if (project.getLastBuild() != null) { Result result = project.getLastBuild().getResult(); StarWarsResult starWarsResult = StarWarsResult.get(result); Quote quote = quotesGenerator.generate(starWarsResult); action = new StarWarsAction(starWarsResult, quote); } return action; }
@Test public void shouldTriggerJobOnPullRequestOpen() throws Exception { when(trigger.getRepoFullName(any(AbstractProject.class))).thenReturn(create(REPO_URL_FROM_PAYLOAD)); when(trigger.getTriggerMode()).thenReturn(GitHubPRTriggerMode.HEAVY_HOOKS); FreeStyleProject job = jenkins.createFreeStyleProject(); job.addProperty(new GithubProjectProperty(REPO_URL_FROM_PAYLOAD)); job.addTrigger(trigger); new GHPullRequestSubscriber().onEvent(GHEvent.PULL_REQUEST, classpath("payload/pull_request.json")); verify(trigger).queueRun(eq(job), eq(1)); }
/** * @return JDK to be used with this project. */ private JDK getJdkToUse(AbstractProject<?, ?> project) { JDK jdkToUse = getJDK(); if (jdkToUse == null) { jdkToUse = project.getJDK(); } return jdkToUse; }
public static void triggerRunAndWait(int numOfTriggers, GhprcTrigger trigger, AbstractProject<?, ?> project) throws InterruptedException { for (int i = 0; i < numOfTriggers; ++i) { trigger.run(); waitForBuildsToFinish(project); } }
/** * Form validation method. * * Copied from hudson.tasks.BuildTrigger.doCheck(Item project, String value) */ public FormValidation doCheckProjects(@AncestorInPath AbstractProject<?,?> project, @QueryParameter String value ) { // Require CONFIGURE permission on this project if(!project.hasPermission(Item.CONFIGURE)){ return FormValidation.ok(); } StringTokenizer tokens = new StringTokenizer(Util.fixNull(value),","); boolean hasProjects = false; while(tokens.hasMoreTokens()) { String projectName = tokens.nextToken().trim(); if (StringUtils.isNotBlank(projectName)) { Item item = Jenkins.getInstance().getItem(projectName,project,Item.class); // only works after version 1.410 if(item==null){ return FormValidation.error("Project name " + projectName + " not found, did you mean " + AbstractProject.findNearest(projectName).getName()); } if(!(item instanceof AbstractProject)){ return FormValidation.error("Project " + projectName + " is not buildable"); } hasProjects = true; } } if (!hasProjects) { // return FormValidation.error(Messages.BuildTrigger_NoProjectSpecified()); // only works with Jenkins version built after 2011-01-30 return FormValidation.error("No project specified"); } return FormValidation.ok(); }
@Override public Action getProjectAction(AbstractProject<?, ?> project) { if (!project.getBuilds().isEmpty() /*|| !project.getActions().isEmpty()*/) { BuildAction buildAction = project.getLastBuild().getAction(BuildAction.class); if (buildAction != null) { ProjectAction lastProject = buildAction.getProjectAction(); return new ProjectAction(project, lastProject.getModules()); } } return new ProjectAction(project); }
public static GhprcTrigger extractTrigger(AbstractProject<?, ?> p) { GhprcTrigger trigger = p.getTrigger(GhprcTrigger.class); if (trigger == null) { return null; } return trigger; }
/** * Returns the AWS Device Farm test run action from the most recent build. * * @param project The Jenkins project which contains builds/runs to examine. * @return The previous Device Farm build result action. */ public static AWSDeviceFarmTestResultAction previousAWSDeviceFarmBuildAction(AbstractProject<?, ?> project) { AbstractBuild<?, ?> build = AWSDeviceFarmUtils.previousAWSDeviceFarmBuild(project); if (build == null) { return null; } return build.getAction(AWSDeviceFarmTestResultAction.class); }
/** * Field 'root' should be a valid directory. */ public FormValidation doCheckRoot(@AncestorInPath AbstractProject project, @QueryParameter String value) throws IOException { if (value.length() == 0) { return FormValidation.warning("Workspace root will be used as Drupal root"); } if (project != null) { return FilePath.validateFileMask(project.getSomeWorkspace(), value); } return FormValidation.ok(); }
private void notifyStart(AbstractBuild build, String attachmentMessage) { AbstractProject<?, ?> project = (build != null) ? build.getProject() : null; AbstractBuild<?, ?> previousBuild = (project != null && project.getLastBuild() != null) ? project.getLastBuild().getPreviousCompletedBuild() : null; String expandedCustomMessage = getExpandedCustomMessage(build); if (previousBuild == null) { getMattermost(build).publish(attachmentMessage, expandedCustomMessage, "good"); } else { getMattermost(build).publish(attachmentMessage, expandedCustomMessage, getBuildColor(previousBuild)); } }
public void completed(AbstractBuild r) { AbstractProject<?, ?> project = r.getProject(); Result result = r.getResult(); AbstractBuild<?, ?> previousBuild = project.getLastBuild(); if (previousBuild != null) { do { previousBuild = previousBuild.getPreviousCompletedBuild(); } while (previousBuild != null && previousBuild.getResult() == Result.ABORTED); } Result previousResult = (previousBuild != null) ? previousBuild.getResult() : Result.SUCCESS; if ((result == Result.ABORTED && notifier.getNotifyAborted()) || (result == Result.FAILURE //notify only on single failed build && previousResult != Result.FAILURE && notifier.getNotifyFailure()) || (result == Result.FAILURE //notify only on repeated failures && previousResult == Result.FAILURE && notifier.getNotifyRepeatedFailure()) || (result == Result.NOT_BUILT && notifier.getNotifyNotBuilt()) || (result == Result.SUCCESS && (previousResult == Result.FAILURE || previousResult == Result.UNSTABLE) && notifier.getNotifyBackToNormal()) || (result == Result.SUCCESS && notifier.getNotifySuccess()) || (result == Result.UNSTABLE && notifier.getNotifyUnstable())) { String expandedCustomMessage = getExpandedCustomMessage(r); getMattermost(r).publish(getBuildStatusMessage(r, notifier.includeTestSummary(), notifier.includeCustomAttachmentMessage()), expandedCustomMessage, getBuildColor(r)); if (notifier.getCommitInfoChoice().showAnything()) { getMattermost(r).publish(getCommitList(r), expandedCustomMessage, getBuildColor(r)); } } }
@SuppressWarnings("unchecked") FineGrainedNotifier getNotifier(AbstractProject project, TaskListener listener) { Map<Descriptor<Publisher>, Publisher> map = project.getPublishersList().toMap(); for (Publisher publisher : map.values()) { if (publisher instanceof MattermostNotifier) { return new ActiveNotifier((MattermostNotifier) publisher, (BuildListener)listener); } } return new DisabledNotifier(); }
@Override public boolean isApplicable(AbstractProject<?, ?> item) { // MatrixProject is configured by Axis // TODO Better solution would be to return false only if an OpenEdge axis is configured if (item instanceof MatrixProject) return false; return true; }