Java源码示例:org.jenkinsci.plugins.docker.commons.credentials.DockerServerEndpoint

示例1
@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));
       }
    });
}
 
示例2
@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;
}
 
示例3
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;
}
 
示例4
@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);
    });
}
 
示例5
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);
        }
    }
 
示例6
@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;
}
 
示例7
@DataBoundConstructor
public SampleDockerBuilder(DockerServerEndpoint server, DockerRegistryEndpoint registry) {
    if (server == null || registry == null) {
        throw new IllegalArgumentException();
    }
    this.server = server;
    this.registry = registry;
}
 
示例8
@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));
}
 
示例9
@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);
}
 
示例10
@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);
}
 
示例11
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;
}
 
示例12
@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());
    }
}
 
示例13
@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));
}
 
示例14
public DockerServerEndpoint getDockerHost() {
    return dockerHost;
}
 
示例15
@DataBoundConstructor public ServerEndpointStep(@Nonnull DockerServerEndpoint server) {
    assert server != null;
    this.server = server;
}
 
示例16
public DockerServerEndpoint getServer() {
    return server;
}
 
示例17
public DockerServerEndpoint getServer() {
    return server;
}
 
示例18
@Deprecated
public DockerServerEndpoint getDockerHost() {
    return dockerApi.getDockerHost();
}
 
示例19
public ListBoxModel doFillCredentialsIdItems(@AncestorInPath Item item, @QueryParameter String uri) {
    DockerServerEndpoint.DescriptorImpl descriptor = (DockerServerEndpoint.DescriptorImpl) Jenkins.getInstance().getDescriptorOrDie(DockerServerEndpoint.class);
    return descriptor.doFillCredentialsIdItems(item, uri);
}
 
示例20
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;
}
 
示例21
@DataBoundConstructor
public DockerAPI(DockerServerEndpoint dockerHost) {
    this.dockerHost = dockerHost;
}
 
示例22
public DockerServerEndpoint getDockerHost() {
    return dockerHost;
}
 
示例23
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);
}