hudson.slaves.DumbSlave Java Examples

The following examples show how to use hudson.slaves.DumbSlave. 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: 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 #2
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 #3
Source File: AbsolutePathGeneratorITest.java    From warnings-ng-plugin with MIT License 6 votes vote down vote up
@SuppressWarnings("checkstyle:IllegalCatch")
private Slave createAgentWithWrongWorkspaceFolder() {
    try {
        JenkinsRule jenkinsRule = getJenkins();
        int size = jenkinsRule.jenkins.getNodes().size();

        DumbSlave slave = new DumbSlave("slave" + size,
                agentWorkspace.getRoot().getPath().toLowerCase(Locale.ENGLISH),
                jenkinsRule.createComputerLauncher(null));
        slave.setLabelString("agent");
        jenkinsRule.jenkins.addNode(slave);
        jenkinsRule.waitOnline(slave);

        return slave;
    }
    catch (Exception e) {
        throw new AssertionError(e);
    }
}
 
Example #4
Source File: IntegrationTest.java    From warnings-ng-plugin with MIT License 6 votes vote down vote up
@SuppressWarnings({"PMD.AvoidCatchingThrowable", "IllegalCatch"})
protected DumbSlave createDockerContainerAgent(final DockerContainer dockerContainer) {
    try {
        SystemCredentialsProvider.getInstance().getDomainCredentialsMap().put(Domain.global(),
                Collections.singletonList(
                        new UsernamePasswordCredentialsImpl(CredentialsScope.SYSTEM, "dummyCredentialId",
                                null, "test", "test")
                )
        );
        DumbSlave agent = new DumbSlave("docker", "/home/test",
                new SSHLauncher(dockerContainer.ipBound(22), dockerContainer.port(22), "dummyCredentialId"));
        agent.setNodeProperties(Collections.singletonList(new EnvironmentVariablesNodeProperty(
                new Entry("JAVA_HOME", "/usr/lib/jvm/java-8-openjdk-amd64/jre"))));
        getJenkins().jenkins.addNode(agent);
        getJenkins().waitOnline(agent);

        return agent;
    }
    catch (Throwable e) {
        throw new AssumptionViolatedException("Failed to create docker container", e);
    }
}
 
Example #5
Source File: JUnitResultArchiverTest.java    From junit-plugin with MIT License 6 votes vote down vote up
private void doRepeatedArchiving(boolean slave) throws Exception {
    if (slave) {
        DumbSlave s = j.createOnlineSlave();
        project.setAssignedLabel(s.getSelfLabel());
    }
    project.getPublishersList().removeAll(JUnitResultArchiver.class);
    project.getBuildersList().add(new SimpleArchive("A", 7, 0));
    project.getBuildersList().add(new SimpleArchive("B", 0, 1));
    FreeStyleBuild build = j.assertBuildStatus(Result.UNSTABLE, project.scheduleBuild2(0).get());
    List<TestResultAction> actions = build.getActions(TestResultAction.class);
    assertEquals(1, actions.size());
    TestResultAction testResultAction = actions.get(0);
    TestResult result = testResultAction.getResult();
    assertNotNull("no TestResult", result);
    assertEquals("should have 1 failing test", 1, testResultAction.getFailCount());
    assertEquals("should have 1 failing test", 1, result.getFailCount());
    assertEquals("should have 8 total tests", 8, testResultAction.getTotalCount());
    assertEquals("should have 8 total tests", 8, result.getTotalCount());
    assertEquals(/* ⅞ = 87.5% */87, testResultAction.getBuildHealth().getScore());
}
 
Example #6
Source File: CucumberLivingDocumentationIT.java    From cucumber-living-documentation-plugin with MIT License 6 votes vote down vote up
@Test
public void shouldGenerateLivingDocumentatationOnSlaveNode() throws Exception{
	DumbSlave slave = jenkins.createOnlineSlave();
	FreeStyleProject project = jenkins.createFreeStyleProject("test");
	project.setAssignedNode(slave);
	
	SingleFileSCM scm = new SingleFileSCM("asciidoctor.json",
			CucumberLivingDocumentationIT.class.getResource("/json-output/asciidoctor/asciidoctor.json").toURI().toURL());
	
	project.setScm(scm);
	CukedoctorPublisher publisher = new CukedoctorPublisher(null, FormatType.HTML, TocType.RIGHT, true, true, "Living Documentation",false,false,false,false,false);
	project.getPublishersList().add(publisher);
	project.save();

	FreeStyleBuild build = jenkins.buildAndAssertSuccess(project);
	jenkins.assertLogContains("Format: html" + NEW_LINE + "Toc: right"+NEW_LINE +
			"Title: Living Documentation"+NEW_LINE+"Numbered: true"+NEW_LINE +
			"Section anchors: true", build);
	jenkins.assertLogContains("Found 4 feature(s)...",build);
	jenkins.assertLogContains("Documentation generated successfully!",build);
	Assert.assertTrue("It should run on slave",build.getBuiltOn().equals(slave));
	
}
 
Example #7
Source File: DockerToolInstallerTest.java    From docker-commons-plugin with MIT License 6 votes vote down vote up
private FilePath downloadDocker(DumbSlave slave, FilePath toolDir, String version) throws IOException, InterruptedException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    TeeOutputStream tee = new TeeOutputStream(baos, new PlainTextConsoleOutputStream(System.err));
    TaskListener l = new StreamTaskListener(tee);

    FilePath exe = toolDir.child(version+"/bin/docker");
    // Download for first time:
    assertEquals(exe.getRemote(), DockerTool.getExecutable(version, slave, l, null));
    assertTrue(exe.exists());
    assertThat(baos.toString(), containsString(Messages.DockerToolInstaller_downloading_docker_client_(version)));
    // Next time we do not need to download:
    baos.reset();
    assertEquals(exe.getRemote(), DockerTool.getExecutable(version, slave, l, null));
    assertTrue(exe.exists());
    assertThat(baos.toString(), not(containsString(Messages.DockerToolInstaller_downloading_docker_client_(version))));
    // Version check:
    baos.reset();
    assertEquals(0, slave.createLauncher(l).launch().cmds(exe.getRemote(), "version", "--format", "{{.Client.Version}}").quiet(true).stdout(tee).stderr(System.err).join());
    if (!version.equals("latest")) {
        assertEquals(version, baos.toString().trim());
    }
    return exe;
}
 
Example #8
Source File: HudsonTestCase.java    From jenkins-test-harness with MIT License 6 votes vote down vote up
/**
 * Create a new slave on the local host and wait for it to come online
 * before returning
 */
@SuppressWarnings("deprecation")
public DumbSlave createOnlineSlave(Label l, EnvVars env) throws Exception {
    final CountDownLatch latch = new CountDownLatch(1);
    ComputerListener waiter = new ComputerListener() {
                                        @Override
                                        public void onOnline(Computer C, TaskListener t) {
                                            latch.countDown();
                                            unregister();
                                        }
                                    };
    waiter.register();

    DumbSlave s = createSlave(l, env);
    latch.await();

    return s;
}
 
Example #9
Source File: JenkinsRule.java    From jenkins-test-harness with MIT License 5 votes vote down vote up
public DumbSlave createSlave(String nodeName, String labels, EnvVars env) throws Exception {
    synchronized (jenkins) {
        DumbSlave slave = new DumbSlave(nodeName, "dummy",
				createTmpDir().getPath(), "1", Node.Mode.NORMAL, labels==null?"":labels, createComputerLauncher(env), RetentionStrategy.NOOP, Collections.EMPTY_LIST);                        
		jenkins.addNode(slave);
		return slave;
	}
}
 
Example #10
Source File: RemotingTest.java    From git-client-plugin with MIT License 5 votes vote down vote up
/**
 * Makes sure {@link GitClient} is remotable.
 */
@Test
public void testRemotability() throws Exception {
    DumbSlave agent = j.createSlave();

    GitClient jgit = new JGitAPIImpl(tempFolder.getRoot(), StreamBuildListener.fromStdout());

    Computer c = agent.toComputer();
    c.connect(false).get();
    VirtualChannel channel = c.getChannel();
    channel.call(new Work(jgit));
    channel.close();
}
 
Example #11
Source File: JenkinsRule.java    From jenkins-test-harness with MIT License 5 votes vote down vote up
/**
 * Create a new slave on the local host and wait for it to come online
 * before returning
 * @see #waitOnline
 */
@SuppressWarnings({"deprecation"})
public DumbSlave createOnlineSlave(Label l, EnvVars env) throws Exception {
    DumbSlave s = createSlave(l, env);
    waitOnline(s);
    return s;
}
 
Example #12
Source File: HudsonTestCase.java    From jenkins-test-harness with MIT License 5 votes vote down vote up
/**
 * Creates a slave with certain additional environment variables
 */
public DumbSlave createSlave(String labels, EnvVars env) throws Exception {
    synchronized (jenkins) {
        int sz = jenkins.getNodes().size();
        return createSlave("slave" + sz,labels,env);
	}
}
 
Example #13
Source File: HudsonTestCase.java    From jenkins-test-harness with MIT License 5 votes vote down vote up
public DumbSlave createSlave(String nodeName, String labels, EnvVars env) throws Exception {
    synchronized (jenkins) {
        DumbSlave slave = new DumbSlave(nodeName, "dummy",
				createTmpDir().getPath(), "1", Mode.NORMAL, labels==null?"":labels, createComputerLauncher(env),
       RetentionStrategy.NOOP, Collections.emptyList());
		jenkins.addNode(slave);
		return slave;
	}
}
 
Example #14
Source File: DockerToolTest.java    From docker-commons-plugin with MIT License 5 votes vote down vote up
@Test public void getExecutable() throws Exception {
    assertEquals(DockerTool.COMMAND, DockerTool.getExecutable(null, null, null, null));
    DockerTool.DescriptorImpl descriptor = r.jenkins.getDescriptorByType(DockerTool.DescriptorImpl.class);
    String name = "docker15";
    descriptor.setInstallations(new DockerTool(name, "/usr/local/docker15", Collections.<ToolProperty<?>>emptyList()));
    // TODO r.jenkins.restart() does not reproduce need for get/setInstallations; use RestartableJenkinsRule in 1.567+
    assertEquals("/usr/local/docker15/bin/docker", DockerTool.getExecutable(name, null, null, null));
    DumbSlave slave = r.createOnlineSlave();
    slave.getNodeProperties().add(new ToolLocationNodeProperty(new ToolLocationNodeProperty.ToolLocation(descriptor, name, "/opt/docker")));
    assertEquals("/usr/local/docker15/bin/docker", DockerTool.getExecutable(name, null, null, null));
    assertEquals("/opt/docker/bin/docker", DockerTool.getExecutable(name, slave, StreamTaskListener.fromStderr(), null));
}
 
Example #15
Source File: DockerServerEndpointTest.java    From docker-commons-plugin with MIT License 5 votes vote down vote up
@Test
public void smokes() throws Exception {
    DumbSlave slave = j.createOnlineSlave();
    VirtualChannel channel = slave.getChannel();
    FreeStyleProject item = j.createFreeStyleProject();
    CredentialsStore store = CredentialsProvider.lookupStores(j.getInstance()).iterator().next();
    assertThat(store, instanceOf(SystemCredentialsProvider.StoreImpl.class));
    Domain domain = new Domain("docker", "A domain for docker credentials",
            Collections.<DomainSpecification>singletonList(new DockerServerDomainSpecification()));
    DockerServerCredentials credentials = new DockerServerCredentials(CredentialsScope.GLOBAL, "foo", "desc", Secret.fromString("a"), "b", "c");
    store.addDomain(domain, credentials);
    DockerServerEndpoint endpoint = new DockerServerEndpoint("tcp://localhost:2736", credentials.getId());
    FilePath dotDocker = DockerServerEndpoint.dotDocker(channel);
    List<FilePath> dotDockerKids = dotDocker.list();
    int initialSize = dotDockerKids == null ? 0 : dotDockerKids.size();
    KeyMaterialFactory factory = endpoint.newKeyMaterialFactory(item, channel);
    KeyMaterial keyMaterial = factory.materialize();
    FilePath path = null;
    try {
        assertThat(keyMaterial.env().get("DOCKER_HOST", "missing"), is("tcp://localhost:2736"));
        assertThat(keyMaterial.env().get("DOCKER_TLS_VERIFY", "missing"), is("1"));
        assertThat(keyMaterial.env().get("DOCKER_CERT_PATH", "missing"), not("missing"));
        path = new FilePath(channel, keyMaterial.env().get("DOCKER_CERT_PATH", "missing"));
        if (!Functions.isWindows()) {
            assertThat(path.mode() & 0777, is(0700));
        }
        assertThat(path.child("key.pem").readToString(), is("a"));
        assertThat(path.child("cert.pem").readToString(), is("b"));
        assertThat(path.child("ca.pem").readToString(), is("c"));
    } finally {
        keyMaterial.close();
    }
    assertThat(path.child("key.pem").exists(), is(false));
    assertThat(path.child("cert.pem").exists(), is(false));
    assertThat(path.child("ca.pem").exists(), is(false));
    assertThat(dotDocker.list().size(), is(initialSize));
}
 
Example #16
Source File: JUnitResultArchiverTest.java    From junit-plugin with MIT License 5 votes vote down vote up
@RandomlyFails("TimeoutException from basic")
@LocalData("All")
@Test public void slave() throws Exception {
     DumbSlave s = j.createOnlineSlave();
     project.setAssignedLabel(s.getSelfLabel());

     FilePath src = new FilePath(j.jenkins.getRootPath(), "jobs/junit/workspace/");
     assertNotNull(src);
     FilePath dest = s.getWorkspaceFor(project);
     assertNotNull(dest);
     src.copyRecursiveTo("*.xml", dest);

     basic();
 }
 
Example #17
Source File: TestResultPublishingTest.java    From junit-plugin with MIT License 5 votes vote down vote up
@LocalData
@Test
public void testSlave() throws Exception {
    DumbSlave s = rule.createOnlineSlave();
    project.setAssignedLabel(s.getSelfLabel());

    FilePath src = new FilePath(rule.jenkins.getRootPath(), "jobs/" + BASIC_TEST_PROJECT + "/workspace/");
    assertNotNull(src);
    FilePath dest = s.getWorkspaceFor(project);
    assertNotNull(dest);
    src.copyRecursiveTo("*.xml", dest);

    testBasic();
}
 
Example #18
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 #19
Source File: NodeChangeListenerTest.java    From audit-log-plugin with MIT License 5 votes vote down vote up
@Issue("JENKINS-56646")
@Test
public void testOnCreated() throws Exception {
    DumbSlave slave = j.createSlave("TestSlave", "", null);

    List<LogEvent> events = app.getEvents();

    assertThat(events).hasSize(1);
    assertThat(events).extracting(event -> ((AuditMessage) event.getMessage()).getId().toString()).contains("createNode");
}
 
Example #20
Source File: NodeChangeListenerTest.java    From audit-log-plugin with MIT License 5 votes vote down vote up
@Issue("JENKINS-56648")
@Test
public void testOnDeleted() throws Exception {
    DumbSlave slave = j.createOnlineSlave();
    j.jenkins.removeNode(slave);

    List<LogEvent> events = app.getEvents();

    assertThat(events).hasSize(2);
    assertThat(events).extracting(event -> ((AuditMessage) event.getMessage()).getId().toString()).contains("createNode", "deleteNode");

}
 
Example #21
Source File: KafkaComputerLauncherTest.java    From remoting-kafka-plugin with MIT License 5 votes vote down vote up
@Test
public void configureRoundTrip() throws Exception {
    GlobalKafkaConfiguration g = GlobalKafkaConfiguration.get();
    String kafkaURL = kafka.getBootstrapServers().split("//")[1];
    String zookeeperURL = kafka.getContainerIpAddress() + ":" + kafka.getMappedPort(2181);
    g.setBrokerURL(kafkaURL);
    g.setZookeeperURL(zookeeperURL);
    g.setEnableSSL(false);
    g.save();
    g.load();
    KafkaComputerLauncher launcher = new KafkaComputerLauncher("", "",
            "", "false");
    DumbSlave agent = new DumbSlave("test", "/tmp/", launcher);
    j.jenkins.addNode(agent);
    Computer c = j.jenkins.getComputer("test");
    assertNotNull(c);
    Thread.sleep(10000); // wait to connect master to kafka.
    String[] urls = j.getInstance().getRootUrl().split("/");
    String jenkinsURL = urls[0] + "//" + urls[1] + urls[2] + "/";
    String[] args = new String[]{"-name", "test", "-master", jenkinsURL, "-secret",
            KafkaSecretManager.getConnectionSecret("test"), "-kafkaURL", kafkaURL, "-noauth"};
    AgentRunnable runnable = new AgentRunnable(args);
    Thread t = new Thread(runnable);
    try {
        t.start();
        Thread.sleep(10000); // wait to connect agent to jenkins master.
        FreeStyleProject p = j.createFreeStyleProject();
        p.setAssignedNode(agent);
        j.buildAndAssertSuccess(p);
    } finally {
        t.interrupt();
    }
}
 
Example #22
Source File: NodesByLabelStepTest.java    From pipeline-utility-steps-plugin with MIT License 5 votes vote down vote up
@Before
public void setup() throws Exception {
    job = r.jenkins.createProject(WorkflowJob.class, "workflow");
    r.createSlave("dummy1", "a", new EnvVars());
    r.createSlave("dummy2", "a b", new EnvVars());
    r.createSlave("dummy3", "a b c", new EnvVars());
    DumbSlave slave = r.createSlave("dummy4", "a b c d", new EnvVars());
    slave.toComputer().waitUntilOnline();
    CLICommandInvoker command = new CLICommandInvoker(r, "disconnect-node");
    CLICommandInvoker.Result result = command
            .authorizedTo(Computer.DISCONNECT, Jenkins.READ)
            .invokeWithArgs("dummy4");
    assertThat(result, succeededSilently());
    assertThat(slave.toComputer().isOffline(), equalTo(true));
}
 
Example #23
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 #24
Source File: JenkinsRule.java    From jenkins-test-harness with MIT License 5 votes vote down vote up
public DumbSlave createSlave(boolean waitForChannelConnect) throws Exception {
    DumbSlave slave = createSlave();
    if (waitForChannelConnect) {
        long start = System.currentTimeMillis();
        while (slave.getChannel() == null) {
            if (System.currentTimeMillis() > (start + 10000)) {
                throw new IllegalStateException("Timed out waiting on DumbSlave channel to connect.");
            }
            Thread.sleep(200);
        }
    }
    return slave;
}
 
Example #25
Source File: JenkinsRule.java    From jenkins-test-harness with MIT License 5 votes vote down vote up
public void disconnectSlave(DumbSlave slave) throws Exception {
    slave.getComputer().disconnect(new OfflineCause.ChannelTermination(new Exception("terminate")));
    long start = System.currentTimeMillis();
    while (slave.getChannel() != null) {
        if (System.currentTimeMillis() > (start + 10000)) {
            throw new IllegalStateException("Timed out waiting on DumbSlave channel to disconnect.");
        }
        Thread.sleep(200);
    }
}
 
Example #26
Source File: JenkinsRule.java    From jenkins-test-harness with MIT License 5 votes vote down vote up
/**
 * Creates a slave with certain additional environment variables
 */
public DumbSlave createSlave(String labels, EnvVars env) throws Exception {
    synchronized (jenkins) {
        int sz = jenkins.getNodes().size();
        return createSlave("slave" + sz,labels,env);
	}
}
 
Example #27
Source File: JenkinsRule.java    From jenkins-test-harness with MIT License 4 votes vote down vote up
public DumbSlave createSlave() throws Exception {
    return createSlave("",null);
}
 
Example #28
Source File: ConfigurationAsCodeTest.java    From folder-auth-plugin with MIT License 4 votes vote down vote up
@Before
public void setUp() throws Exception {
    j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
    j.jenkins.addNode(new DumbSlave("agent1", "", new JNLPLauncher(true)));
    folder = j.jenkins.createProject(Folder.class, "root");
}
 
Example #29
Source File: DockerBuildImageStepTest.java    From yet-another-docker-plugin with MIT License 4 votes vote down vote up
@Test
    public void testBuild() throws Throwable {
        jRule.getInstance().setNumExecutors(0);
//        jRule.createSlave();
//        jRule.createSlave("my-slave", "remote-slave", new EnvVars());
        final UsernamePasswordCredentialsImpl credentials = new UsernamePasswordCredentialsImpl(CredentialsScope.SYSTEM,
                null, "description", "vagrant", "vagrant");

        CredentialsStore store = CredentialsProvider.lookupStores(jRule.getInstance()).iterator().next();
        store.addCredentials(Domain.global(), credentials);

        final SSHLauncher sshLauncher = new SSHLauncher("192.168.33.10", 22, credentials.getId(),
                "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005", //jvmopts
                "", //      String javaPath,
                "",  //      String prefixStartSlaveCmd,
                "", //      String suffixStartSlaveCmd,
                20, //      Integer launchTimeoutSeconds,
                1, //      Integer maxNumRetries,
                3,//      Integer retryWaitTime
                new NonVerifyingKeyVerificationStrategy()
        );
        final DumbSlave dumbSlave = new DumbSlave("docker-daemon", "/home/vagrant/jenkins2", sshLauncher);
        jRule.getInstance().addNode(dumbSlave);
        await().timeout(60, SECONDS).until(() -> assertThat(dumbSlave.getChannel(), notNullValue()));
        String dockerfilePath = dumbSlave.getChannel().call(new StringThrowableCallable());


        final CredentialsYADockerConnector dockerConnector = new CredentialsYADockerConnector()
                .withConnectorType(JERSEY)
                .withServerUrl("tcp://127.0.0.1:2376")
                .withSslConfig(new LocalDirectorySSLConfig("/home/vagrant/keys"))
                ;
//                .withCredentials(new DockerDaemonFileCredentials(null, "docker-cert", "",
//                        "/home/vagrant/keys"));

        DockerBuildImage buildImage = new DockerBuildImage();
        buildImage.setBaseDirectory(dockerfilePath);
        buildImage.setPull(true);
        buildImage.setNoCache(true);

        DockerBuildImageStep dockerBuildImageStep = new DockerBuildImageStep(dockerConnector, buildImage);

        FreeStyleProject project = jRule.createFreeStyleProject("test");
        project.getBuildersList().add(dockerBuildImageStep);

        project.save();

        QueueTaskFuture<FreeStyleBuild> taskFuture = project.scheduleBuild2(0);
        FreeStyleBuild freeStyleBuild = taskFuture.get();
        jRule.waitForCompletion(freeStyleBuild);
        jRule.assertBuildStatusSuccess(freeStyleBuild);
    }
 
Example #30
Source File: DockerImageComboStepTest.java    From yet-another-docker-plugin with MIT License 4 votes vote down vote up
@Ignore
    @Test
    public void testComboBuild() throws Throwable {
        jRule.getInstance().setNumExecutors(0);
//        jRule.createSlave();
//        jRule.createSlave("my-slave", "remote-slave", new EnvVars());
        final UsernamePasswordCredentialsImpl credentials = new UsernamePasswordCredentialsImpl(CredentialsScope.SYSTEM,
                null, "description", "vagrant", "vagrant");

        CredentialsStore store = CredentialsProvider.lookupStores(jRule.getInstance()).iterator().next();
        store.addCredentials(Domain.global(), credentials);

        final SSHLauncher sshLauncher = new SSHLauncher("192.168.33.10", 22, credentials.getId(),
                "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005", //jvmopts
                "", //      String javaPath,
                "",  //      String prefixStartSlaveCmd,
                "", //      String suffixStartSlaveCmd,
                20, //      Integer launchTimeoutSeconds,
                1, //      Integer maxNumRetries,
                3,//      Integer retryWaitTime
                new NonVerifyingKeyVerificationStrategy()
        );
        final DumbSlave dumbSlave = new DumbSlave("docker-daemon", "/home/vagrant/jenkins2", sshLauncher);
        jRule.getInstance().addNode(dumbSlave);
        await().timeout(60, SECONDS).until(() -> assertThat(dumbSlave.getChannel(), notNullValue()));
        String dockerfilePath = dumbSlave.getChannel().call(new StringThrowableCallable());


        final CredentialsYADockerConnector dockerConnector = new CredentialsYADockerConnector()
                .withConnectorType(JERSEY)
                .withServerUrl("tcp://127.0.0.1:2376")
                .withSslConfig(new LocalDirectorySSLConfig("/home/vagrant/keys"));
//                .withCredentials(new DockerDaemonFileCredentials(null, "docker-cert", "",
//                        "/home/vagrant/keys"));

        DockerBuildImage buildImage = new DockerBuildImage();
        buildImage.setBaseDirectory(dockerfilePath);
        buildImage.setPull(true);
        buildImage.setTags(Collections.singletonList("localhost:5000/myfirstimage"));

        DockerImageComboStep comboStep = new DockerImageComboStep(dockerConnector, buildImage);
        comboStep.setClean(true);
        comboStep.setCleanupDangling(true);
        comboStep.setPush(true);

        FreeStyleProject project = jRule.createFreeStyleProject("test");
        project.getBuildersList().add(comboStep);

        project.save();

        QueueTaskFuture<FreeStyleBuild> taskFuture = project.scheduleBuild2(0);
        FreeStyleBuild freeStyleBuild = taskFuture.get();
        jRule.waitForCompletion(freeStyleBuild);
        jRule.assertBuildStatusSuccess(freeStyleBuild);
    }