Search in sources :

Example 31 with Client

use of io.fabric8.kubernetes.client.Client in project kubernetes by ballerinax.

the class DockerHandler method pushImage.

/**
 * Push docker image.
 *
 * @param dockerModel DockerModel
 * @throws InterruptedException When error with docker build process
 * @throws IOException          When error with docker build process
 */
public void pushImage(DockerModel dockerModel) throws InterruptedException, IOException, KubernetesPluginException {
    AuthConfig authConfig = new AuthConfigBuilder().withUsername(dockerModel.getUsername()).withPassword(dockerModel.getPassword()).build();
    Config config = new ConfigBuilder().withDockerUrl(dockerModel.getDockerHost()).addToAuthConfigs(RegistryUtils.extractRegistry(dockerModel.getName()), authConfig).build();
    DockerClient client = new DefaultDockerClient(config);
    final DockerError dockerError = new DockerError();
    OutputHandle handle = client.image().withName(dockerModel.getName()).push().usingListener(new EventListener() {

        @Override
        public void onSuccess(String message) {
            pushDone.countDown();
        }

        @Override
        public void onError(String message) {
            pushDone.countDown();
            dockerError.setErrorMsg("error pushing docker image: " + message);
        }

        @Override
        public void onError(Throwable t) {
            pushDone.countDown();
            dockerError.setErrorMsg("error pushing docker image: " + t.getMessage());
        }

        @Override
        public void onEvent(String event) {
            printDebug(event);
        }
    }).toRegistry();
    pushDone.await();
    handle.close();
    client.close();
    handleError(dockerError);
}
Also used : AuthConfigBuilder(io.fabric8.docker.api.model.AuthConfigBuilder) DefaultDockerClient(io.fabric8.docker.client.DefaultDockerClient) DockerClient(io.fabric8.docker.client.DockerClient) Config(io.fabric8.docker.client.Config) AuthConfig(io.fabric8.docker.api.model.AuthConfig) DefaultDockerClient(io.fabric8.docker.client.DefaultDockerClient) AuthConfigBuilder(io.fabric8.docker.api.model.AuthConfigBuilder) ConfigBuilder(io.fabric8.docker.client.ConfigBuilder) OutputHandle(io.fabric8.docker.dsl.OutputHandle) AuthConfig(io.fabric8.docker.api.model.AuthConfig) EventListener(io.fabric8.docker.dsl.EventListener)

Example 32 with Client

use of io.fabric8.kubernetes.client.Client in project fabric8 by jboss-fuse.

the class ExampleCamelClusterTest method testRegistryEntries.

@Test
public void testRegistryEntries() throws Exception {
    System.out.println(executeCommand("fabric:create -n --wait-for-provisioning root"));
    // System.out.println(executeCommand("shell:info"));
    // System.out.println(executeCommand("fabric:info"));
    // System.out.println(executeCommand("fabric:profile-list"));
    ServiceProxy<FabricService> fabricProxy = ServiceProxy.createServiceProxy(bundleContext, FabricService.class);
    try {
        FabricService fabricService = fabricProxy.getService();
        CuratorFramework curator = fabricService.adapt(CuratorFramework.class);
        Set<ContainerProxy> containers = ContainerBuilder.create(fabricProxy, 3).withName("fabric-camel").assertProvisioningResult().build();
        try {
            // We will use the first container as a client and the rest as servers.
            LinkedList<Container> containerList = new LinkedList<Container>(containers);
            Container client = containerList.removeLast();
            LinkedList<Container> servers = new LinkedList<Container>(containerList);
            for (Container c : servers) {
                Profile p1 = c.getVersion().getRequiredProfile("feature-camel");
                Profile p2 = c.getVersion().getRequiredProfile("example-camel-cluster-cluster.server");
                c.setProfiles(new Profile[] { p1, p2 });
            }
            Provision.provisioningSuccess(servers, PROVISION_TIMEOUT);
            Profile p1 = client.getVersion().getRequiredProfile("feature-camel");
            Profile p2 = client.getVersion().getRequiredProfile("example-camel-cluster-cluster.client");
            client.setProfiles(new Profile[] { p1, p2 });
            Provision.provisioningSuccess(Arrays.asList(new Container[] { client }), PROVISION_TIMEOUT);
            System.out.println(executeCommand("fabric:container-list"));
            System.out.println(executeCommand("fabric:profile-display --overlay fabric-camel-server"));
            // Check that the entries have been properly propagated.
            Assert.assertNotNull(exists(curator, "/fabric/registry/camel/endpoints"));
            Assert.assertEquals(1, getChildren(curator, "/fabric/registry/camel/endpoints").size());
            Assert.assertTrue(Provision.waitForCondition(Arrays.asList(client), new ContainerCondition() {

                @Override
                public Boolean checkConditionOnContainer(final Container c) {
                    return getCompletedExchangesCount(c) > 0;
                }
            }, 60000L));
            // We want to kill all but one server, so we take out the first and keep it to the end.
            Container lastActiveServerContainer = servers.removeLast();
            for (Container c : servers) {
                try {
                    c.destroy(true);
                } catch (Exception ex) {
                // ignore.
                }
                // Get the number of exchanges completed before we kill the server.
                final int completed = getCompletedExchangesCount(client);
                // Ensure that we still have messages flowing
                Assert.assertTrue(Provision.waitForCondition(Arrays.asList(client), new ContainerCondition() {

                    @Override
                    public Boolean checkConditionOnContainer(final Container c) {
                        return getCompletedExchangesCount(c) > completed + 3;
                    }
                }, 60000L));
            }
            System.out.println(new AnsiString(executeCommand("fabric:container-connect -u admin -p admin " + client.getId() + " camel:route-info fabric-client")).getPlain().toString());
        } finally {
            ContainerBuilder.destroy(containers);
        }
    } finally {
        fabricProxy.close();
    }
}
Also used : AnsiString(org.fusesource.jansi.AnsiString) LinkedList(java.util.LinkedList) Profile(io.fabric8.api.Profile) ContainerCondition(io.fabric8.itests.paxexam.support.ContainerCondition) CuratorFramework(org.apache.curator.framework.CuratorFramework) Container(io.fabric8.api.Container) FabricService(io.fabric8.api.FabricService) ContainerProxy(io.fabric8.itests.paxexam.support.ContainerProxy) Test(org.junit.Test)

Example 33 with Client

use of io.fabric8.kubernetes.client.Client in project fabric8 by jboss-fuse.

the class ProxyServlet method executeProxyRequest.

/**
 * Executes the {@link HttpMethod} passed in and sends the proxy response
 * back to the client via the given {@link javax.servlet.http.HttpServletResponse}
 *
 * @param proxyDetails
 * @param httpMethodProxyRequest An object representing the proxy request to be made
 * @param httpServletResponse    An object by which we can send the proxied
 *                               response back to the client
 * @throws java.io.IOException            Can be thrown by the {@link HttpClient}.executeMethod
 * @throws javax.servlet.ServletException Can be thrown to indicate that another error has occurred
 */
private void executeProxyRequest(ProxyDetails proxyDetails, HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException {
    httpMethodProxyRequest.setDoAuthentication(false);
    httpMethodProxyRequest.setFollowRedirects(false);
    // Create a default HttpClient
    HttpClient httpClient = proxyDetails.createHttpClient(httpMethodProxyRequest);
    // Execute the request
    int intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest);
    // Hooray for open source software
    if (intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES && /* 300 */
    intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED) /* 304 */
    {
        String stringStatusCode = Integer.toString(intProxyResponseCode);
        String stringLocation = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue();
        if (stringLocation == null) {
            throw new ServletException("Received status code: " + stringStatusCode + " but no " + STRING_LOCATION_HEADER + " header was found in the response");
        }
        // Modify the redirect to go to this proxy servlet rather that the proxied host
        String stringMyHostName = httpServletRequest.getServerName();
        if (httpServletRequest.getServerPort() != 80) {
            stringMyHostName += ":" + httpServletRequest.getServerPort();
        }
        stringMyHostName += httpServletRequest.getContextPath();
        httpServletResponse.sendRedirect(stringLocation.replace(proxyDetails.getProxyHostAndPort() + proxyDetails.getProxyPath(), stringMyHostName));
        return;
    } else if (intProxyResponseCode == HttpServletResponse.SC_NOT_MODIFIED) {
        // 304 needs special handling.  See:
        // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304
        // We get a 304 whenever passed an 'If-Modified-Since'
        // header and the data on disk has not changed; server
        // responds w/ a 304 saying I'm not going to send the
        // body because the file has not changed.
        httpServletResponse.setIntHeader(STRING_CONTENT_LENGTH_HEADER_NAME, 0);
        httpServletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }
    // Pass the response code back to the client
    httpServletResponse.setStatus(intProxyResponseCode);
    // Pass response headers back to the client
    Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders();
    for (Header header : headerArrayResponse) {
        if (!ProxySupport.isHopByHopHeader(header.getName())) {
            if (ProxySupport.isSetCookieHeader(header)) {
                HttpProxyRule proxyRule = proxyDetails.getProxyRule();
                String setCookie = ProxySupport.replaceCookieAttributes(header.getValue(), proxyRule.getCookiePath(), proxyRule.getCookieDomain());
                httpServletResponse.setHeader(header.getName(), setCookie);
            } else {
                httpServletResponse.setHeader(header.getName(), header.getValue());
            }
        }
    }
    // check if we got data, that is either the Content-Length > 0
    // or the response code != 204
    int code = httpMethodProxyRequest.getStatusCode();
    boolean noData = code == HttpStatus.SC_NO_CONTENT;
    if (!noData) {
        String length = httpServletRequest.getHeader(STRING_CONTENT_LENGTH_HEADER_NAME);
        if (length != null && "0".equals(length.trim())) {
            noData = true;
        }
    }
    LOG.trace("Response has data? {}", !noData);
    if (!noData) {
        // Send the content to the client
        InputStream inputStreamProxyResponse = httpMethodProxyRequest.getResponseBodyAsStream();
        BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStreamProxyResponse);
        OutputStream outputStreamClientResponse = httpServletResponse.getOutputStream();
        int intNextByte;
        while ((intNextByte = bufferedInputStream.read()) != -1) {
            outputStreamClientResponse.write(intNextByte);
        }
    }
}
Also used : ServletException(javax.servlet.ServletException) Header(org.apache.commons.httpclient.Header) BufferedInputStream(java.io.BufferedInputStream) BufferedInputStream(java.io.BufferedInputStream) InputStream(java.io.InputStream) HttpClient(org.apache.commons.httpclient.HttpClient) OutputStream(java.io.OutputStream) HttpProxyRule(io.fabric8.gateway.model.HttpProxyRule)

Example 34 with Client

use of io.fabric8.kubernetes.client.Client in project fabric8 by jboss-fuse.

the class ExampleCxfProfileLongTest method testExample.

@Test
public void testExample() throws Exception {
    System.out.println("creating the cxf-server container.");
    ServiceProxy<FabricService> fabricProxy = ServiceProxy.createServiceProxy(bundleContext, FabricService.class);
    try {
        Set<ContainerProxy> containers = ContainerBuilder.create(fabricProxy).withName("child").withProfiles("example-cxf-cxf.server").assertProvisioningResult().build();
        try {
            assertTrue("We should create the cxf-server container.", containers.size() == 1);
            System.out.println("created the cxf-server container.");
            // install bundle of CXF
            Thread.sleep(2000);
            System.out.println(executeCommand("fabric:cluster-list"));
            // install bundle of CXF
            Thread.sleep(2000);
            // calling the client here
            System.out.println("install the cxf client demo in root container");
            // This test need to take sometime to download the cxf feature related bundles
            System.out.println(executeCommand("features:install fabric-cxf", 600000, false));
            String projectVersion = System.getProperty("fabricitest.version");
            // install bundle of CXF demo client
            System.out.println(executeCommand("osgi:install -s mvn:io.fabric8.examples/fabric-cxf-demo-common/" + projectVersion));
            System.out.println(executeCommand("osgi:install -s mvn:io.fabric8.examples/fabric-cxf-demo-client/" + projectVersion));
            System.out.println(executeCommand("osgi:list"));
            System.out.println("invoking the web service");
            Hello proxy = ServiceLocator.awaitService(bundleContext, Hello.class);
            assertNotNull(proxy);
            String result1 = proxy.sayHello();
            String result2 = proxy.sayHello();
            assertNotSame("We should get the two different result", result1, result2);
        } finally {
            ContainerBuilder.destroy(containers);
        }
    } finally {
        fabricProxy.close();
    }
}
Also used : Hello(io.fabric8.demo.cxf.Hello) FabricService(io.fabric8.api.FabricService) ContainerProxy(io.fabric8.itests.paxexam.support.ContainerProxy) Test(org.junit.Test)

Example 35 with Client

use of io.fabric8.kubernetes.client.Client in project fabric8 by jboss-fuse.

the class FabricMavenProxyTest method testUpload.

@Test
public void testUpload() throws Exception {
    String featureLocation = System.getProperty("feature.location");
    System.out.println("Testing with feature from:" + featureLocation);
    System.out.println(executeCommand("fabric:create -n --wait-for-provisioning"));
    // System.out.println(executeCommand("shell:info"));
    // System.out.println(executeCommand("fabric:info"));
    // System.out.println(executeCommand("fabric:profile-list"));
    ServiceProxy<FabricService> fabricProxy = ServiceProxy.createServiceProxy(bundleContext, FabricService.class);
    try {
        Set<ContainerProxy> containers = ContainerBuilder.create(fabricProxy, 2).withName("maven").withProfiles("fabric").waitForProvisioning(10 * 60 * 1000L).assertProvisioningResult().build();
        try {
            List<String> uploadUrls = new ArrayList<String>();
            ServiceProxy<CuratorFramework> curatorProxy = ServiceProxy.createServiceProxy(bundleContext, CuratorFramework.class);
            try {
                CuratorFramework curator = curatorProxy.getService();
                List<String> children = ZooKeeperUtils.getChildren(curator, ZkPath.MAVEN_PROXY.getPath("upload"));
                for (String child : children) {
                    String uploadeUrl = ZooKeeperUtils.getSubstitutedPath(curator, ZkPath.MAVEN_PROXY.getPath("upload") + "/" + child);
                    uploadUrls.add(uploadeUrl);
                }
            } finally {
                curatorProxy.close();
            }
            // Pick a random maven proxy from the list.
            Random random = new Random();
            int index = random.nextInt(uploadUrls.size());
            String targetUrl = uploadUrls.get(index);
            String uploadUrl = targetUrl + "itest/itest/1.0/itest-1.0-features.xml";
            System.out.println("Using URI: " + uploadUrl);
            BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("admin", "admin"));
            CloseableHttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).build();
            HttpPut put = new HttpPut(uploadUrl);
            NFileEntity entity = new NFileEntity(new File(featureLocation), ContentType.TEXT_XML);
            put.setEntity(entity);
            HttpResponse response = client.execute(put);
            System.out.println("Response:" + response.getStatusLine());
            Assert.assertTrue(response.getStatusLine().getStatusCode() == 200 || response.getStatusLine().getStatusCode() == 202);
            System.out.println(executeCommand("fabric:profile-edit --repository mvn:itest/itest/1.0/xml/features default"));
            System.out.println(executeCommand("fabric:profile-edit --feature example-cbr default"));
            Provision.containerStatus(containers, PROVISION_TIMEOUT);
        } finally {
            ContainerBuilder.destroy(containers);
        }
    } finally {
        fabricProxy.close();
    }
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) NFileEntity(org.apache.http.nio.entity.NFileEntity) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) ArrayList(java.util.ArrayList) HttpResponse(org.apache.http.HttpResponse) HttpPut(org.apache.http.client.methods.HttpPut) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) CuratorFramework(org.apache.curator.framework.CuratorFramework) Random(java.util.Random) FabricService(io.fabric8.api.FabricService) File(java.io.File) ContainerProxy(io.fabric8.itests.paxexam.support.ContainerProxy) Test(org.junit.Test)

Aggregations

KubernetesClient (io.fabric8.kubernetes.client.KubernetesClient)42 Test (org.junit.Test)34 DefaultKubernetesClient (io.fabric8.kubernetes.client.DefaultKubernetesClient)29 Service (io.fabric8.kubernetes.api.model.Service)24 OpenShiftClient (io.fabric8.openshift.client.OpenShiftClient)23 IOException (java.io.IOException)23 File (java.io.File)22 ArrayList (java.util.ArrayList)21 HashMap (java.util.HashMap)20 KubernetesClientException (io.fabric8.kubernetes.client.KubernetesClientException)18 Pod (io.fabric8.kubernetes.api.model.Pod)14 DefaultOpenShiftClient (io.fabric8.openshift.client.DefaultOpenShiftClient)14 ClientInvokerImpl (io.fabric8.dosgi.tcp.ClientInvokerImpl)8 ServerInvokerImpl (io.fabric8.dosgi.tcp.ServerInvokerImpl)8 URL (java.net.URL)8 Map (java.util.Map)8 ServerInvoker (io.fabric8.dosgi.io.ServerInvoker)7 DockerClient (io.fabric8.docker.client.DockerClient)6 MalformedURLException (java.net.MalformedURLException)6 Session (io.fabric8.arquillian.kubernetes.Session)5