Search in sources :

Example 1 with Localizable

use of org.jvnet.localizer.Localizable in project code-coverage-api-plugin by jenkinsci.

the class CoverageChecksPublisherTest method shouldPublishFailedCheck.

@Test
public void shouldPublishFailedCheck() {
    ChecksDetails expectedDetails = new ChecksDetailsBuilder().withName("Code Coverage").withStatus(ChecksStatus.COMPLETED).withConclusion(ChecksConclusion.FAILURE).withDetailsURL(JENKINS_BASE_URL + "/" + BUILD_LINK + COVERAGE_URL_NAME).withOutput(new ChecksOutputBuilder().withTitle("Line: 60.00%. Branch: 40.00%.").withSummary("## Coverage Healthy score is 10%.\n" + "## Failed because coverage is unhealthy.").withText("## Conditional\n* :white_check_mark: Coverage: 40%\n" + "## Line\n* :white_check_mark: Coverage: 60%\n").withText("||Conditional|Line|\n" + "|:-:|:-:|:-:|\n" + "|:white_check_mark: **Coverage**|40.00%|60.00%|\n" + "|:chart_with_upwards_trend: **Trend**|-|-|").build()).build();
    Run build = mock(Run.class);
    CoverageResult result = createCoverageResult((float) 0.6, (float) 0.4);
    when(result.getPreviousResult()).thenReturn(null);
    when(result.getOwner()).thenReturn(build);
    when(build.getUrl()).thenReturn(BUILD_LINK);
    when(build.getPreviousSuccessfulBuild()).thenReturn(null);
    CoverageAction action = getCoverageAction(result);
    Localizable localizable = mock(Localizable.class);
    when(localizable.toString()).thenReturn("Coverage Healthy score is 10%");
    action.setHealthReport(new HealthReport(100, localizable));
    action.setFailMessage("Failed because coverage is unhealthy.");
    assertThat(new CoverageChecksPublisher(action, createJenkins()).extractChecksDetails()).usingRecursiveComparison().isEqualTo(expectedDetails);
}
Also used : ChecksOutputBuilder(io.jenkins.plugins.checks.api.ChecksOutput.ChecksOutputBuilder) HealthReport(hudson.model.HealthReport) ChecksDetailsBuilder(io.jenkins.plugins.checks.api.ChecksDetails.ChecksDetailsBuilder) Run(hudson.model.Run) ChecksDetails(io.jenkins.plugins.checks.api.ChecksDetails) CoverageResult(io.jenkins.plugins.coverage.targets.CoverageResult) Localizable(org.jvnet.localizer.Localizable) Test(org.junit.Test)

Example 2 with Localizable

use of org.jvnet.localizer.Localizable in project code-coverage-api-plugin by jenkinsci.

the class CoverageChecksPublisherTest method shouldConstructChecksDetailsWithIncreasedLineCoverageAndConditionalCoverage.

@Test
public void shouldConstructChecksDetailsWithIncreasedLineCoverageAndConditionalCoverage() {
    ChecksDetails expectedDetails = new ChecksDetailsBuilder().withName("Code Coverage").withStatus(ChecksStatus.COMPLETED).withConclusion(ChecksConclusion.SUCCESS).withDetailsURL(JENKINS_BASE_URL + "/" + BUILD_LINK + COVERAGE_URL_NAME).withOutput(new ChecksOutputBuilder().withTitle("Line: 50.00% (+10.00% against target branch). " + "Branch: 50.00% (+15.00% against target branch).").withSummary("* ### [Target branch build](" + JENKINS_BASE_URL + "/" + TARGET_BUILD_LINK + ")\n" + "* ### [Last successful build](" + JENKINS_BASE_URL + "/" + LAST_SUCCESSFUL_BUILD_LINK + ")\n" + "## " + HEALTH_REPORT + ".").withText("## Conditional\n* :white_check_mark: Coverage: 50%\n* :arrow_up: Trend: 20%\n" + "## Line\n* :white_check_mark: Coverage: 50%\n* :arrow_up: Trend: 10%\n").withText("||Conditional|Line|\n" + "|:-:|:-:|:-:|\n" + "|:white_check_mark: **Coverage**|50.00%|50.00%|\n" + "|:chart_with_upwards_trend: **Trend**|+20.00% :arrow_up:|+10.00% :arrow_up:|").build()).build();
    CoverageResult result = createCoverageResult((float) 0.4, (float) 0.3, (float) 0.5, (float) 0.5, TARGET_BUILD_LINK, +10, +15);
    CoverageAction action = new CoverageAction(result);
    Localizable localizable = mock(Localizable.class);
    when(localizable.toString()).thenReturn(HEALTH_REPORT);
    action.setHealthReport(new HealthReport(100, localizable));
    assertThat(new CoverageChecksPublisher(createActionWithDefaultHealthReport(result), createJenkins()).extractChecksDetails()).usingRecursiveComparison().isEqualTo(expectedDetails);
}
Also used : ChecksOutputBuilder(io.jenkins.plugins.checks.api.ChecksOutput.ChecksOutputBuilder) HealthReport(hudson.model.HealthReport) ChecksDetailsBuilder(io.jenkins.plugins.checks.api.ChecksDetails.ChecksDetailsBuilder) ChecksDetails(io.jenkins.plugins.checks.api.ChecksDetails) CoverageResult(io.jenkins.plugins.coverage.targets.CoverageResult) Localizable(org.jvnet.localizer.Localizable) Test(org.junit.Test)

Example 3 with Localizable

use of org.jvnet.localizer.Localizable in project code-coverage-api-plugin by jenkinsci.

the class CoverageChecksPublisherTest method shouldConstructChecksDetailsWithDecreasedLineCoverageAndConditionalCoverage.

@Test
public void shouldConstructChecksDetailsWithDecreasedLineCoverageAndConditionalCoverage() {
    ChecksDetails expectedDetails = new ChecksDetailsBuilder().withName("Code Coverage").withStatus(ChecksStatus.COMPLETED).withConclusion(ChecksConclusion.SUCCESS).withDetailsURL(JENKINS_BASE_URL + "/job/pipeline-coding-style/job/PR-3/49/coverage").withOutput(new ChecksOutputBuilder().withTitle("Line: 50.00% (-10.00% against target branch). " + "Branch: 50.00% (-15.00% against target branch).").withSummary("* ### [Target branch build](" + JENKINS_BASE_URL + "/" + TARGET_BUILD_LINK + ")\n" + "* ### [Last successful build](" + JENKINS_BASE_URL + "/" + LAST_SUCCESSFUL_BUILD_LINK + ")\n" + "## " + HEALTH_REPORT + ".").withText("## Conditional\n* :white_check_mark: Coverage: 50%\n* :arrow_down: Trend: 15%\n" + "## Line\n* :white_check_mark: Coverage: 50%\n* :arrow_down: Trend: 10%\n").withText("||Conditional|Line|\n" + "|:-:|:-:|:-:|\n" + "|:white_check_mark: **Coverage**|50.00%|50.00%|\n" + "|:chart_with_upwards_trend: **Trend**|-20.00% :arrow_down:|-10.00% :arrow_down:|").build()).build();
    CoverageResult result = createCoverageResult((float) 0.6, (float) 0.7, (float) 0.5, (float) 0.5, TARGET_BUILD_LINK, -10, -15);
    CoverageAction action = new CoverageAction(result);
    Localizable localizable = mock(Localizable.class);
    when(localizable.toString()).thenReturn(HEALTH_REPORT);
    action.setHealthReport(new HealthReport(100, localizable));
    assertThat(new CoverageChecksPublisher(createActionWithDefaultHealthReport(result), createJenkins()).extractChecksDetails()).usingRecursiveComparison().isEqualTo(expectedDetails);
}
Also used : ChecksOutputBuilder(io.jenkins.plugins.checks.api.ChecksOutput.ChecksOutputBuilder) HealthReport(hudson.model.HealthReport) ChecksDetailsBuilder(io.jenkins.plugins.checks.api.ChecksDetails.ChecksDetailsBuilder) ChecksDetails(io.jenkins.plugins.checks.api.ChecksDetails) CoverageResult(io.jenkins.plugins.coverage.targets.CoverageResult) Localizable(org.jvnet.localizer.Localizable) Test(org.junit.Test)

Example 4 with Localizable

use of org.jvnet.localizer.Localizable in project code-coverage-api-plugin by jenkinsci.

the class CoverageChecksPublisherTest method shouldReportNoLineOrBranchCoverageInChecksTitle.

@Test
public void shouldReportNoLineOrBranchCoverageInChecksTitle() {
    Run build = mock(Run.class);
    CoverageResult result = mock(CoverageResult.class);
    when(result.getOwner()).thenReturn(build);
    when(build.getPreviousSuccessfulBuild()).thenReturn(null);
    when(build.getUrl()).thenReturn(BUILD_LINK);
    Map<CoverageElement, Ratio> ratios = new HashMap<>();
    when(result.getResults()).thenReturn(ratios);
    when(result.getCoverage(CoverageElement.LINE)).thenReturn(null);
    when(result.getCoverage(CoverageElement.CONDITIONAL)).thenReturn(null);
    when(result.getCoverageTrends()).thenReturn(null);
    CoverageAction action = new CoverageAction(result);
    Localizable localizable = mock(Localizable.class);
    when(localizable.toString()).thenReturn(HEALTH_REPORT);
    action.setHealthReport(new HealthReport(100, localizable));
    assertThat(new CoverageChecksPublisher(createActionWithDefaultHealthReport(result), createJenkins()).extractChecksDetails().getOutput()).isPresent().get().hasFieldOrPropertyWithValue("title", Optional.of("No line or branch coverage has been computed."));
}
Also used : HashMap(java.util.HashMap) HealthReport(hudson.model.HealthReport) Run(hudson.model.Run) Ratio(io.jenkins.plugins.coverage.targets.Ratio) CoverageElement(io.jenkins.plugins.coverage.targets.CoverageElement) CoverageResult(io.jenkins.plugins.coverage.targets.CoverageResult) Localizable(org.jvnet.localizer.Localizable) Test(org.junit.Test)

Example 5 with Localizable

use of org.jvnet.localizer.Localizable in project azure-vm-agents-plugin by jenkinsci.

the class AzureVMAgentSSHLauncher method launch.

@Override
public void launch(SlaveComputer agentComputer, TaskListener listener) {
    if (!(agentComputer instanceof AzureVMComputer)) {
        LOGGER.log(Level.INFO, "AgentComputer is invalid {0}", agentComputer);
        return;
    }
    AzureVMComputer computer = (AzureVMComputer) agentComputer;
    AzureVMAgent agent = computer.getNode();
    if (agent == null) {
        LOGGER.log(Level.INFO, "Agent node is null");
        return;
    }
    LOGGER.log(Level.FINE, "launching agent {0}", computer.getName());
    final boolean isUnix = agent.getOsType().equals(OperatingSystemTypes.LINUX);
    // This still means that a delete agent will eventually get cleaned up.
    try {
        if (!agent.isVMAliveOrHealthy()) {
            LOGGER.log(Level.INFO, "Agent {0} is shut down, deleted, etc. Not attempting to connect", computer.getName());
            return;
        }
    } catch (Exception e1) {
    // ignoring exception purposefully
    }
    // Block cleanup while we attempt to start.
    agent.blockCleanUpAction();
    PrintStream logger = listener.getLogger();
    boolean successful = false;
    Session session = null;
    SlaveComputer slaveComputer = agent.getComputer();
    if (slaveComputer == null) {
        LOGGER.log(Level.SEVERE, "Got null computer.");
        handleLaunchFailure(agent, Constants.AGENT_POST_PROV_NULL_COMPUTER);
        return;
    }
    try {
        session = connectToSsh(agent);
    } catch (UnknownHostException e) {
        LOGGER.log(Level.SEVERE, "Got unknown host exception. Virtual machine might have been deleted already", e);
    } catch (ConnectException e) {
        LOGGER.log(Level.SEVERE, "Got connect exception while launching " + agent.getNodeName() + ". Might be due to firewall rules", e);
        handleLaunchFailure(agent, Constants.AGENT_POST_PROV_CONN_FAIL);
    } catch (Exception e) {
        // Checking if we need to mark template as disabled. Need to re-visit this logic based on tests.
        if (e.getMessage() != null && e.getMessage().equalsIgnoreCase("Auth fail")) {
            LOGGER.log(Level.SEVERE, "Authentication failure launching " + agent.getNodeName() + ". Image may not be supporting password authentication", e);
            handleLaunchFailure(agent, Constants.AGENT_POST_PROV_AUTH_FAIL);
        } else {
            LOGGER.log(Level.SEVERE, "Exception launching" + agent.getNodeName(), e);
            handleLaunchFailure(agent, Constants.AGENT_POST_PROV_CONN_FAIL + e.getMessage());
        }
    } finally {
        if (session == null) {
            slaveComputer.setAcceptingTasks(false);
            agent.setCleanUpAction(CleanUpAction.DELETE, Messages._Agent_Failed_To_Connect());
            return;
        }
    }
    Localizable cleanUpReason = null;
    try {
        final Session cleanupSession = session;
        String initScript = agent.getInitScript();
        // Executing script only if script is not executed even once
        String command;
        if (isUnix) {
            command = "test -e ~/.azure-agent-init";
        } else {
            command = "dir C:\\.azure-agent-init";
        }
        if (StringUtils.isNotBlank(initScript) && executeRemoteCommand(session, command, logger, isUnix) != 0) {
            LOGGER.fine("Init script is not null, " + "preparing to execute script remotely on " + agent.getNodeName());
            if (isUnix) {
                copyFileToRemote(session, new ByteArrayInputStream(initScript.getBytes(StandardCharsets.UTF_8)), REMOTE_INIT_FILE_NAME);
            } else {
                copyFileToRemote(session, new ByteArrayInputStream(initScript.getBytes(StandardCharsets.UTF_8)), REMOTE_INIT_FILE_NAME_WINDOWS);
            }
            // Execute initialization script
            // Make sure to change file permission for execute if needed. TODO: need to test
            // Grab the username/pass
            StandardUsernamePasswordCredentials creds = AzureUtil.getCredentials(agent.getVMCredentialsId());
            if (isUnix) {
                command = "sh " + REMOTE_INIT_FILE_NAME;
            } else {
                command = "powershell " + REMOTE_INIT_FILE_NAME_WINDOWS;
            }
            int exitStatus = executeRemoteCommand(session, command, logger, isUnix, agent.getExecuteInitScriptAsRoot(), creds.getPassword().getPlainText());
            if (exitStatus != 0) {
                if (agent.getDoNotUseMachineIfInitFails()) {
                    LOGGER.log(Level.SEVERE, "Init script failed on " + agent.getNodeName() + ": exit code={0} " + "(marking agent for deletion)", exitStatus);
                    cleanUpReason = Messages._Agent_Failed_Init_Script();
                    return;
                } else {
                    LOGGER.log(Level.INFO, "Init script failed on " + agent.getNodeName() + ": exit code={0} (ignoring)", exitStatus);
                }
            } else {
                LOGGER.fine("Init script on " + agent.getNodeName() + " got executed successfully");
            }
            // In Windows, restart sshd to get new system environment variables
            if (!isUnix) {
                executeRemoteCommand(session, "powershell -ExecutionPolicy Bypass Restart-Service sshd", logger, isUnix);
            }
            /* Create a new session after the init script has executed to
                 * make sure we pick up whatever new settings have been set up
                 * for our user
                 *
                 * https://issues.jenkins-ci.org/browse/JENKINS-40291
                 */
            session.disconnect();
            session = connectToSsh(agent);
            // Create tracking file
            if (isUnix) {
                command = "touch ~/.azure-agent-init";
            } else {
                command = "copy NUL C:\\.azure-agent-init";
            }
            executeRemoteCommand(session, command, logger, isUnix);
        }
        LOGGER.fine("Checking for java runtime on " + agent.getNodeName());
        if (executeRemoteCommand(session, agent.getJavaPath() + " -fullversion", logger, isUnix) != 0) {
            LOGGER.info("Java not found on " + agent.getNodeName() + ". " + "At a minimum init script should ensure that java runtime is installed");
            handleLaunchFailure(agent, Constants.AGENT_POST_PROV_JAVA_NOT_FOUND);
            return;
        }
        LOGGER.fine("Java runtime present on " + agent.getNodeName() + ", copying remoting.jar to remote");
        InputStream inputStream = new ByteArrayInputStream(Jenkins.get().getJnlpJars("remoting.jar").readFully());
        copyFileToRemote(session, inputStream, "remoting.jar");
        String remotingWorkingDirectory = getRemotingWorkingDirectory(isUnix);
        String remotingDefaultOptions = "-workDir " + remotingWorkingDirectory;
        String remotingOptions = Util.fixEmpty(agent.getRemotingOptions()) != null ? agent.getRemotingOptions() : remotingDefaultOptions;
        String jvmopts = agent.getJvmOptions();
        String execCommand = agent.getJavaPath() + " " + (StringUtils.isNotBlank(jvmopts) ? jvmopts : "") + " -jar remoting.jar " + remotingOptions;
        LOGGER.log(Level.INFO, "Launching agent " + agent.getNodeName() + ": {0}", execCommand);
        final ChannelExec jschChannel = (ChannelExec) session.openChannel("exec");
        jschChannel.setCommand(execCommand);
        jschChannel.connect();
        LOGGER.info("Connected " + agent.getNodeName() + " successfully");
        computer.setChannel(jschChannel.getInputStream(), jschChannel.getOutputStream(), logger, new Listener() {

            @Override
            public void onClosed(Channel channel, IOException cause) {
                jschChannel.disconnect();
                cleanupSession.disconnect();
            }
        });
        LOGGER.info("Launched agent " + agent.getNodeName() + " successfully");
        // There's a chance that it was marked as delete for instance, if the node
        // was unreachable and then someone hit connect and it worked.  Reset the node cleanup
        // state to the default for the node.
        agent.clearCleanUpAction();
        successful = true;
    } catch (Exception e) {
        LOGGER.log(Level.SEVERE, "Got exception on agent " + agent.getNodeName(), e);
    } finally {
        if (!successful) {
            session.disconnect();
            if (cleanUpReason == null) {
                cleanUpReason = Messages._Agent_Failed_To_Connect();
            }
            slaveComputer.setAcceptingTasks(false);
            // Set the machine to be deleted by the cleanup task
            agent.setCleanUpAction(CleanUpAction.DELETE, cleanUpReason);
        }
    }
}
Also used : SlaveComputer(hudson.slaves.SlaveComputer) Listener(hudson.remoting.Channel.Listener) TaskListener(hudson.model.TaskListener) AzureVMComputer(com.microsoft.azure.vmagent.AzureVMComputer) UnknownHostException(java.net.UnknownHostException) AzureVMAgent(com.microsoft.azure.vmagent.AzureVMAgent) Channel(hudson.remoting.Channel) ConnectException(java.net.ConnectException) UnknownHostException(java.net.UnknownHostException) Localizable(org.jvnet.localizer.Localizable) StandardUsernamePasswordCredentials(com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials) ConnectException(java.net.ConnectException)

Aggregations

Localizable (org.jvnet.localizer.Localizable)42 FilePath (hudson.FilePath)28 HealthReport (hudson.model.HealthReport)8 CoverageResult (io.jenkins.plugins.coverage.targets.CoverageResult)7 Test (org.junit.Test)6 ChecksDetails (io.jenkins.plugins.checks.api.ChecksDetails)5 ChecksDetailsBuilder (io.jenkins.plugins.checks.api.ChecksDetails.ChecksDetailsBuilder)5 ChecksOutputBuilder (io.jenkins.plugins.checks.api.ChecksOutput.ChecksOutputBuilder)5 ExtensionPoint (hudson.ExtensionPoint)2 Run (hudson.model.Run)2 Ratio (io.jenkins.plugins.coverage.targets.Ratio)2 File (java.io.File)2 HashMap (java.util.HashMap)2 StandardUsernamePasswordCredentials (com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials)1 AzureVMAgent (com.microsoft.azure.vmagent.AzureVMAgent)1 AzureVMComputer (com.microsoft.azure.vmagent.AzureVMComputer)1 TaskListener (hudson.model.TaskListener)1 Channel (hudson.remoting.Channel)1 Listener (hudson.remoting.Channel.Listener)1 SlaveComputer (hudson.slaves.SlaveComputer)1