Search in sources :

Example 16 with Watch

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

the class WatchServicesExample method main.

public static void main(String... args) throws Exception {
    KubernetesClient client = new DefaultKubernetesClient();
    client.services().watch(new io.fabric8.kubernetes.client.Watcher<Service>() {

        @Override
        public void eventReceived(Action action, Service service) {
            System.out.println(action + ": " + service);
        }

        @Override
        public void onClose(KubernetesClientException e) {
            System.out.println("Closed: " + e);
        }
    });
    client.close();
}
Also used : KubernetesClient(io.fabric8.kubernetes.client.KubernetesClient) DefaultKubernetesClient(io.fabric8.kubernetes.client.DefaultKubernetesClient) Service(io.fabric8.kubernetes.api.model.Service) DefaultKubernetesClient(io.fabric8.kubernetes.client.DefaultKubernetesClient) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException)

Example 17 with Watch

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

the class KubernetesConfigAdminBridge method watchConfigMapList.

private void watchConfigMapList() {
    if (configWatch) {
        KubernetesClient client = kubernetesClient.get();
        if (client != null) {
            FilterWatchListDeletable<ConfigMap, ConfigMapList, Boolean, Watch, Watcher<ConfigMap>> configMapsSelector = client.configMaps().withLabel(pidLabel);
            for (String key : filters.keySet()) {
                configMapsSelector.withLabelIn(key, filters.get(key).toArray(new String[filters.get(key).size()]));
            }
            watch = configMapsSelector.watch(this);
        } else {
            throw new RuntimeException("KubernetesClient not set");
        }
    }
}
Also used : ConfigMapList(io.fabric8.kubernetes.api.model.ConfigMapList) KubernetesClient(io.fabric8.kubernetes.client.KubernetesClient) ConfigMap(io.fabric8.kubernetes.api.model.ConfigMap) Watch(io.fabric8.kubernetes.client.Watch) Watcher(io.fabric8.kubernetes.client.Watcher)

Example 18 with Watch

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

the class KubernetesConfigAdminBridgeTest method testOr.

@Test
public void testOr() {
    System.setProperty("fabric8.pid.filters", "appName=A;B");
    KubernetesMockServer plainServer = new KubernetesMockServer(false);
    plainServer.expect().get().withPath("/api/v1/namespaces/test/configmaps?labelSelector=karaf.pid,appName%20in%20(A,B)&watch=true").andReturnChunked(200).always();
    plainServer.expect().get().withPath("/api/v1/namespaces/test/configmaps?labelSelector=karaf.pid,appName%20in%20(A,B)").andReturn(200, cmEmptyList).once();
    KubernetesConfigAdminBridge kcab = new KubernetesConfigAdminBridge();
    kcab.bindConfigAdmin(caService);
    kcab.bindKubernetesClient(plainServer.createClient());
    kcab.activate();
}
Also used : KubernetesMockServer(io.fabric8.kubernetes.client.server.mock.KubernetesMockServer) Test(org.junit.Test)

Example 19 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 && imageConfig.getBuildConfiguration().getAssemblyConfiguration() != null) {
                if (watcher.isCopy()) {
                    String containerBaseDir = imageConfig.getBuildConfiguration().getAssemblyConfiguration().getTargetDir();
                    schedule(executor, createCopyWatchTask(watcher, context.getMojoParameters(), containerBaseDir), interval);
                    tasks.add("copying artifacts");
                }
                if (watcher.isBuild()) {
                    schedule(executor, createBuildWatchTask(watcher, 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) 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)

Example 20 with Watch

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

the class DummyBatchingProgressMonitor method activateInternal.

private void activateInternal() throws Exception {
    LOGGER.info("Starting up GitDataStore " + this);
    // Call the bootstrap {@link DataStoreTemplate}
    DataStoreTemplate template = runtimeProperties.get().removeRuntimeAttribute(DataStoreTemplate.class);
    if (template != null) {
        // Do the initial commit and set the root tag
        Ref rootTag = getGit().getRepository().getRef(GitHelpers.ROOT_TAG);
        if (rootTag == null) {
            getGit().commit().setMessage("First Commit").setCommitter("fabric", "user@fabric").call();
            getGit().tag().setName(GitHelpers.ROOT_TAG).setMessage("Tag the root commit").call();
        }
        LOGGER.debug("Running datastore bootstrap template: " + template);
        template.doWith(this, dataStore.get());
    }
    // Setup proxy service
    GitProxyService proxyService = gitProxyService.get();
    defaultProxySelector = ProxySelector.getDefault();
    // authenticator disabled, until properly tested it does not affect others, as Authenticator is static in the JVM
    // Authenticator.setDefault(new FabricGitLocalHostAuthenticator(proxyService));
    ProxySelector fabricProxySelector = new FabricGitLocalHostProxySelector(defaultProxySelector, proxyService);
    ProxySelector.setDefault(fabricProxySelector);
    LOGGER.debug("Setting up FabricProxySelector: {}", fabricProxySelector);
    if (gitRemoteUrl != null) {
        gitListener.runRemoteUrlChanged(gitRemoteUrl);
        remoteUrl = gitRemoteUrl;
    } else {
        gitService.get().addGitListener(gitListener);
        remoteUrl = gitService.get().getRemoteUrl();
        if (remoteUrl != null) {
            gitListener.runRemoteUrlChanged(remoteUrl);
        }
    }
    // Get initial versions
    getInitialVersions();
    // poll logic in case of remote git repo
    if (gitRemoteUrl != null) {
        // i need this old logic in case of remote repos
        LOGGER.info("Starting to pull from remote git repository every {} millis", gitRemotePollInterval);
        threadPool.scheduleWithFixedDelay(new Runnable() {

            @Override
            public void run() {
                LockHandle writeLock = aquireWriteLock();
                try {
                    LOGGER.trace("Performing timed pull");
                    doPullInternal();
                    LOGGER.debug("Performed timed pull from external git repo");
                } catch (Throwable e) {
                    LOGGER.debug("Error during performed timed pull/push due " + e.getMessage(), e);
                    LOGGER.warn("Error during performed timed pull/push due " + e.getMessage() + ". This exception is ignored.");
                } finally {
                    writeLock.unlock();
                }
            }

            @Override
            public String toString() {
                return "TimedPushTask";
            }
        }, 1000, gitRemotePollInterval, TimeUnit.MILLISECONDS);
    }
    LOGGER.info("Using ZooKeeper SharedCount to react when master git repo is changed, so we can do a git pull to the local git repo.");
    counter = new SharedCount(curator.get(), ZkPath.GIT_TRIGGER.getPath(), 0);
    counter.addListener(new SharedCountListener() {

        @Override
        public void countHasChanged(final SharedCountReader sharedCountReader, final int value) throws Exception {
            Runnable task = new Runnable() {

                @Override
                public void run() {
                    doPullInternal();
                }
            };
            if (gitRandomFetchDelay == 0) {
                LOGGER.debug("Watch counter updated to " + value + ", scheduling immediate pull");
                threadPool.submit(task);
            } else {
                int delay = RND.nextInt(gitRandomFetchDelay) + 1;
                LOGGER.debug("Watch counter updated to " + value + ", scheduling pull with random delay=" + delay + "s");
                threadPool.schedule(task, delay, TimeUnit.SECONDS);
            }
        }

        @Override
        public void stateChanged(CuratorFramework curatorFramework, ConnectionState connectionState) {
            switch(connectionState) {
                case SUSPENDED:
                case READ_ONLY:
                case LOST:
                    // do nothing
                    break;
                case CONNECTED:
                case RECONNECTED:
                    LOGGER.info("Shared Counter (Re)connected, doing a pull");
                    doPullInternal();
                    break;
            }
        }
    });
    try {
        counter.start();
    } catch (KeeperException.NotReadOnlyException ex) {
    // In read only mode the counter is not going to start.
    // If the connection is reestablished the component will reactivate.
    // We need to catch this error so that the component gets activated.
    }
    if (gitGcOnLoad) {
        LockHandle writeLock = aquireWriteLock();
        try {
            GitOperation<Void> gitop = new GitOperation<Void>() {

                public Void call(Git git, GitContext context) throws Exception {
                    long before = System.currentTimeMillis();
                    try {
                        git.gc().call();
                        LOGGER.debug("git gc took " + ((System.currentTimeMillis() - before)) + " ms.");
                    } catch (GitAPIException e) {
                        LOGGER.debug("git gc threw an exception!", e);
                    }
                    return null;
                }
            };
            executeInternal(new GitContext(), null, gitop);
        } finally {
            writeLock.unlock();
        }
    }
    // failing to activate the component
    if (readWriteLock.isWriteLockedByCurrentThread() || readWriteLock.getWriteHoldCount() == 0) {
        try {
            // let's delegate to other thread in order to free MCF thread
            // ENTESB-7843: there's a problem when jetty is configured with TLS and keystore location using
            // profile: URI. while Jetty continues to be configured if profile:jetty.xml isn't available
            // (and it isn't initially), it fails trying to access keystore via profile: URI.
            // we should optimistically assume we can pull, but there's nothing wrong if we can't
            // - we'll be able to pull later
            threadPoolInitial.execute(new Runnable() {

                @Override
                public void run() {
                    doPullInternal(5);
                }
            });
        } catch (IllegalStateException e) {
            LOGGER.info("Another thread acquired write lock and GitDataStore can't pull from remote repository.");
        }
    } else {
        LOGGER.info("Another thread is keeping git write lock. GitDataStore will continue activation.");
    }
}
Also used : SharedCount(org.apache.curator.framework.recipes.shared.SharedCount) ProxySelector(java.net.ProxySelector) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) CuratorFramework(org.apache.curator.framework.CuratorFramework) DataStoreTemplate(io.fabric8.api.DataStoreTemplate) SharedCountListener(org.apache.curator.framework.recipes.shared.SharedCountListener) GitProxyService(io.fabric8.git.GitProxyService) LockHandle(io.fabric8.api.LockHandle) SharedCountReader(org.apache.curator.framework.recipes.shared.SharedCountReader) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) IOException(java.io.IOException) FabricException(io.fabric8.api.FabricException) KeeperException(org.apache.zookeeper.KeeperException) MalformedURLException(java.net.MalformedURLException) Ref(org.eclipse.jgit.lib.Ref) Git(org.eclipse.jgit.api.Git) GitContext(io.fabric8.api.GitContext) ConnectionState(org.apache.curator.framework.state.ConnectionState) KeeperException(org.apache.zookeeper.KeeperException)

Aggregations

KubernetesClientException (io.fabric8.kubernetes.client.KubernetesClientException)13 Watch (io.fabric8.kubernetes.client.Watch)12 Pod (io.fabric8.kubernetes.api.model.Pod)10 Watcher (io.fabric8.kubernetes.client.Watcher)10 KubernetesClient (io.fabric8.kubernetes.client.KubernetesClient)8 PodList (io.fabric8.kubernetes.api.model.PodList)7 ConfigMap (io.fabric8.kubernetes.api.model.ConfigMap)6 MojoExecutionException (org.apache.maven.plugin.MojoExecutionException)6 ArrayList (java.util.ArrayList)5 Test (org.junit.Test)5 Logger (org.slf4j.Logger)5 LoggerFactory (org.slf4j.LoggerFactory)5 HasMetadata (io.fabric8.kubernetes.api.model.HasMetadata)4 Logger (io.fabric8.maven.docker.util.Logger)4 IOException (java.io.IOException)4 DoneablePod (io.fabric8.kubernetes.api.model.DoneablePod)3 MixedOperation (io.fabric8.kubernetes.client.dsl.MixedOperation)3 Build (io.fabric8.openshift.api.model.Build)3 Map (java.util.Map)3 ConfigMapList (io.fabric8.kubernetes.api.model.ConfigMapList)2