Search in sources :

Example 16 with Client

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

the class DeployToProfileMojo method execute.

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    if (isIgnoreProject())
        return;
    try {
        ProjectRequirements requirements = new ProjectRequirements();
        if (isIncludeArtifact()) {
            DependencyDTO rootDependency = loadRootDependency();
            requirements.setRootDependency(rootDependency);
        }
        configureRequirements(requirements);
        // validate requirements
        if (requirements.getProfileId() != null) {
            // make sure the profile id is a valid name
            FabricValidations.validateProfileName(requirements.getProfileId());
        }
        boolean newUserAdded = false;
        fabricServer = mavenSettings.getServer(serverId);
        // we may have username and password from jolokiaUrl
        String jolokiaUsername = null;
        String jolokiaPassword = null;
        try {
            URL url = new URL(jolokiaUrl);
            String s = url.getUserInfo();
            if (Strings.isNotBlank(s) && s.indexOf(':') > 0) {
                int idx = s.indexOf(':');
                jolokiaUsername = s.substring(0, idx);
                jolokiaPassword = s.substring(idx + 1);
                customUsernameAndPassword = true;
            }
        } catch (MalformedURLException e) {
            throw new IllegalArgumentException("Option jolokiaUrl is invalid due " + e.getMessage());
        }
        // jolokia url overrides username/password configured in maven settings
        if (jolokiaUsername != null) {
            if (fabricServer == null) {
                fabricServer = new Server();
            }
            getLog().info("Using username: " + jolokiaUsername + " and password from provided jolokiaUrl option");
            fabricServer.setId(serverId);
            fabricServer.setUsername(jolokiaUsername);
            fabricServer.setPassword(jolokiaPassword);
        }
        if (fabricServer == null) {
            boolean create = false;
            if (mavenSettings.isInteractiveMode() && mavenSettingsWriter != null) {
                System.out.println("Maven settings file: " + mavenSettingsFile.getAbsolutePath());
                System.out.println();
                System.out.println();
                System.out.println("There is no <server> section in your ~/.m2/settings.xml file for the server id: " + serverId);
                System.out.println();
                System.out.println("You can enter the username/password now and have the settings.xml updated or you can do this by hand if you prefer.");
                System.out.println();
                while (true) {
                    String value = readInput("Would you like to update the settings.xml file now? (y/n): ").toLowerCase();
                    if (value.startsWith("n")) {
                        System.out.println();
                        System.out.println();
                        break;
                    } else if (value.startsWith("y")) {
                        create = true;
                        break;
                    }
                }
                if (create) {
                    System.out.println("Please let us know the login details for this server: " + serverId);
                    System.out.println();
                    String userName = readInput("Username: ");
                    String password = readPassword("Password: ");
                    String password2 = readPassword("Repeat Password: ");
                    while (!password.equals(password2)) {
                        System.out.println("Passwords do not match, please try again.");
                        password = readPassword("Password: ");
                        password2 = readPassword("Repeat Password: ");
                    }
                    System.out.println();
                    fabricServer = new Server();
                    fabricServer.setId(serverId);
                    fabricServer.setUsername(userName);
                    fabricServer.setPassword(password);
                    mavenSettings.addServer(fabricServer);
                    if (mavenSettingsFile.exists()) {
                        int counter = 1;
                        while (true) {
                            File backupFile = new File(mavenSettingsFile.getAbsolutePath() + ".backup-" + counter++ + ".xml");
                            if (!backupFile.exists()) {
                                System.out.println("Copied original: " + mavenSettingsFile.getAbsolutePath() + " to: " + backupFile.getAbsolutePath());
                                Files.copy(mavenSettingsFile, backupFile);
                                break;
                            }
                        }
                    }
                    Map<String, Object> config = new HashMap<String, Object>();
                    mavenSettingsWriter.write(mavenSettingsFile, config, mavenSettings);
                    System.out.println("Updated settings file: " + mavenSettingsFile.getAbsolutePath());
                    System.out.println();
                    newUserAdded = true;
                }
            }
        }
        if (fabricServer == null) {
            String message = "No <server> element can be found in ~/.m2/settings.xml for the server <id>" + serverId + "</id> so we cannot connect to fabric8!\n\n" + "Please add the following to your ~/.m2/settings.xml file (using the correct user/password values):\n\n" + "<servers>\n" + "  <server>\n" + "    <id>" + serverId + "</id>\n" + "    <username>admin</username>\n" + "    <password>admin</password>\n" + "  </server>\n" + "</servers>\n";
            getLog().error(message);
            throw new MojoExecutionException(message);
        }
        // now lets invoke the mbean
        J4pClient client = createJolokiaClient();
        if (upload) {
            uploadDeploymentUnit(client, newUserAdded || customUsernameAndPassword);
        } else {
            getLog().info("Uploading to the fabric8 maven repository is disabled");
        }
        DeployResults results = uploadRequirements(client, requirements);
        if (results != null) {
            uploadReadMeFile(client, results);
            uploadProfileConfigurations(client, results);
            refreshProfile(client, results);
        }
    } catch (MojoExecutionException e) {
        throw e;
    } catch (Exception e) {
        throw new MojoExecutionException("Error executing", e);
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) DeployResults(io.fabric8.deployer.dto.DeployResults) Server(org.apache.maven.settings.Server) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) HashMap(java.util.HashMap) J4pClient(org.jolokia.client.J4pClient) DependencyDTO(io.fabric8.deployer.dto.DependencyDTO) URL(java.net.URL) MalformedObjectNameException(javax.management.MalformedObjectNameException) J4pRemoteException(org.jolokia.client.exception.J4pRemoteException) ArtifactDeploymentException(org.apache.maven.artifact.deployer.ArtifactDeploymentException) J4pConnectException(org.jolokia.client.exception.J4pConnectException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) MojoFailureException(org.apache.maven.plugin.MojoFailureException) J4pException(org.jolokia.client.exception.J4pException) ProjectRequirements(io.fabric8.deployer.dto.ProjectRequirements) File(java.io.File)

Example 17 with Client

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

the class DeployToProfileMojo method uploadRequirements.

protected DeployResults uploadRequirements(J4pClient client, ProjectRequirements requirements) throws Exception {
    String json = DtoHelper.getMapper().writeValueAsString(requirements);
    ObjectName mbeanName = ProjectDeployerImpl.OBJECT_NAME;
    getLog().info("Updating " + (requirements.isAbstractProfile() ? "abstract " : "") + "profile: " + requirements.getProfileId() + " with parent profile(s): " + requirements.getParentProfiles() + (requirements.isUseResolver() ? " using OSGi resolver" : "") + (requirements.isLocked() ? " locked" : ""));
    getLog().info("About to invoke mbean " + mbeanName + " on jolokia URL: " + jolokiaUrl + " with user: " + fabricServer.getUsername());
    getLog().debug("JSON: " + json);
    try {
        // Append bundles to existing profile bundles if we're not running the plugin at project root
        Boolean appendBundles = !mavenSession.getExecutionRootDirectory().equalsIgnoreCase(project.getBasedir().toString());
        J4pExecRequest request = new J4pExecRequest(mbeanName, "deployProjectJsonMergeOption(java.lang.String,boolean)", json, appendBundles);
        J4pResponse<J4pExecRequest> response = client.execute(request, "POST");
        Object value = response.getValue();
        if (value == null) {
            return null;
        } else {
            DeployResults answer = DtoHelper.getMapper().reader(DeployResults.class).readValue(value.toString());
            if (answer != null) {
                String profileUrl = answer.getProfileUrl();
                if (profileUrl != null) {
                    getLog().info("");
                    getLog().info("Profile page: " + profileUrl);
                    getLog().info("");
                } else {
                    getLog().info("Result: " + answer);
                }
            } else {
                getLog().info("Result: " + value);
            }
            return answer;
        }
    } catch (J4pRemoteException e) {
        if (e.getMessage().contains(".InstanceNotFoundException")) {
            throw new MojoExecutionException("Could not find the mbean " + mbeanName + " in the JVM for " + jolokiaUrl + ". Are you sure this JVM is running the Fabric8 console?");
        } else {
            getLog().error("Failed to invoke mbean " + mbeanName + " on jolokia URL: " + jolokiaUrl + " with user: " + fabricServer.getUsername() + ". Error: " + e.getErrorType());
            getLog().error("Stack: " + e.getRemoteStackTrace());
            throw e;
        }
    }
}
Also used : J4pRemoteException(org.jolokia.client.exception.J4pRemoteException) DeployResults(io.fabric8.deployer.dto.DeployResults) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) J4pExecRequest(org.jolokia.client.request.J4pExecRequest) ObjectName(javax.management.ObjectName)

Example 18 with Client

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

the class InvocationTest method testUnderLoadAsyncProto.

@Test(timeout = 30 * 1000)
public void testUnderLoadAsyncProto() throws Exception {
    HashMap<String, SerializationStrategy> map = new HashMap<String, SerializationStrategy>();
    map.put("protobuf", new ProtobufSerializationStrategy());
    DispatchQueue queue = Dispatch.createQueue();
    ServerInvokerImpl server = new ServerInvokerImpl("tcp://localhost:0", queue, map);
    server.start();
    ClientInvokerImpl client = new ClientInvokerImpl(queue, map);
    client.start();
    try {
        final HelloImpl helloImpl = new HelloImpl();
        server.registerService("service-id", new ServerInvoker.ServiceFactory() {

            public Object get() {
                return helloImpl;
            }

            public void unget() {
            }
        }, HelloImpl.class.getClassLoader());
        InvocationHandler handler = client.getProxy(server.getConnectAddress(), "service-id", HelloImpl.class.getClassLoader());
        final Hello hello = (Hello) Proxy.newProxyInstance(HelloImpl.class.getClassLoader(), new Class[] { Hello.class }, handler);
        final AtomicInteger requests = new AtomicInteger(0);
        final AtomicInteger failures = new AtomicInteger(0);
        final long[] latencies = new long[BENCHMARK_CLIENTS * BENCHMARK_INVOCATIONS_PER_CLIENT];
        final long start = System.nanoTime();
        AsyncClient[] threads = new AsyncClient[BENCHMARK_CLIENTS];
        for (int t = 0; t < BENCHMARK_CLIENTS; t++) {
            threads[t] = new AsyncClient(t, BENCHMARK_INVOCATIONS_PER_CLIENT, hello, failures, requests, latencies);
            threads[t].start();
        }
        for (int t = 0; t < BENCHMARK_CLIENTS; t++) {
            threads[t].join();
        }
        final long end = System.nanoTime();
        long latency_sum = 0;
        for (int t = 0; t < latencies.length; t++) {
            if (latencies[t] != -1) {
                latency_sum += latencies[t];
            }
        }
        double latency_avg = ((latency_sum * 1.0d) / requests.get()) / MILLIS_IN_A_NANO;
        double request_rate = ((requests.get() * 1.0d) / (end - start)) * SECONDS_IN_A_NANO;
        System.err.println(String.format("Requests/Second: %,.2f", request_rate));
        System.err.println(String.format("Average request latency: %,.2f ms", latency_avg));
        System.err.println("Error Ratio: " + failures.get() + " / " + requests.get());
    } finally {
        server.stop();
        client.stop();
    }
}
Also used : ServerInvoker(io.fabric8.dosgi.io.ServerInvoker) HashMap(java.util.HashMap) InvocationHandler(java.lang.reflect.InvocationHandler) ClientInvokerImpl(io.fabric8.dosgi.tcp.ClientInvokerImpl) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ServerInvokerImpl(io.fabric8.dosgi.tcp.ServerInvokerImpl) DispatchQueue(org.fusesource.hawtdispatch.DispatchQueue) Test(org.junit.Test)

Example 19 with Client

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

the class InvocationTest method testOverflow.

@Test(timeout = 30 * 1000)
public void testOverflow() throws Exception {
    DispatchQueue queue = Dispatch.createQueue();
    HashMap<String, SerializationStrategy> map = new HashMap<String, SerializationStrategy>();
    map.put("protobuf", new ProtobufSerializationStrategy());
    ServerInvokerImpl server = new ServerInvokerImpl("tcp://localhost:0", queue, map);
    server.start();
    ClientInvokerImpl client = new ClientInvokerImpl(queue, map);
    client.start();
    try {
        server.registerService("service-id", new ServerInvoker.ServiceFactory() {

            public Object get() {
                return new HelloImpl();
            }

            public void unget() {
            }
        }, HelloImpl.class.getClassLoader());
        InvocationHandler handler = client.getProxy(server.getConnectAddress(), "service-id", HelloImpl.class.getClassLoader());
        final Hello hello = (Hello) Proxy.newProxyInstance(HelloImpl.class.getClassLoader(), new Class[] { Hello.class }, handler);
        final AtomicInteger requests = new AtomicInteger(0);
        final AtomicInteger responses = new AtomicInteger(0);
        final AtomicInteger failures = new AtomicInteger(0);
        char[] chars = new char[65 * 1024];
        final String payload = new String(chars);
        Thread[] threads = new Thread[BENCHMARK_CLIENTS];
        for (int t = 0; t < BENCHMARK_CLIENTS; t++) {
            threads[t] = new Thread() {

                public void run() {
                    try {
                        requests.incrementAndGet();
                        hello.hello(payload);
                        responses.incrementAndGet();
                    } catch (Throwable t) {
                        failures.incrementAndGet();
                    }
                }
            };
            threads[t].start();
        }
        for (int t = 0; t < BENCHMARK_CLIENTS; t++) {
            threads[t].join(10000);
            System.err.format("REQUEST: %d of %d%n", requests.get(), BENCHMARK_CLIENTS);
            System.err.format("RESPONSES: %d of %d%n", responses.get(), BENCHMARK_CLIENTS);
            assertEquals(threads[t].isAlive(), false);
        }
        assertEquals(BENCHMARK_CLIENTS, requests.get());
        assertEquals(BENCHMARK_CLIENTS, responses.get());
        assertEquals(0, failures.get());
    } finally {
        server.stop();
        client.stop();
    }
}
Also used : ServerInvoker(io.fabric8.dosgi.io.ServerInvoker) HashMap(java.util.HashMap) InvocationHandler(java.lang.reflect.InvocationHandler) ClientInvokerImpl(io.fabric8.dosgi.tcp.ClientInvokerImpl) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ServerInvokerImpl(io.fabric8.dosgi.tcp.ServerInvokerImpl) DispatchQueue(org.fusesource.hawtdispatch.DispatchQueue) Test(org.junit.Test)

Example 20 with Client

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

the class InvocationTest method testOverflowAsync.

@Test(timeout = 30 * 1000)
public void testOverflowAsync() throws Exception {
    DispatchQueue queue = Dispatch.createQueue();
    HashMap<String, SerializationStrategy> map = new HashMap<String, SerializationStrategy>();
    map.put("protobuf", new ProtobufSerializationStrategy());
    ServerInvokerImpl server = new ServerInvokerImpl("tcp://localhost:0", queue, map);
    server.start();
    ClientInvokerImpl client = new ClientInvokerImpl(queue, map);
    client.start();
    try {
        server.registerService("service-id", new ServerInvoker.ServiceFactory() {

            public Object get() {
                return new HelloImpl();
            }

            public void unget() {
            }
        }, HelloImpl.class.getClassLoader());
        InvocationHandler handler = client.getProxy(server.getConnectAddress(), "service-id", HelloImpl.class.getClassLoader());
        Hello hello = (Hello) Proxy.newProxyInstance(HelloImpl.class.getClassLoader(), new Class[] { Hello.class }, handler);
        char[] chars = new char[65 * 1024];
        String payload = new String(chars);
        final List<AsyncCallbackFuture<String>> futures = new ArrayList<AsyncCallbackFuture<String>>();
        for (int i = 0; i < 100; i++) {
            AsyncCallbackFuture<String> future = new AsyncCallbackFuture<String>();
            hello.hello(payload, future);
            futures.add(future);
        }
        for (Future<String> f : futures) {
            f.get(3, TimeUnit.SECONDS);
        }
    // future2.get(2, TimeUnit.SECONDS);
    // assertEquals("Hello Hiram!", future1.get(2, TimeUnit.SECONDS));
    // assertEquals("Hello Hiram!", hello.protobuf(stringValue(payload)).getValue());
    } finally {
        server.stop();
        client.stop();
    }
}
Also used : ServerInvoker(io.fabric8.dosgi.io.ServerInvoker) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) InvocationHandler(java.lang.reflect.InvocationHandler) ClientInvokerImpl(io.fabric8.dosgi.tcp.ClientInvokerImpl) ServerInvokerImpl(io.fabric8.dosgi.tcp.ServerInvokerImpl) DispatchQueue(org.fusesource.hawtdispatch.DispatchQueue) 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