org.jenkinsci.plugins.docker.commons.credentials.DockerServerEndpoint Java Examples

The following examples show how to use org.jenkinsci.plugins.docker.commons.credentials.DockerServerEndpoint. 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: DockerComputerConnectorTest.java    From docker-plugin with MIT License 6 votes vote down vote up
protected void should_connect_agent(DockerTemplate template) throws IOException, ExecutionException, InterruptedException, TimeoutException {

        // FIXME on CI windows nodes don't have Docker4Windows
        Assume.assumeFalse(SystemUtils.IS_OS_WINDOWS);

        String dockerHost = SystemUtils.IS_OS_WINDOWS ? "tcp://localhost:2375" : "unix:///var/run/docker.sock";

        DockerCloud cloud = new DockerCloud(cloudName, new DockerAPI(new DockerServerEndpoint(dockerHost, null)),
                Collections.singletonList(template));

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

        final FreeStyleProject project = j.createFreeStyleProject("test-docker-ssh");
        project.setAssignedLabel(Label.get(LABEL));
        project.getBuildersList().add(new Shell("whoami"));
        final QueueTaskFuture<FreeStyleBuild> scheduledBuild = project.scheduleBuild2(0);
        try {
            final FreeStyleBuild build = scheduledBuild.get(60L, TimeUnit.SECONDS);
            Assert.assertTrue(build.getResult() == Result.SUCCESS);
            Assert.assertTrue(build.getLog().contains("jenkins"));
        } finally {
            scheduledBuild.cancel(true);
        }
    }
 
Example #2
Source File: DockerNodeStepTest.java    From docker-plugin with MIT License 6 votes vote down vote up
@Test
public void defaults() {
    story.then(r -> {
        DockerNodeStep s = new DockerNodeStep("foo");
        s.setCredentialsId("");
        s.setDockerHost("");
        s.setRemoteFs("");
        UninstantiatedDescribable uninstantiated = new DescribableModel<>(DockerNodeStep.class).uninstantiate2(s);
        assertEquals(uninstantiated.toString(), Collections.singleton("image"), uninstantiated.getArguments().keySet());
        r.jenkins.clouds.add(new DockerCloud("whatever", new DockerAPI(new DockerServerEndpoint("unix:///var/run/docker.sock", null)), Collections.emptyList()));
        WorkflowJob j = r.createProject(WorkflowJob.class, "p");
        j.setDefinition(new CpsFlowDefinition(
            dockerNodeWithImage("openjdk:8") + " {\n" +
            "  sh 'java -version && whoami && pwd && touch stuff && ls -lat . ..'\n" +
            "}\n", true));
        r.buildAndAssertSuccess(j);
    });
}
 
Example #3
Source File: ServerEndpointStepTest.java    From docker-workflow-plugin with MIT License 6 votes vote down vote up
@Test public void configRoundTrip() {
    story.addStep(new Statement() {
        @Override public void evaluate() throws Throwable {
            IdCredentials serverCredentials = new DockerServerCredentials(CredentialsScope.GLOBAL, "serverCreds", null, "clientKey", "clientCertificate", "serverCaCertificate");
            CredentialsProvider.lookupStores(story.j.jenkins).iterator().next().addCredentials(Domain.global(), serverCredentials);
            StepConfigTester sct = new StepConfigTester(story.j);
            Map<String,Object> serverConfig = new TreeMap<String,Object>();
            serverConfig.put("uri", "tcp://host:2375");
            serverConfig.put("credentialsId", serverCredentials.getId());
            Map<String,Object> config = Collections.<String,Object>singletonMap("server", serverConfig);
            ServerEndpointStep step = DescribableHelper.instantiate(ServerEndpointStep.class, config);
            step = sct.configRoundTrip(step);
            DockerServerEndpoint server = step.getServer();
            assertNotNull(server);
            assertEquals("tcp://host:2375", server.getUri());
            assertEquals(serverCredentials.getId(), server.getCredentialsId());
            assertEquals(config, DescribableHelper.uninstantiate(step));
       }
    });
}
 
Example #4
Source File: TestableDockerContainerWatchdog.java    From docker-plugin with MIT License 6 votes vote down vote up
public static DockerAPI createMockedDockerAPI(List<Container> containerList) {
    DockerAPI result = Mockito.mock(DockerAPI.class);
    DockerClient client = Mockito.mock(DockerClient.class);
    Mockito.when(result.getClient()).thenReturn(client);
    DockerServerEndpoint dockerServerEndpoint = Mockito.mock(DockerServerEndpoint.class);
    Mockito.when(dockerServerEndpoint.getUri()).thenReturn("tcp://mocked-docker-host:2375");
    Mockito.when(result.getDockerHost()).thenReturn(dockerServerEndpoint);
    ListContainersCmd listContainerCmd = Mockito.mock(ListContainersCmd.class);
    Mockito.when(client.listContainersCmd()).thenReturn(listContainerCmd);
    Mockito.when(listContainerCmd.withShowAll(true)).thenReturn(listContainerCmd);
    Mockito.when(listContainerCmd.withLabelFilter(Matchers.anyMap())).thenAnswer( new Answer<ListContainersCmd>() {
        @Override
        public ListContainersCmd answer(InvocationOnMock invocation) throws Throwable {
            Map<String, String> arg = invocation.getArgumentAt(0, Map.class);
            String jenkinsInstanceIdInFilter = arg.get(DockerContainerLabelKeys.JENKINS_INSTANCE_ID);
            Assert.assertEquals(UNITTEST_JENKINS_ID, jenkinsInstanceIdInFilter);
            return listContainerCmd;
        }
    });
    Mockito.when(listContainerCmd.exec()).thenReturn(containerList);
    return result;
}
 
Example #5
Source File: DockerComputer.java    From docker-plugin with MIT License 6 votes vote down vote up
@Override
public EnvVars getEnvironment() throws IOException, InterruptedException {
    EnvVars variables = super.getEnvironment();
    final String containerIdOrNull = getContainerId();
    if (containerIdOrNull != null) {
        variables.put("DOCKER_CONTAINER_ID", containerIdOrNull);
    }
    final DockerCloud cloudOrNull = getCloud();
    if (cloudOrNull != null && cloudOrNull.isExposeDockerHost()) {
        variables.put("JENKINS_CLOUD_ID", cloudOrNull.name);
        final DockerAPI dockerApi = cloudOrNull.getDockerApi();
        final DockerServerEndpoint dockerHost = dockerApi.getDockerHost();
        final String dockerHostUriOrNull = dockerHost.getUri();
        if (dockerHostUriOrNull != null) {
            variables.put("DOCKER_HOST", dockerHostUriOrNull);
        }
    }
    return variables;
}
 
Example #6
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 #7
Source File: SampleDockerBuilder.java    From docker-commons-plugin with MIT License 5 votes vote down vote up
@DataBoundConstructor
public SampleDockerBuilder(DockerServerEndpoint server, DockerRegistryEndpoint registry) {
    if (server == null || registry == null) {
        throw new IllegalArgumentException();
    }
    this.server = server;
    this.registry = registry;
}
 
Example #8
Source File: ConfigTest.java    From docker-commons-plugin with MIT License 5 votes vote down vote up
@Test public void configRoundTrip() throws Exception {
    CredentialsStore store = CredentialsProvider.lookupStores(r.jenkins).iterator().next();
    IdCredentials serverCredentials = new DockerServerCredentials(CredentialsScope.GLOBAL, "serverCreds", null, Secret.fromString("clientKey"), "clientCertificate", "serverCaCertificate");
    store.addCredentials(Domain.global(), serverCredentials);
    IdCredentials registryCredentials = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "registryCreds", null, "me", "pass");
    store.addCredentials(Domain.global(), registryCredentials);
    SampleDockerBuilder b1 = new SampleDockerBuilder(new DockerServerEndpoint("", ""), new DockerRegistryEndpoint("http://dhe.mycorp.com/", registryCredentials.getId()));
    r.assertEqualDataBoundBeans(b1, r.configRoundtrip(b1));
    b1 = new SampleDockerBuilder(new DockerServerEndpoint("tcp://192.168.1.104:8333", serverCredentials.getId()), new DockerRegistryEndpoint("", ""));
    r.assertEqualDataBoundBeans(b1, r.configRoundtrip(b1));
    r.jenkins.getDescriptorByType(DockerTool.DescriptorImpl.class).setInstallations(new DockerTool("Docker 1.5", "/usr/local/docker15", Collections.<ToolProperty<?>>emptyList()));
    b1.setToolName("Docker 1.5");
    r.assertEqualDataBoundBeans(b1, r.configRoundtrip(b1));
}
 
Example #9
Source File: DockerCloud.java    From docker-plugin with MIT License 5 votes vote down vote up
@Deprecated
public DockerCloud(String name,
                   List<DockerTemplate> templates,
                   DockerServerEndpoint dockerHost,
                   int containerCap,
                   int connectTimeout,
                   int readTimeout,
                   String version,
                   String dockerHostname) {
    this(name, new DockerAPI(dockerHost, connectTimeout, readTimeout, version, dockerHostname), templates);
    setContainerCap(containerCap);
}
 
Example #10
Source File: DockerCloud.java    From docker-plugin with MIT License 5 votes vote down vote up
@Deprecated
public DockerCloud(String name,
                   List<DockerTemplate> templates,
                   String serverUrl,
                   int containerCap,
                   int connectTimeout,
                   int readTimeout,
                   String credentialsId,
                   String version,
                   String dockerHostname) {
    this(name, templates, new DockerServerEndpoint(serverUrl, credentialsId), containerCap, connectTimeout, readTimeout, version, dockerHostname);
}
 
Example #11
Source File: DockerSwarmCloud.java    From docker-swarm-plugin with MIT License 5 votes vote down vote up
@DataBoundConstructor
public DockerSwarmCloud(DockerServerEndpoint dockerHost, String dockerSwarmApiUrl, String jenkinsUrl,
        String swarmNetwork, String cacheDriverName, String tunnel, List<DockerSwarmAgentTemplate> agentTemplates) {
    super(DOCKER_SWARM_CLOUD_NAME);
    this.jenkinsUrl = jenkinsUrl;
    this.swarmNetwork = swarmNetwork;
    this.cacheDriverName = cacheDriverName;
    this.tunnel = tunnel;
    if (agentTemplates != null) {
        this.agentTemplates = agentTemplates;
    }
    this.dockerHost = dockerHost;
}
 
Example #12
Source File: DockerAPI.java    From docker-plugin with MIT License 5 votes vote down vote up
@RequirePOST
public FormValidation doTestConnection(
        @AncestorInPath Item context,
        @QueryParameter String uri,
        @QueryParameter String credentialsId,
        @QueryParameter String apiVersion,
        @QueryParameter int connectTimeout,
        @QueryParameter int readTimeout
) {
    throwIfNoPermission(context);
    final FormValidation credentialsIdCheckResult = doCheckCredentialsId(context, uri, credentialsId);
    if (credentialsIdCheckResult != FormValidation.ok()) {
        return FormValidation.error("Invalid credentials");
    }
    try {
        final DockerServerEndpoint dsep = new DockerServerEndpoint(uri, credentialsId);
        final DockerAPI dapi = new DockerAPI(dsep, connectTimeout, readTimeout, apiVersion, null);
        try(final DockerClient dc = dapi.getClient()) {
            final VersionCmd vc = dc.versionCmd();
            final Version v = vc.exec();
            final String actualVersion = v.getVersion();
            final String actualApiVersion = v.getApiVersion();
            return FormValidation.ok("Version = " + actualVersion + ", API Version = " + actualApiVersion);
        }
    } catch (Exception e) {
        return FormValidation.error(e, e.getMessage());
    }
}
 
Example #13
Source File: DockerAPI.java    From docker-plugin with MIT License 5 votes vote down vote up
public DockerAPI(DockerServerEndpoint dockerHost, int connectTimeout, int readTimeout, String apiVersion, String hostname) {
    this.dockerHost = dockerHost;
    this.connectTimeout = connectTimeout;
    this.readTimeout = readTimeout;
    this.apiVersion = apiVersion;
    this.hostname = hostname;
}
 
Example #14
Source File: DockerNodeStep.java    From docker-plugin with MIT License 4 votes vote down vote up
public ListBoxModel doFillCredentialsIdItems(@AncestorInPath Item item, @QueryParameter String uri) {
    DockerServerEndpoint.DescriptorImpl descriptor = (DockerServerEndpoint.DescriptorImpl) Jenkins.getInstance().getDescriptorOrDie(DockerServerEndpoint.class);
    return descriptor.doFillCredentialsIdItems(item, uri);
}
 
Example #15
Source File: DockerAPI.java    From docker-plugin with MIT License 4 votes vote down vote up
public ListBoxModel doFillCredentialsIdItems(@AncestorInPath Item context, @QueryParameter String uri) {
    final DockerServerEndpoint.DescriptorImpl descriptor = (DockerServerEndpoint.DescriptorImpl) Jenkins.getInstance().getDescriptorOrDie(DockerServerEndpoint.class);
    return descriptor.doFillCredentialsIdItems(context, uri);
}
 
Example #16
Source File: DockerAPI.java    From docker-plugin with MIT License 4 votes vote down vote up
public DockerServerEndpoint getDockerHost() {
    return dockerHost;
}
 
Example #17
Source File: DockerAPI.java    From docker-plugin with MIT License 4 votes vote down vote up
@DataBoundConstructor
public DockerAPI(DockerServerEndpoint dockerHost) {
    this.dockerHost = dockerHost;
}
 
Example #18
Source File: DockerNodeStepExecution.java    From docker-plugin with MIT License 4 votes vote down vote up
private DockerTransientNode createNode(TaskListener listener) {
    final String uuid = UUID.randomUUID().toString();
    final DockerTemplate t = new DockerTemplate(
            new DockerTemplateBase(image),
            (DockerComputerConnector) connector,
            uuid, remoteFs, "1");
    t.setMode(Node.Mode.EXCLUSIVE);

    final DockerAPI api;
    if (dockerHost == null && credentialsId == null) {
        api = defaultApi();
    } else {
        api = new DockerAPI(new DockerServerEndpoint(dockerHost, credentialsId));
    }

    final DockerTransientNode node;
    Computer computer = null;
    try {
        node = t.provisionNode(api, listener);
        node.setDockerAPI(api);
        node.setAcceptingTasks(false); // Prevent this node to be used by tasks from build queue
        Jenkins.getInstance().addNode(node);

        listener.getLogger().println("Waiting for node to be online ...");
        // TODO maybe rely on ComputerListener to catch onOnline() event ?
        while ((computer = node.toComputer()) == null || computer.isOffline()) {
            Thread.sleep(1000);
        }
        listener.getLogger().println("Node " + node.getNodeName() + " is online.");
    } catch (Exception e) {
        // Provisioning failed ! capture computer log and dump to pipeline log to assist in diagnostic
        if (computer != null) {
            try {
                final String computerLogAsString = computer.getLog();
                listener.getLogger().println("Node provisioning failed: " + e);
                listener.getLogger().println(computerLogAsString);
                listener.getLogger().println("See log above for details.");
            } catch (IOException x) {
                listener.getLogger().println("Failed to capture docker agent provisioning log " + x);
            }
        }
        getContext().onFailure(e);
        return null;
    }
    return node;
}
 
Example #19
Source File: DockerCloud.java    From docker-plugin with MIT License 4 votes vote down vote up
@Deprecated
public DockerServerEndpoint getDockerHost() {
    return dockerApi.getDockerHost();
}
 
Example #20
Source File: SampleDockerBuilder.java    From docker-commons-plugin with MIT License 4 votes vote down vote up
public DockerServerEndpoint getServer() {
    return server;
}
 
Example #21
Source File: ServerEndpointStep.java    From docker-workflow-plugin with MIT License 4 votes vote down vote up
public DockerServerEndpoint getServer() {
    return server;
}
 
Example #22
Source File: ServerEndpointStep.java    From docker-workflow-plugin with MIT License 4 votes vote down vote up
@DataBoundConstructor public ServerEndpointStep(@Nonnull DockerServerEndpoint server) {
    assert server != null;
    this.server = server;
}
 
Example #23
Source File: DockerSwarmCloud.java    From docker-swarm-plugin with MIT License 4 votes vote down vote up
public DockerServerEndpoint getDockerHost() {
    return dockerHost;
}