Search in sources :

Example 46 with Event

use of io.fabric8.kubernetes.api.model.Event in project fabric8-maven-plugin by fabric8io.

the class PodLogService method waitAndLogPods.

private void waitAndLogPods(final KubernetesClient kubernetes, final String namespace, LabelSelector selector, final boolean watchAddedPodsOnly, final String ctrlCMessage, final boolean followLog, Date ignorePodsOlderThan, boolean waitInCurrentThread) {
    FilterWatchListDeletable<Pod, PodList, Boolean, Watch, Watcher<Pod>> pods = withSelector(kubernetes.pods().inNamespace(namespace), selector, log);
    if (context.getPodName() != null) {
        log.info("Watching pod with selector %s, and name %s waiting for a running pod...", selector, context.getPodName());
        pods = pods.withField("metadata.name", context.getPodName());
    } else {
        log.info("Watching pods with selector %s waiting for a running pod...", selector);
    }
    Pod latestPod = null;
    boolean runningPod = false;
    PodList list = pods.list();
    if (list != null) {
        List<Pod> items = list.getItems();
        if (items != null) {
            for (Pod pod : items) {
                PodStatusType status = getPodStatus(pod);
                switch(status) {
                    case WAIT:
                    case OK:
                        if (latestPod == null || KubernetesResourceUtil.isNewerResource(pod, latestPod)) {
                            if (ignorePodsOlderThan != null) {
                                Date podCreateTime = KubernetesResourceUtil.getCreationTimestamp(pod);
                                if (podCreateTime != null && podCreateTime.compareTo(ignorePodsOlderThan) > 0) {
                                    latestPod = pod;
                                }
                            } else {
                                latestPod = pod;
                            }
                        }
                        runningPod = true;
                        break;
                    case ERROR:
                    default:
                        continue;
                }
            }
        }
    }
    // we may have missed the ADDED event so lets simulate one
    if (latestPod != null) {
        onPod(Watcher.Action.ADDED, latestPod, kubernetes, namespace, ctrlCMessage, followLog);
    }
    if (!watchAddedPodsOnly) {
        // lets watch the current pods then watch for changes
        if (!runningPod) {
            log.warn("No pod is running yet. Are you sure you deployed your app via `fabric8:deploy`?");
            log.warn("Or did you stop it via `fabric8:stop`? If so try running the `fabric8:start` goal");
        }
    }
    podWatcher = pods.watch(new Watcher<Pod>() {

        @Override
        public void eventReceived(Action action, Pod pod) {
            onPod(action, pod, kubernetes, namespace, ctrlCMessage, followLog);
        }

        @Override
        public void onClose(KubernetesClientException e) {
        // ignore
        }
    });
    if (waitInCurrentThread) {
        while (terminateLatch.getCount() > 0) {
            try {
                terminateLatch.await();
            } catch (InterruptedException e) {
            // ignore
            }
        }
    }
}
Also used : PodList(io.fabric8.kubernetes.api.model.PodList) DoneablePod(io.fabric8.kubernetes.api.model.DoneablePod) Pod(io.fabric8.kubernetes.api.model.Pod) Watcher(io.fabric8.kubernetes.client.Watcher) Date(java.util.Date) Watch(io.fabric8.kubernetes.client.Watch) LogWatch(io.fabric8.kubernetes.client.dsl.LogWatch) PodStatusType(io.fabric8.kubernetes.api.PodStatusType) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException)

Example 47 with Event

use of io.fabric8.kubernetes.api.model.Event in project kubernetes by ballerinax.

the class DockerHandler method buildImage.

/**
 * Create docker image.
 *
 * @param dockerModel dockerModel object
 * @param dockerDir   dockerfile directory
 * @throws InterruptedException When error with docker build process
 * @throws IOException          When error with docker build process
 */
public void buildImage(DockerModel dockerModel, String dockerDir) throws InterruptedException, IOException, KubernetesPluginException {
    Config dockerClientConfig = new ConfigBuilder().withDockerUrl(dockerModel.getDockerHost()).build();
    DockerClient client = new io.fabric8.docker.client.DefaultDockerClient(dockerClientConfig);
    final DockerError dockerError = new DockerError();
    OutputHandle buildHandle = client.image().build().withRepositoryName(dockerModel.getName()).withNoCache().alwaysRemovingIntermediate().usingListener(new EventListener() {

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

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

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

        @Override
        public void onEvent(String event) {
            printDebug(event);
        }
    }).fromFolder(dockerDir);
    buildDone.await();
    buildHandle.close();
    client.close();
    handleError(dockerError);
}
Also used : 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) EventListener(io.fabric8.docker.dsl.EventListener)

Example 48 with Event

use of io.fabric8.kubernetes.api.model.Event in project fabric8 by fabric8io.

the class SessionListener method start.

public void start(@Observes final Start event, KubernetesClient client, Controller controller, Configuration configuration) throws Exception {
    Objects.requireNonNull(client, "KubernetesClient most not be null!");
    Session session = event.getSession();
    final Logger log = session.getLogger();
    String namespace = session.getNamespace();
    System.setProperty(Constants.KUBERNETES_NAMESPACE, namespace);
    log.status("Using Kubernetes at: " + client.getMasterUrl());
    log.status("Creating kubernetes resources inside namespace: " + namespace);
    log.info("if you use OpenShift then type this switch namespaces:     oc project " + namespace);
    log.info("if you use kubernetes then type this to switch namespaces: kubectl namespace " + namespace);
    clearTestResultDirectories(session);
    controller.setNamespace(namespace);
    controller.setThrowExceptionOnError(true);
    controller.setRecreateMode(true);
    controller.setIgnoreRunningOAuthClients(true);
    if (configuration.isCreateNamespaceForTest()) {
        createNamespace(client, controller, session);
    } else {
        String namespaceToUse = configuration.getNamespace();
        checkNamespace(client, controller, session, configuration);
        updateConfigMapStatus(client, session, Constants.RUNNING_STATUS);
        namespace = namespaceToUse;
        controller.setNamespace(namespace);
    }
    List<KubernetesList> kubeConfigs = new LinkedList<>();
    shutdownHook = new ShutdownHook(client, controller, configuration, session, kubeConfigs);
    Runtime.getRuntime().addShutdownHook(shutdownHook);
    try {
        URL configUrl = configuration.getEnvironmentConfigUrl();
        List<String> dependencies = !configuration.getEnvironmentDependencies().isEmpty() ? configuration.getEnvironmentDependencies() : resolver.resolve(session);
        if (configuration.isEnvironmentInitEnabled()) {
            for (String dependency : dependencies) {
                log.info("Found dependency: " + dependency);
                loadDependency(log, kubeConfigs, dependency, controller, configuration, namespace);
            }
            OpenShiftClient openShiftClient = controller.getOpenShiftClientOrNull();
            if (configUrl == null) {
                // lets try find the default configuration generated by the new fabric8-maven-plugin
                String resourceName = "kubernetes.yml";
                if (openShiftClient != null && openShiftClient.supportsOpenShiftAPIGroup(OpenShiftAPIGroups.IMAGE) && openShiftClient.supportsOpenShiftAPIGroup(OpenShiftAPIGroups.ROUTE)) {
                    resourceName = "openshift.yml";
                }
                configUrl = findConfigResource("/META-INF/fabric8/" + resourceName);
            }
            if (configUrl != null) {
                log.status("Applying kubernetes configuration from: " + configUrl);
                String configText = readAsString(configUrl);
                Object dto = null;
                String configPath = configUrl.getPath();
                if (configPath.endsWith(".yml") || configPath.endsWith(".yaml")) {
                    dto = loadYaml(configText, KubernetesResource.class);
                } else {
                    dto = loadJson(configText);
                }
                dto = expandTemplate(controller, configuration, log, namespace, configUrl.toString(), dto);
                KubernetesList kubeList = KubernetesHelper.asKubernetesList(dto);
                List<HasMetadata> items = kubeList.getItems();
                kubeConfigs.add(kubeList);
            }
            // Lets also try to load the image stream for the project.
            if (openShiftClient != null && openShiftClient.supportsOpenShiftAPIGroup(OpenShiftAPIGroups.IMAGE)) {
                File targetDir = new File(System.getProperty("basedir", ".") + "/target");
                if (targetDir.exists() && targetDir.isDirectory()) {
                    File[] files = targetDir.listFiles();
                    if (files != null) {
                        for (File file : files) {
                            if (file.getName().endsWith("-is.yml")) {
                                loadDependency(log, kubeConfigs, file.toURI().toURL().toString(), controller, configuration, namespace);
                            }
                        }
                    }
                }
            // 
            }
        }
        if (!configuration.isEnvironmentInitEnabled() || applyConfiguration(client, controller, configuration, session, kubeConfigs)) {
            displaySessionStatus(client, session);
        } else {
            throw new IllegalStateException("Failed to apply kubernetes configuration.");
        }
    } catch (Exception e) {
        try {
            cleanupSession(client, controller, configuration, session, kubeConfigs, Constants.ERROR_STATUS);
        } catch (MultiException me) {
            throw e;
        } finally {
            if (shutdownHook != null) {
                Runtime.getRuntime().removeShutdownHook(shutdownHook);
            }
        }
        throw new RuntimeException(e);
    }
}
Also used : Util.readAsString(io.fabric8.arquillian.utils.Util.readAsString) Logger(io.fabric8.arquillian.kubernetes.log.Logger) URL(java.net.URL) MultiException(io.fabric8.utils.MultiException) InvocationTargetException(java.lang.reflect.InvocationTargetException) IOException(java.io.IOException) OpenShiftClient(io.fabric8.openshift.client.OpenShiftClient) File(java.io.File) MultiException(io.fabric8.utils.MultiException) Util.cleanupSession(io.fabric8.arquillian.utils.Util.cleanupSession)

Example 49 with Event

use of io.fabric8.kubernetes.api.model.Event in project fabric8 by fabric8io.

the class SessionListener method stop.

public void stop(@Observes Stop event, KubernetesClient client, Controller controller, Configuration configuration, List<KubernetesList> kubeConfigs) throws Exception {
    try {
        Session session = event.getSession();
        cleanupSession(client, controller, configuration, session, kubeConfigs, Util.getSessionStatus(session));
    } finally {
        if (shutdownHook != null) {
            Runtime.getRuntime().removeShutdownHook(shutdownHook);
        }
    }
}
Also used : Util.cleanupSession(io.fabric8.arquillian.utils.Util.cleanupSession)

Example 50 with Event

use of io.fabric8.kubernetes.api.model.Event in project fabric8 by fabric8io.

the class WatchBuilds method main.

public static void main(String... args) {
    String namespace = null;
    if (args.length > 0) {
        namespace = args[0];
    }
    String consoleLink = Links.getFabric8ConsoleLink();
    OpenShiftClient client = new DefaultOpenShiftClient();
    BuildListener buildListener = new BuildListener() {

        @Override
        public void onBuildFinished(BuildFinishedEvent event) {
            System.out.println("Build: " + event.getUid() + " for config: " + event.getConfigName() + " finished. Status: " + event.getStatus() + " link: " + event.getBuildLink());
        }
    };
    BuildWatcher watcher = new BuildWatcher(client, buildListener, namespace, consoleLink);
    long pollTime = 3000;
    watcher.schedule(pollTime);
    watcher.join();
}
Also used : BuildListener(io.fabric8.kubernetes.api.builds.BuildListener) BuildWatcher(io.fabric8.kubernetes.api.builds.BuildWatcher) DefaultOpenShiftClient(io.fabric8.openshift.client.DefaultOpenShiftClient) OpenShiftClient(io.fabric8.openshift.client.OpenShiftClient) BuildFinishedEvent(io.fabric8.kubernetes.api.builds.BuildFinishedEvent) DefaultOpenShiftClient(io.fabric8.openshift.client.DefaultOpenShiftClient)

Aggregations

Test (org.junit.Test)14 IOException (java.io.IOException)11 ConfigMap (io.fabric8.kubernetes.api.model.ConfigMap)8 ArrayList (java.util.ArrayList)6 ConnectionParameters (io.fabric8.gateway.handlers.loadbalancer.ConnectionParameters)5 File (java.io.File)5 Map (java.util.Map)5 CuratorFramework (org.apache.curator.framework.CuratorFramework)5 Logger (org.slf4j.Logger)5 CountDownLatch (java.util.concurrent.CountDownLatch)4 LoggerFactory (org.slf4j.LoggerFactory)4 ServiceDTO (io.fabric8.gateway.ServiceDTO)3 FutureHandler (io.fabric8.gateway.handlers.detecting.FutureHandler)3 HttpGatewayHandler (io.fabric8.gateway.handlers.http.HttpGatewayHandler)3 LogEvent (io.fabric8.insight.log.LogEvent)3 KubernetesClientException (io.fabric8.kubernetes.client.KubernetesClientException)3 URI (java.net.URI)3 URISyntaxException (java.net.URISyntaxException)3 HashMap (java.util.HashMap)3 ChildData (org.apache.curator.framework.recipes.cache.ChildData)3