Search in sources :

Example 46 with Watch

use of io.fabric8.kubernetes.client.Watch in project fabric8-maven-plugin by fabric8io.

the class SpringBootWatcher method runRemoteSpringApplication.

private void runRemoteSpringApplication(String url) {
    log.info("Running RemoteSpringApplication against endpoint: " + url);
    Properties properties = SpringBootUtil.getSpringBootApplicationProperties(getContext().getProject());
    String remoteSecret = properties.getProperty(DEV_TOOLS_REMOTE_SECRET, System.getProperty(DEV_TOOLS_REMOTE_SECRET));
    if (Strings.isNullOrBlank(remoteSecret)) {
        log.warn("There is no `%s` property defined in your src/main/resources/application.properties. Please add one!", DEV_TOOLS_REMOTE_SECRET);
        throw new IllegalStateException("No " + DEV_TOOLS_REMOTE_SECRET + " property defined in application.properties or system properties");
    }
    ClassLoader classLoader = getClass().getClassLoader();
    if (classLoader instanceof URLClassLoader) {
        URLClassLoader pluginClassLoader = (URLClassLoader) classLoader;
        URLClassLoader projectClassLoader = ClassUtil.createProjectClassLoader(getContext().getProject(), log);
        URLClassLoader[] classLoaders = { projectClassLoader, pluginClassLoader };
        StringBuilder buffer = new StringBuilder("java -cp ");
        int count = 0;
        for (URLClassLoader urlClassLoader : classLoaders) {
            URL[] urLs = urlClassLoader.getURLs();
            for (URL u : urLs) {
                if (count++ > 0) {
                    buffer.append(File.pathSeparator);
                }
                try {
                    URI uri = u.toURI();
                    File file = new File(uri);
                    buffer.append(file.getCanonicalPath());
                } catch (Exception e) {
                    throw new IllegalStateException("Failed to create classpath: " + e, e);
                }
            }
        }
        // Add dev tools to the classpath (the main class is not read from BOOT-INF/lib)
        try {
            File devtools = getSpringBootDevToolsJar(getContext().getProject());
            buffer.append(File.pathSeparator);
            buffer.append(devtools.getCanonicalPath());
        } catch (Exception e) {
            throw new IllegalStateException("Failed to include devtools in the classpath: " + e, e);
        }
        buffer.append(" -Dspring.devtools.remote.secret=");
        buffer.append(remoteSecret);
        buffer.append(" org.springframework.boot.devtools.RemoteSpringApplication ");
        buffer.append(url);
        try {
            String command = buffer.toString();
            log.debug("Running: " + command);
            final Process process = Runtime.getRuntime().exec(command);
            final AtomicBoolean outputEnabled = new AtomicBoolean(true);
            Runtime.getRuntime().addShutdownHook(new Thread("fabric8:watch [spring-boot] shutdown hook") {

                @Override
                public void run() {
                    log.info("Terminating the Spring remote client...");
                    outputEnabled.set(false);
                    process.destroy();
                }
            });
            Logger logger = new PrefixedLogger("Spring-Remote", log);
            Thread stdOutPrinter = startOutputProcessor(logger, process.getInputStream(), false, outputEnabled);
            Thread stdErrPrinter = startOutputProcessor(logger, process.getErrorStream(), true, outputEnabled);
            int status = process.waitFor();
            stdOutPrinter.join();
            stdErrPrinter.join();
            if (status != 0) {
                log.warn("Process returned status: %s", status);
            }
        } catch (Exception e) {
            throw new RuntimeException("Failed to run RemoteSpringApplication: " + e, e);
        }
    } else {
        throw new IllegalStateException("ClassLoader must be a URLClassLoader but it is: " + classLoader.getClass().getName());
    }
}
Also used : Properties(java.util.Properties) Logger(io.fabric8.maven.docker.util.Logger) PrefixedLogger(io.fabric8.maven.core.util.PrefixedLogger) URI(java.net.URI) URL(java.net.URL) IOException(java.io.IOException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) PrefixedLogger(io.fabric8.maven.core.util.PrefixedLogger) URLClassLoader(java.net.URLClassLoader) URLClassLoader(java.net.URLClassLoader) File(java.io.File)

Example 47 with Watch

use of io.fabric8.kubernetes.client.Watch in project watchdog by isdream.

the class KubernetesListener method start.

@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public void start(Object client, Configure config) throws Exception {
    // System.out.println(config.getApiVersion());
    if (ObjectUtils.isNull(client) && ObjectUtils.isNull(config)) {
        throw new Exception("Invalid paremeters");
    }
    // it may throw Exception if wrong PROPERTY_KIND values
    Object model = getModelParamtersGenerator().getKindModel(client, config.getKind());
    if (model instanceof Namespaceable || model instanceof AnyNamespaceable) {
        String namespace = config.getProperties().getOrDefault(PROPERTY_NAMESPACE, ALL_NAMESPACE);
        if (ALL_NAMESPACE.equals(namespace)) {
            model = ((AnyNamespaceable) model).inAnyNamespace();
        } else {
            model = ((Namespaceable) model).inNamespace(namespace);
        }
    }
    List<String> handlers = config.getHandlers();
    if (handlers.isEmpty()) {
        throw new Exception("No handlers");
    }
    Handler handler = (Handler) Class.forName(handlers.remove(0)).newInstance();
    Handler thisHandler = handler;
    for (String name : handlers) {
        Handler nextHandler = (Handler) Class.forName(name).newInstance();
        thisHandler.setNextHandler(nextHandler);
        thisHandler = nextHandler;
    }
    System.out.println(model.getClass());
    ((Watchable) model).watch(new KubernetesWatcher(handler));
}
Also used : Watchable(io.fabric8.kubernetes.client.dsl.Watchable) Handler(com.github.isdream.cwatcher.Handler) Namespaceable(io.fabric8.kubernetes.client.dsl.Namespaceable) AnyNamespaceable(io.fabric8.kubernetes.client.dsl.AnyNamespaceable) AnyNamespaceable(io.fabric8.kubernetes.client.dsl.AnyNamespaceable) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException)

Example 48 with Watch

use of io.fabric8.kubernetes.client.Watch in project hono by eclipse.

the class KubernetesBasedAdapterInstanceStatusServiceTest method testServiceReactivatesAfterWatchClosed.

/**
 * Verifies that when the pod watcher of the status service is closed, a new watcher gets created
 * and subsequently added pods get detected.
 *
 * @throws InterruptedException if test execution gets interrupted.
 */
@Test
public void testServiceReactivatesAfterWatchClosed() throws InterruptedException {
    // 3 events: 2x on initAdaptersListAndWatch() + 1x on WatchEvent
    final CountDownLatch eventLatch = new CountDownLatch(3);
    final Pod pod0 = createAdapterPodWithRunningContainer("testPod0");
    final String pod0ContainerId = KubernetesBasedAdapterInstanceStatusService.getShortContainerId(pod0.getStatus().getContainerStatuses().get(0).getContainerID());
    assertThat(pod0ContainerId).isNotNull();
    server.expect().withPath("/api/v1/namespaces/test/pods").andReturn(200, new PodListBuilder().addToItems(pod0).build()).times(2);
    final Pod pod1 = createAdapterPodWithRunningContainer("testPod1");
    final String pod1ContainerId = KubernetesBasedAdapterInstanceStatusService.getShortContainerId(pod1.getStatus().getContainerStatuses().get(0).getContainerID());
    assertThat(pod1ContainerId).isNotNull();
    server.expect().withPath("/api/v1/namespaces/test/pods?allowWatchBookmarks=true&watch=true").andUpgradeToWebSocket().open().waitFor(10).andEmit(outdatedEvent()).done().once();
    server.expect().withPath("/api/v1/namespaces/test/pods?allowWatchBookmarks=true&watch=true").andUpgradeToWebSocket().open().waitFor(10).andEmit(new WatchEvent(pod1, "MODIFIED")).done().once();
    statusService = new KubernetesBasedAdapterInstanceStatusService(client) {

        @Override
        protected void onAdapterContainerAdded(final String containerId) {
            LOG.debug("onAdapterContainerAdded; containerId: '{}'", containerId);
            eventLatch.countDown();
        }
    };
    assertThat(statusService).isNotNull();
    if (eventLatch.await(10, TimeUnit.SECONDS)) {
        assertThat(statusService.getActiveAdapterInstanceContainerIds().isPresent()).isTrue();
        assertThat(statusService.getActiveAdapterInstanceContainerIds().get()).containsExactly(pod0ContainerId, pod1ContainerId);
        final String adapterInstanceId0 = pod0.getMetadata().getName() + "_" + pod0ContainerId + "_1";
        assertThat(statusService.getStatus(adapterInstanceId0)).isEqualTo(AdapterInstanceStatus.ALIVE);
        final String adapterInstanceId1 = pod1.getMetadata().getName() + "_" + pod1ContainerId + "_1";
        assertThat(statusService.getStatus(adapterInstanceId1)).isEqualTo(AdapterInstanceStatus.ALIVE);
    } else {
        fail("added pod not detected");
    }
}
Also used : PodListBuilder(io.fabric8.kubernetes.api.model.PodListBuilder) Pod(io.fabric8.kubernetes.api.model.Pod) WatchEvent(io.fabric8.kubernetes.api.model.WatchEvent) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.jupiter.api.Test)

Example 49 with Watch

use of io.fabric8.kubernetes.client.Watch in project hono by eclipse.

the class KubernetesBasedAdapterInstanceStatusService method stop.

@Override
public Future<Void> stop() {
    LOG.trace("stopping status service");
    if (active.getAndSet(-1) == -1) {
        // already stopped
        return Future.succeededFuture();
    }
    final Watch w = watch;
    if (w != null) {
        w.close();
    }
    client.close();
    return Future.succeededFuture();
}
Also used : Watch(io.fabric8.kubernetes.client.Watch)

Example 50 with Watch

use of io.fabric8.kubernetes.client.Watch in project docker-maven-plugin by fabric8io.

the class WatchService method watch.

public synchronized void watch(WatchContext context, BuildService.BuildContext buildContext, List<ImageConfiguration> images) throws DockerAccessException, MojoExecutionException {
    // Important to be be a single threaded scheduler since watch jobs must run serialized
    ScheduledExecutorService executor = null;
    try {
        executor = Executors.newSingleThreadScheduledExecutor();
        for (StartOrderResolver.Resolvable resolvable : runService.getImagesConfigsInOrder(queryService, images)) {
            final ImageConfiguration imageConfig = (ImageConfiguration) resolvable;
            String imageId = queryService.getImageId(imageConfig.getName());
            String containerId = runService.lookupContainer(imageConfig.getName());
            ImageWatcher watcher = new ImageWatcher(imageConfig, context, imageId, containerId);
            long interval = watcher.getInterval();
            WatchMode watchMode = watcher.getWatchMode(imageConfig);
            log.info("Watching " + imageConfig.getName() + (watchMode != null ? " using " + watchMode.getDescription() : ""));
            ArrayList<String> tasks = new ArrayList<>();
            if (imageConfig.getBuildConfiguration() != null) {
                for (AssemblyConfiguration assemblyConfiguration : imageConfig.getBuildConfiguration().getAssemblyConfigurations()) {
                    if (watcher.isCopy()) {
                        String containerBaseDir = assemblyConfiguration.getTargetDir();
                        schedule(executor, createCopyWatchTask(watcher, assemblyConfiguration.getName(), context.getMojoParameters(), containerBaseDir), interval);
                        tasks.add("copying artifacts");
                    }
                    if (watcher.isBuild()) {
                        schedule(executor, createBuildWatchTask(watcher, assemblyConfiguration.getName(), context.getMojoParameters(), watchMode == WatchMode.both, buildContext), interval);
                        tasks.add("rebuilding");
                    }
                }
            }
            if (watcher.isRun() && watcher.getContainerId() != null) {
                schedule(executor, createRestartWatchTask(watcher), interval);
                tasks.add("restarting");
            }
            if (tasks.size() > 0) {
                log.info("%s: Watch for %s", imageConfig.getDescription(), StringUtils.join(tasks.toArray(), " and "));
            }
        }
        log.info("Waiting ...");
        if (!context.isKeepRunning()) {
            runService.addShutdownHookForStoppingContainers(context.isKeepContainer(), context.isRemoveVolumes(), context.isAutoCreateCustomNetworks());
        }
        wait();
    } catch (InterruptedException e) {
        log.warn("Interrupted");
    } finally {
        if (executor != null) {
            executor.shutdownNow();
        }
    }
}
Also used : ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) AssemblyConfiguration(io.fabric8.maven.docker.config.AssemblyConfiguration) StartOrderResolver(io.fabric8.maven.docker.util.StartOrderResolver) ImageConfiguration(io.fabric8.maven.docker.config.ImageConfiguration) WatchImageConfiguration(io.fabric8.maven.docker.config.WatchImageConfiguration) WatchMode(io.fabric8.maven.docker.config.WatchMode) ArrayList(java.util.ArrayList)

Aggregations

Watch (io.fabric8.kubernetes.client.Watch)19 Pod (io.fabric8.kubernetes.api.model.Pod)16 KubernetesClientException (io.fabric8.kubernetes.client.KubernetesClientException)16 KubernetesClient (io.fabric8.kubernetes.client.KubernetesClient)13 Watcher (io.fabric8.kubernetes.client.Watcher)11 Test (org.junit.Test)10 PodList (io.fabric8.kubernetes.api.model.PodList)9 IOException (java.io.IOException)8 MojoExecutionException (org.apache.maven.plugin.MojoExecutionException)8 ConfigMap (io.fabric8.kubernetes.api.model.ConfigMap)7 KubernetesMockServer (io.fabric8.kubernetes.client.server.mock.KubernetesMockServer)6 CountDownLatch (java.util.concurrent.CountDownLatch)6 WatchEvent (io.fabric8.kubernetes.api.model.WatchEvent)5 ImageConfiguration (io.fabric8.maven.docker.config.ImageConfiguration)5 ArrayList (java.util.ArrayList)5 Properties (java.util.Properties)5 Logger (org.slf4j.Logger)5 LoggerFactory (org.slf4j.LoggerFactory)5 PodListBuilder (io.fabric8.kubernetes.api.model.PodListBuilder)4 Service (io.fabric8.kubernetes.api.model.Service)4