Search in sources :

Example 41 with Session

use of io.fabric8.arquillian.kubernetes.Session in project fabric8 by jboss-fuse.

the class ServiceFactoryTest method testCallbackOnDisconnectCanClose.

@Test
public void testCallbackOnDisconnectCanClose() throws Exception {
    curator.close();
    LOG.info("....");
    SocketProxy socketProxy = new SocketProxy(new URI("tcp://localhost:" + zkPort));
    final CuratorFramework proxyCurator = CuratorFrameworkFactory.builder().connectString("localhost:" + socketProxy.getUrl().getPort()).sessionTimeoutMs(5000).connectionTimeoutMs(3000).retryPolicy(new RetryNTimes(10, 1000)).build();
    proxyCurator.start();
    proxyCurator.getZookeeperClient().blockUntilConnectedOrTimedOut();
    LOG.info("curator is go: " + proxyCurator);
    final String path = "/singletons/test/threads" + System.currentTimeMillis() + "**";
    final ArrayList<Runnable> members = new ArrayList<Runnable>();
    final int nThreads = 1;
    final CountDownLatch gotDisconnectEvent = new CountDownLatch(1);
    class GroupRunnable implements Runnable, GroupListener<NodeState> {

        final int id;

        private final BlockingQueue<Integer> jobQueue = new LinkedBlockingDeque<Integer>();

        ZooKeeperGroup<NodeState> group;

        NodeState nodeState;

        public GroupRunnable(int id) {
            this.id = id;
            members.add(this);
            nodeState = new NodeState("foo" + id);
        }

        @Override
        public void run() {
            group = new ZooKeeperGroup<NodeState>(proxyCurator, path, NodeState.class);
            group.add(this);
            LOG.info("run: Added: " + this);
            try {
                while (true) {
                    switch(jobQueue.take()) {
                        case 0:
                            LOG.info("run: close: " + this);
                            try {
                                group.close();
                            } catch (IOException ignored) {
                            }
                            return;
                        case 1:
                            LOG.info("run: start: " + this);
                            group.start();
                            group.update(nodeState);
                            break;
                        case 2:
                            LOG.info("run: update: " + this);
                            nodeState.setId(nodeState.getId() + id);
                            group.update(nodeState);
                            break;
                    }
                }
            } catch (InterruptedException exit) {
            }
        }

        @Override
        public void groupEvent(Group<NodeState> group, GroupEvent event) {
            LOG.info("Got: event: " + event);
            if (event.equals(GroupEvent.DISCONNECTED)) {
                gotDisconnectEvent.countDown();
            }
        }
    }
    ;
    ExecutorService executorService = Executors.newFixedThreadPool(nThreads);
    for (int i = 0; i < nThreads; i++) {
        executorService.execute(new GroupRunnable(i));
    }
    for (Runnable r : members) {
        GroupRunnable groupRunnable = (GroupRunnable) r;
        groupRunnable.jobQueue.offer(1);
        // wait for registration
        while (groupRunnable.group == null || groupRunnable.group.getId() == null) {
            TimeUnit.MILLISECONDS.sleep(100);
        }
    }
    boolean firsStartedIsMaster = ((GroupRunnable) members.get(0)).group.isMaster();
    assertTrue("first started is master", firsStartedIsMaster);
    LOG.info("got master...");
    // lets see how long they take to notice a no responses to heart beats
    socketProxy.pause();
    // splash in an update
    for (Runnable r : members) {
        GroupRunnable groupRunnable = (GroupRunnable) r;
        groupRunnable.jobQueue.offer(2);
    }
    boolean hasMaster = true;
    while (hasMaster) {
        for (Runnable r : members) {
            GroupRunnable groupRunnable = (GroupRunnable) r;
            hasMaster &= groupRunnable.group.isMaster();
        }
        if (hasMaster) {
            LOG.info("Waiting for no master state on proxy pause");
            TimeUnit.SECONDS.sleep(1);
        }
    }
    try {
        boolean gotDisconnect = gotDisconnectEvent.await(15, TimeUnit.SECONDS);
        assertTrue("got disconnect event", gotDisconnect);
        LOG.info("do close");
        for (Runnable r : members) {
            GroupRunnable groupRunnable = (GroupRunnable) r;
            groupRunnable.jobQueue.offer(0);
        }
        executorService.shutdown();
        // at a min when the session has expired
        boolean allThreadComplete = executorService.awaitTermination(6, TimeUnit.SECONDS);
        assertTrue("all threads complete", allThreadComplete);
    } finally {
        proxyCurator.close();
        socketProxy.close();
    }
}
Also used : RetryNTimes(org.apache.curator.retry.RetryNTimes) BlockingQueue(java.util.concurrent.BlockingQueue) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) Group(io.fabric8.groups.Group) ZooKeeperGroup(io.fabric8.groups.internal.ZooKeeperGroup) NodeState(io.fabric8.groups.NodeState) GroupListener(io.fabric8.groups.GroupListener) ArrayList(java.util.ArrayList) IOException(java.io.IOException) SocketProxy(org.apache.activemq.util.SocketProxy) CountDownLatch(java.util.concurrent.CountDownLatch) URI(java.net.URI) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) CuratorFramework(org.apache.curator.framework.CuratorFramework) ExecutorService(java.util.concurrent.ExecutorService) ZooKeeperGroup(io.fabric8.groups.internal.ZooKeeperGroup) Test(org.junit.Test)

Example 42 with Session

use of io.fabric8.arquillian.kubernetes.Session in project fabric8 by jboss-fuse.

the class ServiceFactoryTest method testThreadsOnTimeout.

@Test
public void testThreadsOnTimeout() throws Exception {
    curator.close();
    SocketProxy socketProxy = new SocketProxy(new URI("tcp://localhost:" + zkPort));
    final CuratorFramework proxyCurator = CuratorFrameworkFactory.builder().connectString("localhost:" + socketProxy.getUrl().getPort()).sessionTimeoutMs(5000).connectionTimeoutMs(3000).retryPolicy(new RetryNTimes(10, 1000)).build();
    proxyCurator.start();
    proxyCurator.getZookeeperClient().blockUntilConnectedOrTimedOut();
    LOG.info("curator is go: " + proxyCurator);
    final String path = "/singletons/test/threads" + System.currentTimeMillis() + "**";
    final ArrayList<Runnable> members = new ArrayList<Runnable>();
    final int nThreads = 1;
    class GroupRunnable implements Runnable, GroupListener<NodeState> {

        final int id;

        private final BlockingQueue<Integer> jobQueue = new LinkedBlockingDeque<Integer>();

        ZooKeeperGroup<NodeState> group;

        NodeState nodeState;

        public GroupRunnable(int id) {
            this.id = id;
            members.add(this);
            nodeState = new NodeState("foo" + id);
        }

        @Override
        public void run() {
            group = new ZooKeeperGroup<NodeState>(proxyCurator, path, NodeState.class);
            group.add(this);
            LOG.info("run: Added: " + this);
            try {
                while (true) {
                    switch(jobQueue.take()) {
                        case 0:
                            LOG.info("run: close: " + this);
                            try {
                                group.close();
                            } catch (IOException ignored) {
                            }
                            return;
                        case 1:
                            LOG.info("run: start: " + this);
                            group.start();
                            group.update(nodeState);
                            break;
                        case 2:
                            LOG.info("run: update: " + this);
                            nodeState.setId(nodeState.getId() + id);
                            group.update(nodeState);
                            break;
                    }
                }
            } catch (InterruptedException exit) {
            }
        }

        @Override
        public void groupEvent(Group<NodeState> group, GroupEvent event) {
        }
    }
    ;
    ExecutorService executorService = Executors.newFixedThreadPool(nThreads);
    for (int i = 0; i < nThreads; i++) {
        executorService.execute(new GroupRunnable(i));
    }
    for (Runnable r : members) {
        GroupRunnable groupRunnable = (GroupRunnable) r;
        groupRunnable.jobQueue.offer(1);
        // wait for registration
        while (groupRunnable.group == null || groupRunnable.group.getId() == null) {
            TimeUnit.MILLISECONDS.sleep(100);
        }
    }
    boolean firsStartedIsMaster = ((GroupRunnable) members.get(0)).group.isMaster();
    assertTrue("first started is master", firsStartedIsMaster);
    LOG.info("got master...");
    // lets see how long they take to notice a no responses to heart beats
    socketProxy.pause();
    // splash in an update
    for (Runnable r : members) {
        GroupRunnable groupRunnable = (GroupRunnable) r;
        groupRunnable.jobQueue.offer(2);
    }
    boolean hasMaster = true;
    while (hasMaster) {
        for (Runnable r : members) {
            GroupRunnable groupRunnable = (GroupRunnable) r;
            hasMaster &= groupRunnable.group.isMaster();
        }
        if (hasMaster) {
            LOG.info("Waiting for no master state on proxy pause");
            TimeUnit.SECONDS.sleep(1);
        }
    }
    for (Runnable r : members) {
        GroupRunnable groupRunnable = (GroupRunnable) r;
        groupRunnable.jobQueue.offer(0);
    }
    executorService.shutdown();
    // at a min when the session has expired
    boolean allThreadComplete = executorService.awaitTermination(6, TimeUnit.SECONDS);
    proxyCurator.close();
    socketProxy.close();
    assertTrue("all threads complete", allThreadComplete);
}
Also used : RetryNTimes(org.apache.curator.retry.RetryNTimes) BlockingQueue(java.util.concurrent.BlockingQueue) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) Group(io.fabric8.groups.Group) ZooKeeperGroup(io.fabric8.groups.internal.ZooKeeperGroup) NodeState(io.fabric8.groups.NodeState) GroupListener(io.fabric8.groups.GroupListener) ArrayList(java.util.ArrayList) IOException(java.io.IOException) SocketProxy(org.apache.activemq.util.SocketProxy) URI(java.net.URI) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) CuratorFramework(org.apache.curator.framework.CuratorFramework) ExecutorService(java.util.concurrent.ExecutorService) ZooKeeperGroup(io.fabric8.groups.internal.ZooKeeperGroup) Test(org.junit.Test)

Example 43 with Session

use of io.fabric8.arquillian.kubernetes.Session in project fabric8 by jboss-fuse.

the class InstallAction method doExecute.

@Override
protected void doExecute(Service service) throws Exception {
    Patch patch = super.getPatch(patchId);
    if (patch.getPatchData().getMigratorBundle() != null) {
        System.out.println("This patch cannot be rolled back.  Are you sure you want to install?");
        while (true) {
            String response = ShellUtils.readLine(session, "[y/n]: ", false);
            if (response == null) {
                return;
            }
            response = response.trim().toLowerCase();
            if (response.equals("y") || response.equals("yes")) {
                break;
            }
            if (response.equals("n") || response.equals("no")) {
                return;
            }
        }
    }
    PatchResult result = service.install(patch, simulation, synchronous);
}
Also used : PatchResult(io.fabric8.patch.management.PatchResult) Patch(io.fabric8.patch.management.Patch)

Example 44 with Session

use of io.fabric8.arquillian.kubernetes.Session in project fabric8-maven-plugin by fabric8io.

the class ResourceMojo method lateInit.

private void lateInit() throws MojoExecutionException {
    if (goalFinder.runningWithGoal(project, session, "fabric8:watch") || goalFinder.runningWithGoal(project, session, "fabric8:watch")) {
        Properties properties = project.getProperties();
        properties.setProperty("fabric8.watch", "true");
    }
    platformMode = clusterAccess.resolvePlatformMode(mode, log);
    log.info("Running in [[B]]%s[[B]] mode", platformMode.getLabel());
    if (isOpenShiftMode()) {
        Properties properties = project.getProperties();
        if (!properties.contains(DOCKER_IMAGE_USER)) {
            String namespace = clusterAccess.getNamespace();
            log.info("Using docker image name of namespace: " + namespace);
            properties.setProperty(DOCKER_IMAGE_USER, namespace);
        }
        if (!properties.contains(PlatformMode.FABRIC8_EFFECTIVE_PLATFORM_MODE)) {
            properties.setProperty(PlatformMode.FABRIC8_EFFECTIVE_PLATFORM_MODE, platformMode.toString());
        }
    }
    openShiftConverters = new HashMap<>();
    openShiftConverters.put("ReplicaSet", new ReplicSetOpenShiftConverter());
    openShiftConverters.put("Deployment", new DeploymentOpenShiftConverter(platformMode, getOpenshiftDeployTimeoutSeconds()));
    // TODO : This converter shouldn't be here. See its javadoc.
    openShiftConverters.put("DeploymentConfig", new DeploymentConfigOpenShiftConverter(getOpenshiftDeployTimeoutSeconds()));
    openShiftConverters.put("Namespace", new NamespaceOpenShiftConverter());
    handlerHub = new HandlerHub(project);
}
Also used : NamespaceOpenShiftConverter(io.fabric8.maven.plugin.converter.NamespaceOpenShiftConverter) DeploymentConfigOpenShiftConverter(io.fabric8.maven.plugin.converter.DeploymentConfigOpenShiftConverter) DeploymentOpenShiftConverter(io.fabric8.maven.plugin.converter.DeploymentOpenShiftConverter) Properties(java.util.Properties) ReplicSetOpenShiftConverter(io.fabric8.maven.plugin.converter.ReplicSetOpenShiftConverter) HandlerHub(io.fabric8.maven.core.handler.HandlerHub)

Example 45 with Session

use of io.fabric8.arquillian.kubernetes.Session in project fabric8-maven-plugin by fabric8io.

the class DebugMojo method enableDebugging.

private boolean enableDebugging(HasMetadata entity, PodTemplateSpec template) {
    if (template != null) {
        PodSpec podSpec = template.getSpec();
        if (podSpec != null) {
            List<Container> containers = podSpec.getContainers();
            boolean enabled = false;
            for (int i = 0; i < containers.size(); i++) {
                Container container = containers.get(i);
                List<EnvVar> env = container.getEnv();
                if (env == null) {
                    env = new ArrayList<>();
                }
                remoteDebugPort = KubernetesResourceUtil.getEnvVar(env, DebugConstants.ENV_VAR_JAVA_DEBUG_PORT, DebugConstants.ENV_VAR_JAVA_DEBUG_PORT_DEFAULT);
                if (KubernetesResourceUtil.setEnvVar(env, DebugConstants.ENV_VAR_JAVA_DEBUG, "true")) {
                    container.setEnv(env);
                    enabled = true;
                }
                if (KubernetesResourceUtil.setEnvVar(env, DebugConstants.ENV_VAR_JAVA_DEBUG_SUSPEND, String.valueOf(debugSuspend))) {
                    container.setEnv(env);
                    enabled = true;
                }
                List<ContainerPort> ports = container.getPorts();
                if (ports == null) {
                    ports = new ArrayList<>();
                }
                if (KubernetesResourceUtil.addPort(ports, remoteDebugPort, "debug", log)) {
                    container.setPorts(ports);
                    enabled = true;
                }
                if (debugSuspend) {
                    // Setting a random session value to force pod restart
                    this.debugSuspendValue = String.valueOf(new Random().nextLong());
                    KubernetesResourceUtil.setEnvVar(env, DebugConstants.ENV_VAR_JAVA_DEBUG_SESSION, this.debugSuspendValue);
                    container.setEnv(env);
                    if (container.getReadinessProbe() != null) {
                        log.info("Readiness probe will be disabled on " + getKind(entity) + " " + getName(entity) + " to allow attaching a remote debugger during suspension");
                        container.setReadinessProbe(null);
                    }
                    enabled = true;
                } else {
                    if (KubernetesResourceUtil.removeEnvVar(env, DebugConstants.ENV_VAR_JAVA_DEBUG_SESSION)) {
                        container.setEnv(env);
                        enabled = true;
                    }
                }
            }
            if (enabled) {
                log.info("Enabling debug on " + getKind(entity) + " " + getName(entity));
                return true;
            }
        }
    }
    return false;
}
Also used : Container(io.fabric8.kubernetes.api.model.Container) Random(java.util.Random) PodSpec(io.fabric8.kubernetes.api.model.PodSpec) ContainerPort(io.fabric8.kubernetes.api.model.ContainerPort) EnvVar(io.fabric8.kubernetes.api.model.EnvVar)

Aggregations

IOException (java.io.IOException)14 Session (io.fabric8.arquillian.kubernetes.Session)8 FabricException (io.fabric8.api.FabricException)7 KubernetesClient (io.fabric8.kubernetes.client.KubernetesClient)7 Test (org.junit.Test)6 Session (com.jcraft.jsch.Session)5 CreateContainerMetadata (io.fabric8.api.CreateContainerMetadata)5 File (java.io.File)5 Logger (io.fabric8.arquillian.kubernetes.log.Logger)4 Pod (io.fabric8.kubernetes.api.model.Pod)4 Service (io.fabric8.kubernetes.api.model.Service)4 OpenShiftClient (io.fabric8.openshift.client.OpenShiftClient)4 ArrayList (java.util.ArrayList)4 MojoExecutionException (org.apache.maven.plugin.MojoExecutionException)4 FabricAuthenticationException (io.fabric8.api.FabricAuthenticationException)3 Util.readAsString (io.fabric8.arquillian.utils.Util.readAsString)3 ZooKeeperGroup (io.fabric8.groups.internal.ZooKeeperGroup)3 GeneratorContext (io.fabric8.maven.generator.api.GeneratorContext)3 MultiException (io.fabric8.utils.MultiException)3 HashMap (java.util.HashMap)3