hudson.model.Node Java Examples

The following examples show how to use hudson.model.Node. 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: ParallelsDesktopConnectorSlaveComputer.java    From jenkins-parallels with MIT License 6 votes vote down vote up
public Node createSlaveOnVM(ParallelsDesktopVM vm) throws Exception
{
	String vmId = vm.getVmid();
	String slaveName = vm.getSlaveName();
	LOGGER.log(Level.SEVERE, "Starting slave '" + slaveName+ "'");
	LOGGER.log(Level.SEVERE, "Starting virtual machine '" + vmId + "'");
	RunVmCallable command = new RunVmCallable("start", vmId);
	try
	{
		forceGetChannel().call(command);
		LOGGER.log(Level.SEVERE, "Waiting for IP...");
		String ip = getVmIPAddress(vmId);
		LOGGER.log(Level.SEVERE, "Got IP address for VM " + vmId + ": " + ip);
		vm.setLauncherIP(ip);
	}
	catch (Exception ex)
	{
		LOGGER.log(Level.SEVERE, ex.toString());
	}
	return new ParallelsDesktopVMSlave(vm, this);
}
 
Example #2
Source File: DockerCloud.java    From docker-plugin with MIT License 6 votes vote down vote up
/**
 * Multiple amis can have the same label.
 *
 * @return Templates matched to requested label assuming slave Mode
 */
public List<DockerTemplate> getTemplates(Label label) {
    final List<DockerTemplate> dockerTemplates = new ArrayList<>();

    for (DockerTemplate t : getTemplates()) {
        if ( t.getDisabled().isDisabled() ) {
            continue; // pretend it doesn't exist
        }
        if (label == null && t.getMode() == Node.Mode.NORMAL) {
            dockerTemplates.add(t);
        }

        if (label != null && label.matches(t.getLabelSet())) {
            dockerTemplates.add(t);
        }
    }

    // add temporary templates matched to requested label
    for (DockerTemplate template : getJobTemplates().values()) {
        if (label != null && label.matches(template.getLabelSet())) {
            dockerTemplates.add(template);
        }
    }

    return dockerTemplates;
}
 
Example #3
Source File: EC2FleetCloudAwareUtilsTest.java    From ec2-spot-jenkins-plugin with Apache License 2.0 6 votes vote down vote up
@Before
public void before() {
    PowerMockito.mockStatic(LabelFinder.class);

    PowerMockito.mockStatic(Jenkins.class);
    PowerMockito.when(Jenkins.getActiveInstance()).thenReturn(jenkins);

    when(oldCloud.getOldId()).thenReturn("cloud");
    when(computer.getCloud()).thenReturn(oldCloud);
    when(node.getCloud()).thenReturn(oldCloud);

    when(cloud.getOldId()).thenReturn("cloud");
    when(otherCloud.getOldId()).thenReturn("other");

    when(jenkins.getNodes()).thenReturn(Collections.<Node>emptyList());
    when(jenkins.getComputers()).thenReturn(new Computer[0]);
}
 
Example #4
Source File: ContainerExecDecoratorTest.java    From kubernetes-plugin with Apache License 2.0 6 votes vote down vote up
private ProcReturn execCommandInContainer(String containerName, Node node, boolean quiet, String... cmd) throws Exception {
    if (containerName != null && ! containerName.isEmpty()) {
        decorator.setContainerName(containerName);
    }
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    Launcher launcher = decorator
            .decorate(new DummyLauncher(new StreamTaskListener(new TeeOutputStream(out, System.out))), node);
    Map<String, String> envs = new HashMap<>(100);
    for (int i = 0; i < 50; i++) {
        envs.put("aaaaaaaa" + i, "bbbbbbbb");
    }
    envs.put("workingDir1", "/home/jenkins/agent");

    ContainerExecProc proc = (ContainerExecProc) launcher
            .launch(launcher.new ProcStarter().pwd("/tmp").cmds(cmd).envs(envs).quiet(quiet));
    // wait for proc to finish (shouldn't take long)
    for (int i = 0; proc.isAlive() && i < 200; i++) {
        Thread.sleep(100);
    }
    assertFalse("proc is alive", proc.isAlive());
    int exitCode = proc.join();
    return new ProcReturn(proc, exitCode, out.toString());
}
 
Example #5
Source File: DockerContainerWatchdog.java    From docker-plugin with MIT License 6 votes vote down vote up
private Map<String, Node> loadNodeMap() {
    Map<String, Node> nodeMap = new HashMap<>();

    for (Node n : getAllNodes()) {
        nodeMap.put(n.getNodeName(), n);

        /*
         * Note: We are taking all nodes into consideration, and not just
         * those which have been created by this plugin.
         * Reasoning is as follows:
         * The node names of docker-plugin's created containers are generated by the plugin itself.
         * The identifiers are unique (within the Jenkins server).
         * If someone creates a node that exactly matches such a unique name, then
         * this is very likely to have been done on purpose.
         * If we ignored such nodes, we could end up removing containers that the
         * user did not want cleaned up.
         * Whereas if we do not ignore such nodes then there's no lasting harm.
         * 
         * For further details on that discussion, see https://github.com/jenkinsci/docker-plugin/pull/658#discussion_r192695136
         */
    }

    LOGGER.info("We currently have {} nodes assigned to this Jenkins instance, which we will check", nodeMap.size());

    return nodeMap;
}
 
Example #6
Source File: WithMavenStepExecution2.java    From pipeline-maven-plugin with MIT License 6 votes vote down vote up
private String obtainMvnExecutableFromMavenInstallation(String mavenInstallationName) throws IOException, InterruptedException {

        MavenInstallation mavenInstallation = null;
        for (MavenInstallation i : getMavenInstallations()) {
            if (mavenInstallationName.equals(i.getName())) {
                mavenInstallation = i;
                LOGGER.log(Level.FINE, "Found maven installation {0} with installation home {1}", new Object[]{mavenInstallation.getName(), mavenInstallation.getHome()});
                break;
            }
        }
        if (mavenInstallation == null) {
            throw new AbortException("Could not find specified Maven installation '" + mavenInstallationName + "'.");
        }
        Node node = getComputer().getNode();
        if (node == null) {
            throw new AbortException("Could not obtain the Node for the computer: " + getComputer().getName());
        }
        mavenInstallation = mavenInstallation.forNode(node, listener).forEnvironment(env);
        mavenInstallation.buildEnvVars(envOverride);
        console.println("[withMaven] using Maven installation '" + mavenInstallation.getName() + "'");
        String mvnExecPath = mavenInstallation.getExecutable(launcher);

        return mvnExecPath;
    }
 
Example #7
Source File: DockerContainerITest.java    From warnings-ng-plugin with MIT License 6 votes vote down vote up
/**
 * Build a maven project on a docker container agent.
 *
 * @throws IOException
 *         When the node assignment of the agent fails.
 * @throws InterruptedException
 *         If the creation of the docker container fails.
 */
@Test
public void shouldBuildMavenOnAgent() throws IOException, InterruptedException {
    assumeThat(isWindows()).as("Running on Windows").isFalse();

    DumbSlave agent = createDockerContainerAgent(javaDockerRule.get());

    FreeStyleProject project = createFreeStyleProject();
    project.setAssignedNode(agent);

    createFileInAgentWorkspace(agent, project, "src/main/java/Test.java", getSampleJavaFile());
    createFileInAgentWorkspace(agent, project, "pom.xml", getSampleMavenFile());
    project.getBuildersList().add(new Maven("compile", null));
    enableWarnings(project, createTool(new Java(), ""));

    scheduleSuccessfulBuild(project);

    FreeStyleBuild lastBuild = project.getLastBuild();
    AnalysisResult result = getAnalysisResult(lastBuild);

    assertThat(result).hasTotalSize(2);
    assertThat(lastBuild.getBuiltOn().getLabelString()).isEqualTo(((Node) agent).getLabelString());
}
 
Example #8
Source File: DockerContainerITest.java    From warnings-ng-plugin with MIT License 6 votes vote down vote up
/**
 * Runs a make file to compile a cpp file on a docker container agent.
 *
 * @throws IOException
 *         When the node assignment of the agent fails.
 * @throws InterruptedException
 *         If the creation of the docker container fails.
 */
@Test
public void shouldBuildMakefileOnAgent() throws IOException, InterruptedException {
    assumeThat(isWindows()).as("Running on Windows").isFalse();

    DumbSlave agent = createDockerContainerAgent(gccDockerRule.get());

    FreeStyleProject project = createFreeStyleProject();
    project.setAssignedNode(agent);

    createFileInAgentWorkspace(agent, project, "test.cpp", getSampleCppFile());
    createFileInAgentWorkspace(agent, project, "makefile", getSampleMakefileFile());
    project.getBuildersList().add(new Shell("make"));
    enableWarnings(project, createTool(new Gcc4(), ""));

    scheduleSuccessfulBuild(project);

    FreeStyleBuild lastBuild = project.getLastBuild();
    AnalysisResult result = getAnalysisResult(lastBuild);

    assertThat(result).hasTotalSize(1);
    assertThat(lastBuild.getBuiltOn().getLabelString()).isEqualTo(((Node) agent).getLabelString());
}
 
Example #9
Source File: UiIntegrationTest.java    From ec2-spot-jenkins-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldShowNodeConfigurationPage() throws Exception {
    EC2FleetCloud cloud = new EC2FleetCloud(null, null, null, null, null, null, null,
            null, null, null, false, false,
            0, 0, 0, 0, false, false,
            false, 0, 0, false,
            10, false);
    j.jenkins.clouds.add(cloud);

    j.jenkins.addNode(new EC2FleetNode("node-name", "", "", 1,
            Node.Mode.EXCLUSIVE, "", new ArrayList<NodeProperty<?>>(), cloud,
            j.createComputerLauncher(null)));

    HtmlPage page = j.createWebClient().goTo("computer/node-name/configure");

    assertTrue(StringUtils.isNotBlank(((HtmlTextInput) getElementsByNameWithoutJdk(page, "_.name").get(0)).getText()));
}
 
Example #10
Source File: ContainerExecDecoratorTest.java    From kubernetes-plugin with Apache License 2.0 6 votes vote down vote up
@Test
@Issue("JENKINS-58975")
public void testContainerExecOnCustomWorkingDirWithComputeEnvVars() throws Exception {
    EnvVars computeEnvVars = new EnvVars();
    computeEnvVars.put("MyDir", "dir");
    computeEnvVars.put("MyCustomDir", "/home/jenkins/agent");
    Computer computer = mock(Computer.class);
    doReturn(computeEnvVars).when(computer).getEnvironment();

    doReturn(computer).when((Node)agent).toComputer();
    ProcReturn r = execCommandInContainer("busybox1", agent, false, "env");
    assertTrue("Environment variable workingDir1 should be changed to /home/jenkins/agent1",
            r.output.contains("workingDir1=/home/jenkins/agent1"));
    assertTrue("Environment variable MyCustomDir should be changed to /home/jenkins/agent1",
            r.output.contains("MyCustomDir=/home/jenkins/agent1"));
    assertEquals(0, r.exitCode);
    assertFalse(r.proc.isAlive());
}
 
Example #11
Source File: EC2FleetCloudTest.java    From ec2-spot-jenkins-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void update_shouldAddNodeWithScaledNumExecutors_whenWeightPresentAndEnabled() throws IOException {
    // given
    when(ec2Api.connect(any(String.class), any(String.class), anyString())).thenReturn(amazonEC2);

    final String instanceType = "t";
    final String instanceId = "i-0";
    final Instance instance = new Instance()
            .withPublicIpAddress("p-ip")
            .withInstanceType(instanceType)
            .withInstanceId(instanceId);

    when(ec2Api.describeInstances(any(AmazonEC2.class), any(Set.class))).thenReturn(
            ImmutableMap.of(instanceId, instance));

    PowerMockito.when(FleetStateStats.readClusterState(any(AmazonEC2.class), anyString(), anyString()))
            .thenReturn(new FleetStateStats("fleetId", 0, "active",
                    ImmutableSet.of(instanceId),
                    ImmutableMap.of(instanceType, 2.0)));

    mockNodeCreatingPart();

    EC2FleetCloud fleetCloud = new EC2FleetCloud(null, null, "credId", null, "region",
            "", "fleetId", "", null, PowerMockito.mock(ComputerConnector.class), false,
            false, 0, 0, 1, 1, false,
            true, false,
            0, 0, true, 10, false);

    ArgumentCaptor<Node> nodeCaptor = ArgumentCaptor.forClass(Node.class);
    doNothing().when(jenkins).addNode(nodeCaptor.capture());

    // when
    fleetCloud.update();

    // then
    Node actualFleetNode = nodeCaptor.getValue();
    assertEquals(2, actualFleetNode.getNumExecutors());
}
 
Example #12
Source File: DockerCloudTest.java    From docker-plugin with MIT License 5 votes vote down vote up
@Test
public void globalConfigRoundtrip() throws Exception {

    // Create fake credentials, so they are selectable on configuration for during configuration roundtrip
    final CredentialsStore store = CredentialsProvider.lookupStores(jenkins.getInstance()).iterator().next();
    DockerServerCredentials dc = new DockerServerCredentials(SYSTEM, "credentialsId", "test", null, null, null);
    store.addCredentials(Domain.global(), dc);
    UsernamePasswordCredentials rc = new UsernamePasswordCredentialsImpl(SYSTEM, "pullCredentialsId", null, null, null);
    store.addCredentials(Domain.global(), rc);

    final DockerTemplateBase templateBase = new DockerTemplateBase("image", "pullCredentialsId", "dnsString", "network",
            "dockerCommand", "volumesString", "volumesFromString", "environmentString",
            "hostname", "user1", "", 128, 256, 42, 102, "bindPorts", true, true, true, "macAddress", "extraHostsString");
    templateBase.setCapabilitiesToAddString("SYS_ADMIN");
    templateBase.setCapabilitiesToDropString("CHOWN");
    templateBase.setSecurityOptsString("seccomp=unconfined");
    final DockerTemplate template = new DockerTemplate(
            templateBase,
            new DockerComputerAttachConnector("jenkins"),
            "labelString", "remoteFs", "10");
    template.setPullStrategy(DockerImagePullStrategy.PULL_NEVER);
    template.setMode(Node.Mode.NORMAL);
    template.setRemoveVolumes(true);
    template.setStopTimeout(42);
    template.setRetentionStrategy(new DockerOnceRetentionStrategy(33));

    DockerCloud cloud = new DockerCloud("docker", new DockerAPI(new DockerServerEndpoint("uri", "credentialsId")),
            Collections.singletonList(template));

    jenkins.getInstance().clouds.replaceBy(Collections.singleton(cloud));

    jenkins.configRoundtrip();

    Assert.assertEquals(cloud, jenkins.getInstance().clouds.get(0));
}
 
Example #13
Source File: EC2FleetCloud.java    From ec2-spot-jenkins-plugin with Apache License 2.0 5 votes vote down vote up
private void removeNode(final String instanceId) {
    final Jenkins jenkins = Jenkins.getInstance();
    // If this node is dying, remove it from Jenkins
    final Node n = jenkins.getNode(instanceId);
    if (n != null) {
        try {
            jenkins.removeNode(n);
        } catch (final Exception ex) {
            throw new IllegalStateException(String.format("Error removing node %s", instanceId), ex);
        }
    }
}
 
Example #14
Source File: WithMavenStepTest.java    From pipeline-maven-plugin with MIT License 5 votes vote down vote up
@Before
public void setup() throws Exception {
    super.setup();

    JavaGitContainer slaveContainer = slaveRule.get();

    DumbSlave agent = new DumbSlave("remote", "", "/home/test/slave", "1", Node.Mode.NORMAL, "",
            new SSHLauncher(slaveContainer.ipBound(22), slaveContainer.port(22), "test", "test", "", ""),
            RetentionStrategy.INSTANCE, Collections.<NodeProperty<?>>emptyList());
    jenkinsRule.jenkins.addNode(agent);
}
 
Example #15
Source File: ResetStuckBuildsInQueueActor.java    From docker-swarm-plugin with MIT License 5 votes vote down vote up
private void resetStuckBuildsInQueue() throws IOException {
    try {
        final Queue.Item[] items = Jenkins.getInstance().getQueue().getItems();
        for (int i = items.length - 1; i >= 0; i--) { // reverse order
            final Queue.Item item = items[i];
            final DockerSwarmLabelAssignmentAction lblAssignmentAction = item
                    .getAction(DockerSwarmLabelAssignmentAction.class); // This can be null here if computer was
                                                                        // never provisioned. Build will sit in
                                                                        // queue forever
            if (lblAssignmentAction != null) {
                long inQueueForMinutes = TimeUnit.MILLISECONDS
                        .toMinutes(new Date().getTime() - lblAssignmentAction.getProvisionedTime());
                if (inQueueForMinutes > RESET_MINUTES) {
                    final String computerName = lblAssignmentAction.getLabel().getName();
                    final Node provisionedNode = Jenkins.getInstance().getNode(computerName);
                    if (provisionedNode != null) {
                        LOGGER.info(String.format("Rescheduling %s and Deleting %s computer ", item, computerName));
                        BuildScheduler.scheduleBuild((Queue.BuildableItem) item);
                        ((DockerSwarmAgent) provisionedNode).terminate();
                    }
                }
            }
        }
    } finally {
        resechedule();
    }

}
 
Example #16
Source File: NodeChangeListener.java    From audit-log-plugin with MIT License 5 votes vote down vote up
/**
 * Fired when a node is deleted, event logged via Log4j-audit.
 *
 * @param node Node being deleted
 */
@Override
protected void onDeleted(@Nonnull Node node) {
    DeleteNode nodeDeleteEvent = LogEventFactory.getEvent(DeleteNode.class);

    nodeDeleteEvent.setNodeName(node.getNodeName());
    nodeDeleteEvent.setTimestamp(new Date().toString());

    nodeDeleteEvent.logEvent();
}
 
Example #17
Source File: NodeChangeListener.java    From audit-log-plugin with MIT License 5 votes vote down vote up
/**
 * Fired when a node is created, event logged via Log4j-audit.
 *
 * @param node Node being created
 */
@Override
protected void onCreated(@Nonnull Node node) {
    CreateNode nodeCreateEvent = LogEventFactory.getEvent(CreateNode.class);

    nodeCreateEvent.setNodeName(node.getNodeName());
    nodeCreateEvent.setTimestamp(new Date().toString());

    nodeCreateEvent.logEvent();
}
 
Example #18
Source File: NodeChangeListener.java    From audit-log-plugin with MIT License 5 votes vote down vote up
/**
 * Fired when a node is updated, event logged via Log4j-audit.
 *
 * @param oldOne The old node being modified
 * @param newOne The after after modification
 */
@Override
protected void onUpdated(@Nonnull Node oldOne, @Nonnull Node newOne) {
    UpdateNode nodeUpdateEvent = LogEventFactory.getEvent(UpdateNode.class);

    nodeUpdateEvent.setNodeName(newOne.getNodeName());
    nodeUpdateEvent.setOldNodeName(oldOne.getNodeName());
    nodeUpdateEvent.setTimestamp(new Date().toString());

    nodeUpdateEvent.logEvent();

}
 
Example #19
Source File: WorkspaceFileExporter.java    From DotCi with MIT License 5 votes vote down vote up
private FilePath getFilePath(final AbstractBuild<?, ?> build) {
    final FilePath ws = build.getWorkspace();
    if (ws == null) {
        final Node node = build.getBuiltOn();
        if (node == null) {
            throw new RuntimeException("no such build node: " + build.getBuiltOnStr());
        }
        throw new RuntimeException("no workspace from node " + node + " which is computer " + node.toComputer() + " and has channel " + node.getChannel());
    }
    return ws;
}
 
Example #20
Source File: DockerContainerWatchdogTest.java    From docker-plugin with MIT License 5 votes vote down vote up
@Test
public void testSimpleEnvironmentNothingTodo() throws IOException, InterruptedException {
    TestableDockerContainerWatchdog subject = new TestableDockerContainerWatchdog();

    final String nodeName = "unittest-12345";
    final String containerId = UUID.randomUUID().toString();

    /* setup of cloud */
    List<DockerCloud> listOfCloud = new LinkedList<>();

    Map<String, String> labelMap = new HashMap<>();
    labelMap.put(DockerContainerLabelKeys.NODE_NAME, nodeName);
    labelMap.put(DockerContainerLabelKeys.REMOVE_VOLUMES, "false");

    List<Container> containerList = new LinkedList<>();
    Container c = TestableDockerContainerWatchdog.createMockedContainer(containerId, "Running", 0L, labelMap);
    containerList.add(c);

    DockerAPI dockerApi = TestableDockerContainerWatchdog.createMockedDockerAPI(containerList);
    DockerCloud cloud = new DockerCloud("unittestcloud", dockerApi, new LinkedList<>());
    listOfCloud.add(cloud);

    subject.setAllClouds(listOfCloud);

    /* setup of nodes */
    LinkedList<Node> allNodes = new LinkedList<>();

    DockerTransientNode node = TestableDockerContainerWatchdog.createMockedDockerTransientNode(containerId, nodeName, cloud, false);
    allNodes.add(node);

    subject.setAllNodes(allNodes);

    subject.runExecute();

    Assert.assertEquals(0, subject.getAllRemovedNodes().size());
}
 
Example #21
Source File: JenkinsRule.java    From jenkins-test-harness with MIT License 5 votes vote down vote up
public void assertXPathValue(DomNode page, String xpath, String expectedValue) {
    Object node = page.getFirstByXPath(xpath);
    assertNotNull("no node found", node);
    assertTrue("the found object was not a Node " + xpath, node instanceof org.w3c.dom.Node);

    org.w3c.dom.Node n = (org.w3c.dom.Node) node;
    String textString = n.getTextContent();
    assertEquals("xpath value should match for " + xpath, expectedValue, textString);
}
 
Example #22
Source File: GitToolTest.java    From git-client-plugin with MIT License 5 votes vote down vote up
@Test
public void testForNode() throws Exception {
    DumbSlave agent = j.createSlave();
    agent.setMode(Node.Mode.EXCLUSIVE);
    TaskListener log = StreamTaskListener.fromStdout();
    GitTool newTool = gitTool.forNode(agent, log);
    assertEquals(gitTool.getGitExe(), newTool.getGitExe());
}
 
Example #23
Source File: DockerContainerWatchdog.java    From docker-plugin with MIT License 5 votes vote down vote up
private void cleanUpSuperfluousContainers(DockerClient client, Map<String, Node> nodeMap, ContainerNodeNameMap csm, DockerCloud dc, Instant snapshotInstant) {
    Collection<Container> allContainers = csm.getAllContainers();

    for (Container container : allContainers) {
        String nodeName = csm.getNodeName(container.getId());

        Node node = nodeMap.get(nodeName);
        if (node != null) {
            // the node and the container still have a proper mapping => ok
            continue;
        }

        /*
         * During startup it may happen temporarily that a container exists, but the
         * corresponding node isn't there yet.
         * That is why we have to have a grace period for pulling up containers.
         */
        if (isStillTooYoung(container.getCreated(), snapshotInstant)) {
            continue;
        }

        checkForTimeout(snapshotInstant);

        // this is a container, which is missing a corresponding node with us
        LOGGER.info("Container {}, which is reported to be assigned to node {}, "
                + "is no longer associated (node might be gone already?). "
                + "The container's last status is {}; it was created on {}", 
                container.getId(), nodeName, container.getStatus(), container.getCreated());

        try {
            terminateContainer(dc, client, container);
        } catch (Exception e) {
            // Graceful termination failed; we need to use some force
            LOGGER.warn("Graceful termination of Container {} failed; terminating directly via API - this may cause remnants to be left behind", container.getId(), e);
        }
    }
}
 
Example #24
Source File: IntegrationTest.java    From ec2-spot-jenkins-plugin with Apache License 2.0 5 votes vote down vote up
protected static void assertQueueAndNodesIdle(final Node node) {
    tryUntil(new Runnable() {
        @Override
        public void run() {
            Assert.assertTrue(Queue.getInstance().isEmpty() && node.toComputer().isIdle());
        }
    });
}
 
Example #25
Source File: DockerContainerWatchdogTest.java    From docker-plugin with MIT License 5 votes vote down vote up
@Test
public void testContainerExistsButSlaveIsMissingRemoveVolumesLabelMissing() throws IOException, InterruptedException {
    TestableDockerContainerWatchdog subject = new TestableDockerContainerWatchdog();

    final String nodeName = "unittest-12345";
    final String containerId = UUID.randomUUID().toString();

    /* setup of cloud */
    List<DockerCloud> listOfCloud = new LinkedList<>();

    Map<String, String> labelMap = new HashMap<>();
    labelMap.put(DockerContainerLabelKeys.NODE_NAME, nodeName);
    labelMap.put(DockerContainerLabelKeys.TEMPLATE_NAME, "unittesttemplate");
    // NB The removeVolumes label is not set here

    List<Container> containerList = new LinkedList<>();
    Container c = TestableDockerContainerWatchdog.createMockedContainer(containerId, "Running", 0L, labelMap);
    containerList.add(c);

    DockerAPI dockerApi = TestableDockerContainerWatchdog.createMockedDockerAPI(containerList);
    DockerCloud cloud = new DockerCloud("unittestcloud", dockerApi, new LinkedList<>());
    listOfCloud.add(cloud);

    subject.setAllClouds(listOfCloud);

    /* setup of nodes */
    LinkedList<Node> allNodes = new LinkedList<>();

    Node n = TestableDockerContainerWatchdog.createMockedDockerTransientNode(UUID.randomUUID().toString(), nodeName, cloud, false);
    allNodes.add(n);

    subject.setAllNodes(allNodes);

    subject.runExecute();

    List<String> containersRemoved = subject.getContainersRemoved();
    Assert.assertEquals(0, containersRemoved.size());

    Assert.assertEquals(0, subject.getAllRemovedNodes().size());
}
 
Example #26
Source File: AutoResubmitIntegrationTest.java    From ec2-spot-jenkins-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void should_successfully_resubmit_freestyle_task() throws Exception {
    EC2FleetCloud cloud = new EC2FleetCloud(null, null, "credId", null, "region",
            null, "fId", "momo", null, new LocalComputerConnector(j), false, false,
            0, 0, 10, 1, false, false,
            false, 0, 0, false,
            10, false);
    j.jenkins.clouds.add(cloud);

    List<QueueTaskFuture> rs = getQueueTaskFutures(1);

    System.out.println("check if zero nodes!");
    Assert.assertEquals(0, j.jenkins.getNodes().size());

    assertAtLeastOneNode();

    final Node node = j.jenkins.getNodes().get(0);
    assertQueueIsEmpty();

    System.out.println("disconnect node");
    node.toComputer().disconnect(new OfflineCause.ChannelTermination(new UnsupportedOperationException("Test")));

    // due to test nature job could be failed if started or aborted as we call disconnect
    // in prod code it's not matter
    assertLastBuildResult(Result.FAILURE, Result.ABORTED);

    node.toComputer().connect(true);
    assertNodeIsOnline(node);
    assertQueueAndNodesIdle(node);

    Assert.assertEquals(1, j.jenkins.getProjects().size());
    Assert.assertEquals(Result.SUCCESS, j.jenkins.getProjects().get(0).getLastBuild().getResult());
    Assert.assertEquals(2, j.jenkins.getProjects().get(0).getBuilds().size());

    cancelTasks(rs);
}
 
Example #27
Source File: DynamicSubBuild.java    From DotCi with MIT License 5 votes vote down vote up
protected Lease getParentWorkspaceLease(final Node n, final WorkspaceList wsl) throws InterruptedException, IOException {
    final DynamicProject mp = getParent().getParent();

    final String customWorkspace = mp.getCustomWorkspace();
    if (customWorkspace != null) {
        // we allow custom workspaces to be concurrently used between
        // jobs.
        return Lease.createDummyLease(n.getRootPath().child(getEnvironment(this.listener).expand(customWorkspace)));
    }
    return wsl.allocate(n.getWorkspaceFor(mp), getParentBuild());
}
 
Example #28
Source File: AutoResubmitIntegrationTest.java    From ec2-spot-jenkins-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void should_not_resubmit_if_disabled() throws Exception {
    EC2FleetCloud cloud = new EC2FleetCloud(null, null, "credId", null, "region",
            null, "fId", "momo", null, new LocalComputerConnector(j), false, false,
            0, 0, 10, 1, false, false,
            true, 0, 0, false, 10, false);
    j.jenkins.clouds.add(cloud);

    List<QueueTaskFuture> rs = getQueueTaskFutures(1);

    System.out.println("check if zero nodes!");
    Assert.assertEquals(0, j.jenkins.getNodes().size());

    assertAtLeastOneNode();

    final Node node = j.jenkins.getNodes().get(0);
    assertQueueIsEmpty();

    System.out.println("disconnect node");
    node.toComputer().disconnect(new OfflineCause.ChannelTermination(new UnsupportedOperationException("Test")));

    assertLastBuildResult(Result.FAILURE, Result.ABORTED);

    node.toComputer().connect(true);
    assertNodeIsOnline(node);
    assertQueueAndNodesIdle(node);

    Assert.assertEquals(1, j.jenkins.getProjects().size());
    Assert.assertEquals(Result.FAILURE, j.jenkins.getProjects().get(0).getLastBuild().getResult());
    Assert.assertEquals(1, j.jenkins.getProjects().get(0).getBuilds().size());

    cancelTasks(rs);
}
 
Example #29
Source File: DockerTemplate.java    From docker-plugin with MIT License 5 votes vote down vote up
/**
 * Xstream ignores default field values, so set them explicitly
 */
private void configDefaults() {
    if (mode == null) {
        mode = Node.Mode.NORMAL;
    }
    if (retentionStrategy == null) {
        retentionStrategy = new DockerOnceRetentionStrategy(10);
    }
}
 
Example #30
Source File: DockerJobProperty.java    From docker-plugin with MIT License 5 votes vote down vote up
@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
    final Node node = build.getBuiltOn();
    if (!(node instanceof DockerTransientNode)) {
        return true;
    }
    DockerTransientNode dockerNode = (DockerTransientNode) node;
    final String containerId = dockerNode.getContainerId();
    final DockerAPI dockerAPI = dockerNode.getDockerAPI();
    try(final DockerClient client = dockerAPI.getClient()) {
        return perform(build, listener, containerId, dockerAPI, client);
    }
}