Java Code Examples for hudson.model.Node
The following examples show how to use
hudson.model.Node.
These examples are extracted from open source projects.
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 Project: warnings-ng-plugin Author: jenkinsci File: DockerContainerITest.java License: MIT License | 6 votes |
/** * 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 #2
Source Project: warnings-ng-plugin Author: jenkinsci File: DockerContainerITest.java License: MIT License | 6 votes |
/** * 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 #3
Source Project: docker-plugin Author: jenkinsci File: DockerContainerWatchdog.java License: MIT License | 6 votes |
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 #4
Source Project: kubernetes-plugin Author: jenkinsci File: ContainerExecDecoratorTest.java License: Apache License 2.0 | 6 votes |
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 Project: kubernetes-plugin Author: jenkinsci File: ContainerExecDecoratorTest.java License: Apache License 2.0 | 6 votes |
@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 #6
Source Project: ec2-spot-jenkins-plugin Author: awslabs File: UiIntegrationTest.java License: Apache License 2.0 | 6 votes |
@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 #7
Source Project: ec2-spot-jenkins-plugin Author: awslabs File: EC2FleetCloudAwareUtilsTest.java License: Apache License 2.0 | 6 votes |
@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 #8
Source Project: pipeline-maven-plugin Author: jenkinsci File: WithMavenStepExecution2.java License: MIT License | 6 votes |
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 #9
Source Project: jenkins-parallels Author: Parallels File: ParallelsDesktopConnectorSlaveComputer.java License: MIT License | 6 votes |
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 #10
Source Project: docker-plugin Author: jenkinsci File: DockerCloud.java License: MIT License | 6 votes |
/** * 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 #11
Source Project: atlassian-jira-software-cloud-plugin Author: jenkinsci File: JiraSendDeploymentInfoStepTest.java License: Apache License 2.0 | 5 votes |
@Test public void testStep() throws Exception { // given final WorkflowRun mockWorkflowRun = mockWorkflowRun(); final TaskListener mockTaskListener = mockTaskListener(); when(mockTaskListener.getLogger()).thenReturn(mock(PrintStream.class)); final Map<String, Object> r = new HashMap<>(); r.put("site", SITE); r.put("environment", ENVIRONMENT_NAME); r.put("environmentType", ENVIRONMENT_TYPE); final JiraSendDeploymentInfoStep step = (JiraSendDeploymentInfoStep) descriptor.newInstance(r); final StepContext ctx = mock(StepContext.class); when(ctx.get(Node.class)).thenReturn(jenkinsRule.getInstance()); when(ctx.get(WorkflowRun.class)).thenReturn(mockWorkflowRun); when(ctx.get(TaskListener.class)).thenReturn(mockTaskListener); final JiraSendDeploymentInfoStep.JiraSendDeploymentInfoStepExecution start = (JiraSendDeploymentInfoStep.JiraSendDeploymentInfoStepExecution) step.start(ctx); // when final JiraSendInfoResponse response = start.run(); // then assertThat(response.getStatus()).isEqualTo(SUCCESS_DEPLOYMENT_ACCEPTED); }
Example #12
Source Project: appcenter-plugin Author: jenkinsci File: NodeTest.java License: MIT License | 5 votes |
@Before public void setUp() throws Exception { freeStyleProject = jenkinsRule.createFreeStyleProject(); freeStyleProject.getBuildersList().add(TestUtil.createFile("three/days/xiola.apk")); final AppCenterRecorder appCenterRecorder = new AppCenterRecorder("at-this-moment-you-should-be-with-us", "janes-addiction", "ritual-de-lo-habitual", "three/days/xiola.apk", "casey, niccoli"); appCenterRecorder.setBaseUrl(mockWebServer.url("/").toString()); freeStyleProject.getPublishersList().add(appCenterRecorder); slave = new MockSlave("test-slave", 1, Node.Mode.NORMAL, "", RetentionStrategy.Always.INSTANCE, Collections.emptyList()); jenkinsRule.jenkins.addNode(slave); freeStyleProject.setAssignedNode(slave); }
Example #13
Source Project: kubernetes-plugin Author: jenkinsci File: ContainerExecDecoratorTest.java License: Apache License 2.0 | 5 votes |
@Before public void configureCloud() throws Exception { cloud = setupCloud(this, name); client = cloud.connect(); deletePods(client, getLabels(this, name), false); String image = "busybox"; Container c = new ContainerBuilder().withName(image).withImagePullPolicy("IfNotPresent").withImage(image) .withCommand("cat").withTty(true).build(); Container d = new ContainerBuilder().withName(image + "1").withImagePullPolicy("IfNotPresent").withImage(image) .withCommand("cat").withTty(true).withWorkingDir("/home/jenkins/agent1").build(); String podName = "test-command-execution-" + RandomStringUtils.random(5, "bcdfghjklmnpqrstvwxz0123456789"); pod = client.pods().create(new PodBuilder().withNewMetadata().withName(podName) .withLabels(getLabels(this, name)).endMetadata().withNewSpec().withContainers(c, d).withNodeSelector(Collections.singletonMap("kubernetes.io/os", "linux")).withTerminationGracePeriodSeconds(0L).endSpec().build()); System.out.println("Created pod: " + pod.getMetadata().getName()); PodTemplate template = new PodTemplate(); template.setName(pod.getMetadata().getName()); agent = mock(KubernetesSlave.class); when(agent.getNamespace()).thenReturn(client.getNamespace()); when(agent.getPodName()).thenReturn(pod.getMetadata().getName()); doReturn(cloud).when(agent).getKubernetesCloud(); when(agent.getPod()).thenReturn(Optional.of(pod)); StepContext context = mock(StepContext.class); when(context.get(Node.class)).thenReturn(agent); decorator = new ContainerExecDecorator(); decorator.setNodeContext(new KubernetesNodeContext(context)); decorator.setContainerName(image); }
Example #14
Source Project: docker-swarm-plugin Author: jenkinsci File: ResetStuckBuildsInQueueActor.java License: MIT License | 5 votes |
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 #15
Source Project: audit-log-plugin Author: jenkinsci File: NodeChangeListener.java License: MIT License | 5 votes |
/** * 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 #16
Source Project: audit-log-plugin Author: jenkinsci File: NodeChangeListener.java License: MIT License | 5 votes |
/** * 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 #17
Source Project: audit-log-plugin Author: jenkinsci File: NodeChangeListener.java License: MIT License | 5 votes |
/** * 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 #18
Source Project: docker-plugin Author: jenkinsci File: DockerContainerWatchdogTest.java License: MIT License | 5 votes |
@Test public void testContainerExistsButSlaveIsMissing() 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"); 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<>(); subject.setAllNodes(allNodes); subject.runExecute(); Assert.assertEquals(0, subject.getAllRemovedNodes().size()); List<String> containersRemoved = subject.getContainersRemoved(); Assert.assertEquals(1, containersRemoved.size()); Assert.assertEquals(containerId, containersRemoved.get(0)); }
Example #19
Source Project: docker-plugin Author: jenkinsci File: DockerBuilderPublisher.java License: MIT License | 5 votes |
protected DockerAPI getDockerAPI(Launcher launcher) { DockerCloud theCloud; final VirtualChannel channel = launcher.getChannel(); if (!Strings.isNullOrEmpty(cloud)) { theCloud = JenkinsUtils.getServer(cloud); } else { if(channel instanceof Channel) { final Node node = Jenkins.getInstance().getNode(((Channel)channel).getName() ); if (node instanceof DockerTransientNode) { return ((DockerTransientNode) node).getDockerAPI(); } } final Optional<DockerCloud> cloudForChannel = JenkinsUtils.getCloudForChannel(channel); if (!cloudForChannel.isPresent()) throw new RuntimeException("Could not find the cloud this project was built on"); theCloud = cloudForChannel.get(); } // Triton can't do docker build. Ensure we're not trying to do that. if (theCloud.isTriton()) { LOGGER.warn("Selected cloud for build does not support this feature. Finding an alternative"); for (DockerCloud dc : JenkinsUtils.getServers()) { if (!dc.isTriton()) { LOGGER.warn("Picked {} cloud instead", dc.getDisplayName()); theCloud = dc; break; } } } return theCloud.getDockerApi(); }
Example #20
Source Project: configuration-as-code-plugin Author: jenkinsci File: JenkinsConfiguratorCloudSupportTest.java License: MIT License | 5 votes |
@Test public void should_remove_normal_nodes_configured_after_reload() throws Exception { final Node slave = new StaticPretendSlave(); j.jenkins.addNode(slave); ConfigurationAsCode.get().configure(this.getClass().getResource("JenkinsConfiguratorCloudSupportTest.yml").toString()); assertEquals("Base nodes not found", 2, j.jenkins.getNodes().size()); }
Example #21
Source Project: configuration-as-code-plugin Author: jenkinsci File: JenkinsConfiguratorCloudSupportTest.java License: MIT License | 5 votes |
@Test public void should_keep_cloud_no_instantiable_nodes_configured_after_reload() throws Exception { final Node slave = new Cloud1PretendSlave(); j.jenkins.addNode(slave); ConfigurationAsCode.get().configure(this.getClass().getResource("JenkinsConfiguratorCloudSupportTest.yml").toString()); assertEquals("Cloud nodes not found", 3, j.jenkins.getNodes().size()); assertNotNull("Slave 1", j.jenkins.getNode("agent1")); assertNotNull("Slave 1", j.jenkins.getNode("agent2")); assertNotNull("Slave cloud", j.jenkins.getNode("testCloud")); }
Example #22
Source Project: DotCi Author: groupon File: WorkspaceFileExporter.java License: MIT License | 5 votes |
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 #23
Source Project: ec2-spot-jenkins-plugin Author: awslabs File: EC2FleetCloud.java License: Apache License 2.0 | 5 votes |
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 #24
Source Project: docker-plugin Author: jenkinsci File: DockerCloudTest.java License: MIT License | 5 votes |
@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 #25
Source Project: git-client-plugin Author: jenkinsci File: GitToolTest.java License: MIT License | 5 votes |
@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 #26
Source Project: docker-plugin Author: jenkinsci File: DockerContainerWatchdog.java License: MIT License | 5 votes |
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 #27
Source Project: ec2-spot-jenkins-plugin Author: awslabs File: IntegrationTest.java License: Apache License 2.0 | 5 votes |
protected static void assertQueueAndNodesIdle(final Node node) { tryUntil(new Runnable() { @Override public void run() { Assert.assertTrue(Queue.getInstance().isEmpty() && node.toComputer().isIdle()); } }); }
Example #28
Source Project: ec2-spot-jenkins-plugin Author: awslabs File: AutoResubmitIntegrationTest.java License: Apache License 2.0 | 5 votes |
@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 #29
Source Project: ec2-spot-jenkins-plugin Author: awslabs File: AutoResubmitIntegrationTest.java License: Apache License 2.0 | 5 votes |
@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 #30
Source Project: docker-plugin Author: jenkinsci File: DockerTemplate.java License: MIT License | 5 votes |
/** * 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); } }