hudson.model.TaskListener Java Examples

The following examples show how to use hudson.model.TaskListener. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PutStepTest.java    From ssh-steps-plugin with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() throws IOException, InterruptedException {

  when(runMock.getCauses()).thenReturn(null);
  when(taskListenerMock.getLogger()).thenReturn(printStreamMock);
  doNothing().when(printStreamMock).println();
  when(launcherMock.getChannel()).thenReturn(new TestVirtualChannel());

  PowerMockito.mockStatic(SSHService.class);
  when(SSHService.create(any(), anyBoolean(), anyBoolean(), any())).thenReturn(sshServiceMock);

  when(filePathMock.child(any())).thenReturn(filePathMock);
  when(filePathMock.exists()).thenReturn(true);
  when(filePathMock.isDirectory()).thenReturn(false);
  when(filePathMock.getRemote()).thenReturn(path);

  when(contextMock.get(Run.class)).thenReturn(runMock);
  when(contextMock.get(TaskListener.class)).thenReturn(taskListenerMock);
  when(contextMock.get(EnvVars.class)).thenReturn(envVarsMock);
  when(contextMock.get(Launcher.class)).thenReturn(launcherMock);
  when(contextMock.get(FilePath.class)).thenReturn(filePathMock);

}
 
Example #2
Source File: BuildListener.java    From elasticsearch-jenkins with MIT License 6 votes vote down vote up
@Override
public void onCompleted(Run run, TaskListener listener) {
    loadConfig();

    final boolean validConfig = config != null && config.nonEmptyValues();
    if (validConfig) {
        final Build build = createBuild(run, listener);

        try {
            final Index index = new Index.Builder(build).index(config.getIndexName()).type(config.getTypeName()).build();

            final JestResult result = jestClient.execute(index);

            if (result.isSucceeded()) {
                LOG.fine("Sent build to Elasticsearch: " + build);
            } else {
                LOG.warning("Failed to index build, got error message: " + result.getErrorMessage());
            }
        } catch (Exception e) {
            LOG.log(Level.SEVERE, "Error when sending build data: " + build, e);
        }
    } else {
        LOG.fine("The configuration is not valid, can not index the build");
    }
}
 
Example #3
Source File: IssuesScanner.java    From warnings-ng-plugin with MIT License 6 votes vote down vote up
@SuppressWarnings("checkstyle:ParameterNumber")
IssuesScanner(final Tool tool, final List<RegexpFilter> filters, final Charset sourceCodeEncoding,
        final FilePath workspace, final String sourceDirectory, final Run<?, ?> run,
        final FilePath jenkinsRootDir, final TaskListener listener,
        final BlameMode blameMode, final ForensicsMode forensicsMode) {
    this.filters = new ArrayList<>(filters);
    this.sourceCodeEncoding = sourceCodeEncoding;
    this.tool = tool;
    this.workspace = workspace;
    this.sourceDirectory = sourceDirectory;
    this.run = run;
    this.jenkinsRootDir = jenkinsRootDir;
    this.listener = listener;
    this.blameMode = blameMode;
    this.forensicsMode = forensicsMode;
}
 
Example #4
Source File: AnyBranchBuildStrategyImpl.java    From basic-branch-build-strategies-plugin with MIT License 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public boolean isAutomaticBuild(@NonNull SCMSource source, @NonNull SCMHead head, @NonNull SCMRevision currRevision,
                                @CheckForNull SCMRevision lastBuiltRevision, @CheckForNull SCMRevision lastSeenRevision, @NonNull TaskListener taskListener) {

    if(strategies.isEmpty()){
        return false;
    }

    for (BranchBuildStrategy strategy: strategies) {
        if(strategy.automaticBuild(
            source,
            head,
            currRevision,
            lastBuiltRevision,
            lastSeenRevision,
            taskListener
        )){
            return true;
        };

    }
    return false;
}
 
Example #5
Source File: IOpenShiftApiObjHandler.java    From jenkins-plugin with Apache License 2.0 6 votes vote down vote up
default ModelNode hydrateJsonYaml(String jsonyaml, TaskListener listener) {
    // construct json/yaml node
    ModelNode resources = null;
    try {
        resources = ModelNode.fromJSONString(jsonyaml);
    } catch (Exception e) {
        Yaml yaml = new Yaml(new SafeConstructor());
        Map<String, Object> map = (Map<String, Object>) yaml.load(jsonyaml);
        JSONObject jsonObj = JSONObject.fromObject(map);
        try {
            resources = ModelNode.fromJSONString(jsonObj.toString());
        } catch (Throwable t) {
            if (listener != null)
                t.printStackTrace(listener.getLogger());
        }
    }
    return resources;
}
 
Example #6
Source File: AssignableUserSearchStepTest.java    From jira-steps-plugin with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() throws IOException, InterruptedException {

  // Prepare site.
  when(envVarsMock.get("JIRA_SITE")).thenReturn("LOCAL");
  when(envVarsMock.get("BUILD_URL")).thenReturn("http://localhost:8080/jira-testing/job/01");

  PowerMockito.mockStatic(Site.class);
  Mockito.when(Site.get(any())).thenReturn(siteMock);
  when(siteMock.getService()).thenReturn(jiraServiceMock);

  when(runMock.getCauses()).thenReturn(null);
  when(taskListenerMock.getLogger()).thenReturn(printStreamMock);
  doNothing().when(printStreamMock).println();

  final ResponseDataBuilder<Object> builder = ResponseData.builder();
  when(jiraServiceMock
      .assignableUserSearch(any(), anyString(), anyString(), anyInt(), anyInt()))
      .thenReturn(builder.successful(true).code(200).message("Success").build());

  when(contextMock.get(Run.class)).thenReturn(runMock);
  when(contextMock.get(TaskListener.class)).thenReturn(taskListenerMock);
  when(contextMock.get(EnvVars.class)).thenReturn(envVarsMock);
}
 
Example #7
Source File: KubernetesSlave.java    From kubernetes-plugin with Apache License 2.0 6 votes vote down vote up
@Override
public Launcher createLauncher(TaskListener listener) {
    Launcher launcher = super.createLauncher(listener);
    if (template != null) {
        Executor executor = Executor.currentExecutor();
        if (executor != null) {
            Queue.Executable currentExecutable = executor.getCurrentExecutable();
            if (currentExecutable != null && executables.add(currentExecutable)) {
                listener.getLogger().println(Messages.KubernetesSlave_AgentIsProvisionedFromTemplate(
                        ModelHyperlinkNote.encodeTo("/computer/" + getNodeName(), getNodeName()),
                        getTemplate().getName())
                );
                printAgentDescription(listener);
                checkHomeAndWarnIfNeeded(listener);
            }
        }
    }
    return launcher;
}
 
Example #8
Source File: LockRunListener.java    From lockable-resources-plugin with MIT License 6 votes vote down vote up
@Override
public void onCompleted(Run<?, ?> build, TaskListener listener) {
	// Skip unlocking for multiple configuration projects,
	// only the child jobs will actually unlock resources.
	if (build instanceof MatrixBuild)
		return;

	// obviously project name cannot be obtained here
	List<LockableResource> required = LockableResourcesManager.get()
			.getResourcesFromBuild(build);
	if (!required.isEmpty()) {
		LockableResourcesManager.get().unlock(required, build);
		listener.getLogger().printf("%s released lock on %s%n",
				LOG_PREFIX, required);
		LOGGER.fine(build.getFullDisplayName() + " released lock on "
				+ required);
	}

}
 
Example #9
Source File: CFNCreateChangeSetTests.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void createChangeSetStackDoesNotExist() throws Exception {
	WorkflowJob job = this.jenkinsRule.jenkins.createProject(WorkflowJob.class, "cfnTest");
	Mockito.when(this.stack.exists()).thenReturn(false);
	Mockito.when(this.stack.describeChangeSet("bar")).thenReturn(new DescribeChangeSetResult()
			.withChanges(new Change())
			.withStatus(ChangeSetStatus.CREATE_COMPLETE)
	);
	job.setDefinition(new CpsFlowDefinition(""
			+ "node {\n"
			+ "  def changes = cfnCreateChangeSet(stack: 'foo', changeSet: 'bar')\n"
			+ "  echo \"changesCount=${changes.size()}\"\n"
			+ "}\n", true)
	);
	Run run = this.jenkinsRule.assertBuildStatusSuccess(job.scheduleBuild2(0));
	this.jenkinsRule.assertLogContains("changesCount=1", run);

	PowerMockito.verifyNew(CloudFormationStack.class, Mockito.atLeastOnce()).withArguments(Mockito.any(AmazonCloudFormation.class), Mockito.eq("foo"), Mockito.any(TaskListener.class));
	Mockito.verify(this.stack).createChangeSet(Mockito.eq("bar"), Mockito.anyString(), Mockito.anyString(), Mockito.anyCollectionOf(Parameter.class), Mockito.anyCollectionOf(Tag.class),
											   Mockito.anyCollectionOf(String.class), Mockito.any(PollConfiguration.class), Mockito.eq(ChangeSetType.CREATE), Mockito.anyString(), Mockito.any());
}
 
Example #10
Source File: GitHubPRCloseEvent.java    From github-integration-plugin with MIT License 6 votes vote down vote up
@Override
public GitHubPRCause check(@Nonnull GitHubPRDecisionContext prDecisionContext) throws IOException {
    TaskListener listener = prDecisionContext.getListener();
    GHPullRequest remotePR = prDecisionContext.getRemotePR();
    final PrintStream logger = listener.getLogger();
    final GitHubPRPullRequest localPR = prDecisionContext.getLocalPR();

    if (isNull(localPR)) {
        return null;
    }

    GitHubPRCause cause = null;

    // must be closed once
    if (remotePR.getState().equals(GHIssueState.CLOSED)) {
        logger.println(DISPLAY_NAME + ": state has changed (PR was closed)");
        cause = prDecisionContext.newCause("PR was closed", false);
    }

    return cause;
}
 
Example #11
Source File: AnsibleAdHocCommandInvocationTest.java    From ansible-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void should_generate_simple_invocation() throws Exception {
    // Given
    Inventory inventory = new InventoryPath("/tmp/hosts");
    BuildListener listener = mock(BuildListener.class);
    CLIRunner runner = mock(CLIRunner.class);
    AbstractBuild<?,?> build = mock(AbstractBuild.class);
    when(build.getEnvironment(any(TaskListener.class))).thenReturn(new EnvVars());
    AnsibleAdHocCommandInvocation invocation = new AnsibleAdHocCommandInvocation("/usr/local/bin/ansible", build, listener);
    invocation.setHostPattern("localhost");
    invocation.setInventory(inventory);
    invocation.setModule("ping");
    invocation.setForks(5);
    // When
    invocation.execute(runner);
    // Then
    ArgumentCaptor<ArgumentListBuilder> argument = ArgumentCaptor.forClass(ArgumentListBuilder.class);
    verify(runner).execute(argument.capture(), anyMap());
    assertThat(argument.getValue().toString())
            .isEqualTo("/usr/local/bin/ansible localhost -i /tmp/hosts -m ping -f 5");
}
 
Example #12
Source File: CFNCreateChangeSetTests.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void createChangeSetWithRawTemplate() throws Exception {
	WorkflowJob job = this.jenkinsRule.jenkins.createProject(WorkflowJob.class, "cfnTest");
	Mockito.when(this.stack.exists()).thenReturn(true);
	Mockito.when(this.stack.describeChangeSet("bar")).thenReturn(new DescribeChangeSetResult()
			.withChanges(new Change())
			.withStatus(ChangeSetStatus.CREATE_COMPLETE)
	);
	job.setDefinition(new CpsFlowDefinition(""
			+ "node {\n"
			+ "  def changes = cfnCreateChangeSet(stack: 'foo', changeSet: 'bar', template: 'foobaz')\n"
			+ "  echo \"changesCount=${changes.size()}\"\n"
			+ "}\n", true)
	);
	Run run = this.jenkinsRule.assertBuildStatusSuccess(job.scheduleBuild2(0));
	this.jenkinsRule.assertLogContains("changesCount=1", run);

	PowerMockito.verifyNew(CloudFormationStack.class, Mockito.atLeastOnce()).withArguments(Mockito.any(AmazonCloudFormation.class), Mockito.eq("foo"), Mockito.any(TaskListener.class));
	Mockito.verify(this.stack).createChangeSet(Mockito.eq("bar"), Mockito.eq("foobaz"), Mockito.anyString(), Mockito.anyCollectionOf(Parameter.class), Mockito.anyCollectionOf(Tag.class),
											   Mockito.anyCollectionOf(String.class), Mockito.any(PollConfiguration.class), Mockito.eq(ChangeSetType.UPDATE), Mockito.anyString(), Mockito.any());
}
 
Example #13
Source File: Reaper.java    From kubernetes-plugin with Apache License 2.0 6 votes vote down vote up
@Override
public void onEvent(@NonNull Action action, @NonNull KubernetesSlave node, @NonNull Pod pod) throws IOException, InterruptedException {
    List<ContainerStatus> backOffContainers = PodUtils.getContainers(pod, cs -> {
        ContainerStateWaiting waiting = cs.getState().getWaiting();
        return waiting != null && waiting.getMessage() != null && waiting.getMessage().contains("Back-off pulling image");
    });
    if (backOffContainers.isEmpty()) {
        return;
    }
    backOffContainers.forEach(cs -> {
        TaskListener runListener = node.getTemplate().getListener();
        runListener.error("Unable to pull Docker image \""+cs.getImage()+"\". Check if image tag name is spelled correctly.");
    });
    Queue q = Jenkins.get().getQueue();
    String runUrl = pod.getMetadata().getAnnotations().get("runUrl");
    for (Queue.Item item: q.getItems()) {
        if (item.task.getUrl().equals(runUrl)) {
            q.cancel(item);
            break;
        }
    }
    node.terminate();
}
 
Example #14
Source File: CloudWatchMonitor.java    From aws-codebuild-jenkins-plugin with Apache License 2.0 6 votes vote down vote up
public void pollForLogs(TaskListener listener) {
    if(cwlStreamingDisabled) {
        return;
    } else if(this.logsLocation != null && this.logsLocation.getGroupName() != null && this.logsLocation.getStreamName() != null) {
        this.latestLogs = new ArrayList<>();
        GetLogEventsRequest logRequest = new GetLogEventsRequest()
            .withStartTime(lastPollTime)
            .withStartFromHead(true)
            .withLogGroupName(logsLocation.getGroupName())
            .withLogStreamName(logsLocation.getStreamName());
        try {
            GetLogEventsResult logsResult = logsClient.getLogEvents(logRequest);
            getAndFormatLogs(logsResult.getEvents(), listener);
        } catch (Exception e) {
            latestLogs = Arrays.asList(e.getMessage());
            return;
        }
    } else {
        latestLogs = Arrays.asList(noLogsMessage);
        return;
    }
}
 
Example #15
Source File: GitLabSCMMergeRequestHead.java    From gitlab-branch-source-plugin with GNU General Public License v2.0 5 votes vote down vote up
private void checkout(GitSCM scm, Run<?, ?> build, GitClient git, TaskListener listener, Revision rev) throws InterruptedException, IOException, GitException {
    CheckoutCommand checkoutCommand = git.checkout().ref(rev.getSha1String());
    for (GitSCMExtension ext : scm.getExtensions()) {
        ext.decorateCheckoutCommand(scm, build, git, listener, checkoutCommand);
    }
    checkoutCommand.execute();
}
 
Example #16
Source File: PipelineBranchDefaultsProjectFactory.java    From pipeline-multibranch-defaults-plugin with MIT License 5 votes vote down vote up
@Override
protected SCMSourceCriteria getSCMSourceCriteria(SCMSource source) {
    return new SCMSourceCriteria() {
        @Override
        public boolean isHead(Probe probe, TaskListener listener) throws IOException {
            return true;
        }
    };
}
 
Example #17
Source File: GitLabSCMSource.java    From gitlab-branch-source-plugin with MIT License 5 votes vote down vote up
@Override
protected SCMRevision retrieve(@NonNull String thingName, @NonNull TaskListener listener)
        throws IOException, InterruptedException {
    SCMHeadObserver.Named baptist = SCMHeadObserver.named(thingName);
    retrieve(null, baptist, null, listener);
    return baptist.result();
}
 
Example #18
Source File: CommitStatusUpdateRunListener.java    From DotCi with MIT License 5 votes vote down vote up
@Override
public void onCompleted(final DynamicBuild build, final TaskListener listener) {
    final String sha1 = build.getSha();
    if (sha1 == null) {
        return;
    }

    final GHRepository repository = getGithubRepository(build);
    final GHCommitState state;
    String msg;
    final Result result = build.getResult();
    if (result.isBetterOrEqualTo(SUCCESS)) {
        state = GHCommitState.SUCCESS;
        msg = "Success";
    } else if (result.isBetterOrEqualTo(UNSTABLE)) {
        state = GHCommitState.FAILURE;
        msg = "Unstable";
    } else {
        state = GHCommitState.FAILURE;
        msg = "Failed";
    }
    if (build.isSkipped()) {
        msg += " - Skipped";
    }
    try {
        listener.getLogger().println("setting commit status on Github for " + repository.getHtmlUrl() + "/commit/" + sha1);
        repository.createCommitStatus(sha1, state, build.getFullUrl(), msg, getContext(build));
    } catch (final Exception e) {
        printErrorToBuildConsole(listener, e);
    }

}
 
Example #19
Source File: DockerImageComboStep.java    From yet-another-docker-plugin with MIT License 5 votes vote down vote up
@Override
public void perform(@Nonnull Run<?, ?> run, @Nonnull FilePath workspace, @Nonnull Launcher launcher,
                    @Nonnull TaskListener listener) throws InterruptedException, IOException {
    PrintStream llog = listener.getLogger();
    final DockerImageComboStepFileCallable comboCallable = newDockerImageComboStepFileCallableBuilder()
            .withTaskListener(listener)
            .withRun(run)
            .withBuildImage(buildImage)
            .withConnector(connector)
            .withPushAll(push)
            .withCleanAll(clean)
            .withCleanupDangling(cleanupDangling)
            .build();
    try {
        llog.println("Executing remote combo builder...");

        response = workspace.act(comboCallable);

        if (!response.isSuccess()) {
            throw new IOException(trimToEmpty(response.getErrorMessage()),
                    new Exception(trimToEmpty(response.getErrorTrace())));
        }

        if (isNull(response)) {
            throw new AbortException("Something failed.");

        }
    } catch (Exception ex) {
        LOG.error("Can't build image", ex);
        throw ex;
    }
}
 
Example #20
Source File: DockerComposeEnvContributor.java    From DotCi with MIT License 5 votes vote down vote up
@Override
public void buildEnvironmentFor(Run run, EnvVars envs, TaskListener listener) throws IOException, InterruptedException {
    if (isDockerComposeBuild(run)) {
        String composeProjectName = String.format("%s%s", run.getParent().getFullName(), run.getNumber())
            .replaceAll("[^A-Za-z0-9]", "").toLowerCase();
        LOGGER.fine("Setting COMPOSE_PROJECT_NAME=" + composeProjectName);
        envs.put(COMPOSE_PROJECT_NAME, composeProjectName);
    }
}
 
Example #21
Source File: DynamicBuildModel.java    From DotCi with MIT License 5 votes vote down vote up
public Map<String, Object> getEnvironmentWithChangeSet(final TaskListener listener) throws IOException, InterruptedException {
    final HashMap<String, Object> environmentWithChangeSet = new HashMap<>();
    environmentWithChangeSet.putAll(this.build.getEnvironment(listener));
    environmentWithChangeSet.put("DOTCI_CHANGE_SET", getChangeSet());
    environmentWithChangeSet.put("build", this.build);
    return environmentWithChangeSet;
}
 
Example #22
Source File: GitHubPRCommentEvent.java    From github-integration-plugin with MIT License 5 votes vote down vote up
@Override
public GitHubPRCause check(@Nonnull GitHubPRDecisionContext prDecisionContext) {
    final TaskListener listener = prDecisionContext.getListener();
    final PrintStream llog = listener.getLogger();
    final GitHubPRPullRequest localPR = prDecisionContext.getLocalPR();
    final GHPullRequest remotePR = prDecisionContext.getRemotePR();
    final GitHubPRUserRestriction prUserRestriction = prDecisionContext.getPrUserRestriction();

    GitHubPRCause cause = null;
    try {
        for (GHIssueComment issueComment : remotePR.getComments()) {
            if (isNull(localPR) // test all comments for trigger word even if we never saw PR before
                    || isNull(localPR.getLastCommentCreatedAt()) // PR was created but had no comments
                    // don't check comments that we saw before
                    || localPR.getLastCommentCreatedAt().compareTo(issueComment.getCreatedAt()) < 0) {
                llog.printf("%s: state has changed (new comment found - '%s')%n",
                        DISPLAY_NAME, issueComment.getBody());

                cause = checkComment(prDecisionContext, issueComment, prUserRestriction, listener);
                if (nonNull(cause)) {
                    break;
                }
            }
        }
    } catch (Exception e) {
        LOG.warn("Couldn't obtain comments: {}", e);
        listener.error("Couldn't obtain comments", e);
    }

    if (isNull(cause)) {
        LOG.debug("No matching comments found for {}", remotePR.getNumber());
        llog.println("No matching comments found for " + remotePR.getNumber());
    }

    return cause;
}
 
Example #23
Source File: AnsibleAdHocCommandBuilder.java    From ansible-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public void perform(@Nonnull Run<?, ?> run, @Nonnull FilePath ws, @Nonnull Launcher launcher, @Nonnull TaskListener listener) throws InterruptedException, IOException {
    try {
        CLIRunner runner = new CLIRunner(run, ws, launcher, listener);
        Computer computer = Computer.currentComputer();
        if (computer == null) {
            throw new AbortException("The ansible playbook build step requires to be launched on a node");
        }
        String exe = AnsibleInstallation.getExecutable(ansibleName, AnsibleCommand.ANSIBLE, computer.getNode(), listener, run.getEnvironment(listener));
        AnsibleAdHocCommandInvocation invocation = new AnsibleAdHocCommandInvocation(exe, run, ws, listener);
        invocation.setHostPattern(hostPattern);
        invocation.setInventory(inventory);
        invocation.setModule(module);
        invocation.setModuleCommand(command);
        invocation.setSudo(sudo, sudoUser);
        invocation.setForks(forks);
        invocation.setCredentials(StringUtils.isNotBlank(credentialsId) ?
                CredentialsProvider.findCredentialById(credentialsId, StandardUsernameCredentials.class, run) :
                null);
        invocation.setAdditionalParameters(additionalParameters);
        invocation.setHostKeyCheck(hostKeyChecking);
        invocation.setUnbufferedOutput(unbufferedOutput);
        invocation.setColorizedOutput(colorizedOutput);
        if (!invocation.execute(runner)) {
            throw new AbortException("Ansible Ad-Hoc command execution failed");
        }
    } catch (IOException ioe) {
        Util.displayIOException(ioe, listener);
        ioe.printStackTrace(listener.fatalError(hudson.tasks.Messages.CommandInterpreter_CommandFailed()));
        throw ioe;
    } catch (AnsibleInvocationException aie) {
        listener.fatalError(aie.getMessage());
        throw new AbortException(aie.getMessage());
    }
}
 
Example #24
Source File: DockerTool.java    From docker-commons-plugin with MIT License 5 votes vote down vote up
/**
 * Gets the executable name to use for a given launcher.
 * Suitable for the first item in {@link ArgumentListBuilder}.
 * @param name the name of the selected tool, or null for the default
 * @param node optionally, a node (such as a slave) on which we are running Docker
 * @param listener a listener, required in case {@code node} is not null
 * @param env optionally, environment variables to use when expanding the home directory
 * @return {@code docker} or an absolute path
 */
public static @Nonnull String getExecutable(@CheckForNull String name, @CheckForNull Node node, @Nullable TaskListener listener, @CheckForNull EnvVars env) throws IOException, InterruptedException {
    if (name != null) {
        Jenkins j = Jenkins.getInstance();
        if (j != null) {
            for (DockerTool tool : j.getDescriptorByType(DescriptorImpl.class).getInstallations()) {
                if (tool.getName().equals(name)) {
                    if (node != null) {
                        tool = tool.forNode(node, listener);
                    }
                    if (env != null) {
                        tool = tool.forEnvironment(env);
                    }
                    String home = Util.fixEmpty(tool.getHome());
                    if (home != null) {
                        if (node != null) {
                            FilePath homeFP = node.createPath(home);
                            if (homeFP != null) {
                                return homeFP.child("bin/docker").getRemote();
                            }
                        }
                        return home + "/bin/docker";
                    }
                }
            }
        }
    }
    return COMMAND;
}
 
Example #25
Source File: AWSIdentityStep.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
@Override
protected Map<String, String> run() throws Exception {
	AWSSecurityTokenService sts = AWSClientFactory.create(AWSSecurityTokenServiceClientBuilder.standard(), this.getContext());
	GetCallerIdentityResult identity = sts.getCallerIdentity(new GetCallerIdentityRequest());

	this.getContext().get(TaskListener.class).getLogger().format("Current AWS identity: %s - %s - %s %n", identity.getAccount(), identity.getUserId(), identity.getArn());

	Map<String, String> info = new HashMap<>();
	info.put("account", identity.getAccount());
	info.put("user", identity.getUserId());
	info.put("arn", identity.getArn());
	return info;
}
 
Example #26
Source File: BuildListener.java    From audit-log-plugin with MIT License 5 votes vote down vote up
/**
 * Fired when a build is completed, event logged via Log4j-audit.
 *
 * @param run of type Run having the build information
 * @param listener of type TaskListener that the onCompleted method expects
 */
@Override
public void onCompleted(Run run, TaskListener listener) {
    BuildFinish buildFinish = LogEventFactory.getEvent(BuildFinish.class);

    List causeObjects = run.getCauses();
    List<String> causes = new ArrayList<>(causeObjects.size());
    for (Object cause: causeObjects) {
        Cause c = (Cause)cause;
        causes.add(c.getShortDescription());
    }
    buildFinish.setBuildNumber(run.getNumber());
    buildFinish.setCause(causes);
    buildFinish.setProjectName(run.getParent().getFullName());

    Instant start = Instant.ofEpochMilli(run.getStartTimeInMillis());
    Instant finish = start.plusMillis(run.getDuration());
    buildFinish.setTimestamp(formatDateISO(finish.toEpochMilli()));

    User user = User.current();
    if(user != null)
        buildFinish.setUserId(user.getId());
    else
        buildFinish.setUserId(null);

    buildFinish.logEvent();
}
 
Example #27
Source File: AWSCodePipelineSCMTest.java    From aws-codepipeline-plugin-for-jenkins with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws IOException, InterruptedException, ReflectiveOperationException {
    super.setUp();

    descriptor = new AWSCodePipelineSCM.DescriptorImpl(false);

    when(mockBuild.getEnvironment(any(TaskListener.class))).thenReturn(envVars);
    when(envVars.get(any(String.class))).thenReturn("Project");
    when(model.getJob()).thenReturn(mockJob);
    when(mockJob.getId()).thenReturn(jobId);

    CodePipelineStateService.setModel(model);
}
 
Example #28
Source File: GitHubPRDecisionContext.java    From github-integration-plugin with MIT License 5 votes vote down vote up
@Deprecated
protected GitHubPRDecisionContext(@CheckForNull GHPullRequest remotePR,
                                  @CheckForNull GitHubPRPullRequest localPR,
                                  @CheckForNull GitHubPRUserRestriction prUserRestriction,
                                  GitHubSCMSource source,
                                  GitHubPRHandler prHandler,
                                  GitHubPRTrigger prTrigger,
                                  @Nonnull TaskListener listener) {
    this(remotePR, localPR, null, prUserRestriction, source, prHandler, prTrigger, listener);
}
 
Example #29
Source File: OpenShiftImageStreams.java    From jenkins-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public void postCheckout(@Nonnull Run<?, ?> build,
        @Nonnull Launcher launcher, @Nonnull FilePath workspace,
        @Nonnull TaskListener listener) throws IOException,
        InterruptedException {
    if (build.getResult() == Result.FAILURE) {
        EnvVars env = build.getEnvironment(listener);
        String msg = String.format(
                MessageConstants.SCM_IMAGESTREAM_NOT_FOUND,
                getImageStreamName(env), getTag(env));
        throw new AbortException(msg);
    }
}
 
Example #30
Source File: ScanForIssuesStep.java    From warnings-ng-plugin with MIT License 5 votes vote down vote up
@Override
protected AnnotatedReport run() throws IOException, InterruptedException, IllegalStateException {
    FilePath workspace = getWorkspace();
    TaskListener listener = getTaskListener();

    IssuesScanner issuesScanner = new IssuesScanner(tool, filters,
            getCharset(sourceCodeEncoding), workspace, sourceDirectory,
            getRun(), new FilePath(getRun().getRootDir()), listener,
            isBlameDisabled ? BlameMode.DISABLED : BlameMode.ENABLED,
            isForensicsDisabled ? ForensicsMode.DISABLED : ForensicsMode.ENABLED);

    return issuesScanner.scan();
}