Search in sources :

Example 26 with Controller

use of io.fabric8.kubernetes.api.Controller in project strimzi by strimzi.

the class ControllerTest method testOnConfigMapAdded_TopicExistsException.

/**
 * 1. controller is notified that a ConfigMap is created
 * 2. error when creating topic in kafka
 */
@Test
public void testOnConfigMapAdded_TopicExistsException(TestContext context) {
    Exception createException = new TopicExistsException("");
    configMapAdded(context, createException, null);
// TODO check a k8s event got created
// TODO what happens when we subsequently reconcile?
}
Also used : TopicExistsException(org.apache.kafka.common.errors.TopicExistsException) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException) ClusterAuthorizationException(org.apache.kafka.common.errors.ClusterAuthorizationException) TopicExistsException(org.apache.kafka.common.errors.TopicExistsException) UnknownTopicOrPartitionException(org.apache.kafka.common.errors.UnknownTopicOrPartitionException) Test(org.junit.Test)

Example 27 with Controller

use of io.fabric8.kubernetes.api.Controller in project strimzi by strimzi.

the class ControllerIT method setup.

@Before
public void setup(TestContext context) throws Exception {
    LOGGER.info("Setting up test");
    Runtime.getRuntime().addShutdownHook(kafkaHook);
    kafkaCluster = new KafkaCluster();
    kafkaCluster.addBrokers(1);
    kafkaCluster.deleteDataPriorToStartup(true);
    kafkaCluster.deleteDataUponShutdown(true);
    kafkaCluster.usingDirectory(Files.createTempDirectory("controller-integration-test").toFile());
    kafkaCluster.startup();
    kubeClient = new DefaultKubernetesClient().inNamespace(NAMESPACE);
    LOGGER.info("Using namespace {}", NAMESPACE);
    Map<String, String> m = new HashMap();
    m.put(Config.KAFKA_BOOTSTRAP_SERVERS.key, kafkaCluster.brokerList());
    m.put(Config.ZOOKEEPER_CONNECT.key, "localhost:" + zkPort(kafkaCluster));
    m.put(Config.NAMESPACE.key, NAMESPACE);
    session = new Session(kubeClient, new Config(m));
    Async async = context.async();
    vertx.deployVerticle(session, ar -> {
        if (ar.succeeded()) {
            deploymentId = ar.result();
            adminClient = session.adminClient;
            topicsConfigWatcher = session.topicConfigsWatcher;
            topicWatcher = session.topicWatcher;
            topicsWatcher = session.topicsWatcher;
            async.complete();
        } else {
            context.fail("Failed to deploy session");
        }
    });
    async.await();
    waitFor(context, () -> this.topicsWatcher.started(), timeout, "Topics watcher not started");
    waitFor(context, () -> this.topicsConfigWatcher.started(), timeout, "Topic configs watcher not started");
    waitFor(context, () -> this.topicWatcher.started(), timeout, "Topic watcher not started");
    // We can't delete events, so record the events which exist at the start of the test
    // and then waitForEvents() can ignore those
    preExistingEvents = kubeClient.events().inNamespace(NAMESPACE).withLabels(cmPredicate.labels()).list().getItems().stream().map(evt -> evt.getMetadata().getUid()).collect(Collectors.toSet());
    LOGGER.info("Finished setting up test");
}
Also used : KafkaCluster(io.debezium.kafka.KafkaCluster) HashMap(java.util.HashMap) Async(io.vertx.ext.unit.Async) DefaultKubernetesClient(io.fabric8.kubernetes.client.DefaultKubernetesClient) Before(org.junit.Before)

Example 28 with Controller

use of io.fabric8.kubernetes.api.Controller in project syndesis by syndesisio.

the class KubernetesSupport method watchLog.

/*
     * Feeds the controller of the given podName to the callback handler for processing.
     *
     * We do this instead of using the watchLog() feature of the k8s client lib because it really sucks due to:
     *  1. You can't configure the timestamps option or the sinceTime option.  Need to resume log downloads.
     *  2. It seems to need extra threads..
     *  3. It might be hiding some of the http failure conditions.
     *
     */
protected void watchLog(String podName, Consumer<InputStream> handler, String sinceTime, Executor executor) throws IOException {
    try {
        PodOperationsImpl pod = (PodOperationsImpl) client.pods().withName(podName);
        StringBuilder url = new StringBuilder().append(pod.getResourceUrl().toString()).append("/log?pretty=false&follow=true&timestamps=true");
        if (sinceTime != null) {
            url.append("&sinceTime=");
        }
        Request request = new Request.Builder().url(new URL(url.toString())).get().build();
        OkHttpClient clone = okHttpClient.newBuilder().readTimeout(0, TimeUnit.MILLISECONDS).build();
        clone.newCall(request).enqueue(new Callback() {

            @Override
            public void onFailure(Call call, IOException e) {
                LOG.info("Failure occurred getting  controller for pod: {},", podName, e);
                handler.accept(null);
            }

            @Override
            public void onResponse(final Call call, final Response response) throws IOException {
                executor.execute(() -> {
                    try {
                        if (response.code() == 200) {
                            handler.accept(response.body().byteStream());
                        } else {
                            LOG.info("Failure occurred while processing controller for pod: {}, http status: {}, details: {}", podName, response.code(), response.body().string());
                            handler.accept(null);
                        }
                    } catch (IOException e) {
                        LOG.error("Unexpected Error", e);
                    }
                });
            }
        });
    } catch (@SuppressWarnings("PMD.AvoidCatchingGenericException") RuntimeException t) {
        throw new IOException("Unexpected Error", t);
    }
}
Also used : Response(okhttp3.Response) Call(okhttp3.Call) OkHttpClient(okhttp3.OkHttpClient) Callback(okhttp3.Callback) Request(okhttp3.Request) IOException(java.io.IOException) PodOperationsImpl(io.fabric8.kubernetes.client.dsl.internal.PodOperationsImpl) URL(java.net.URL)

Example 29 with Controller

use of io.fabric8.kubernetes.api.Controller in project fabric8 by fabric8io.

the class Example method main.

public static void main(String[] args) {
    try {
        final KubernetesClient client = new DefaultKubernetesClient();
        assertThat(client).pods().runningStatus().hasSize(6);
        assertThat(client).pods().runningStatus().filterLabel("provider", "fabric8").assertSize().isGreaterThan(0);
        assertThat(client.services().inNamespace("default").withName("fabric8").get().getMetadata()).name().isEqualTo("fabric8");
        Map<String, String> consoleLabels = new HashMap<>();
        consoleLabels.put("component", "console");
        consoleLabels.put("provider", "fabric8");
        assertThat(client).podsForService("fabric8").runningStatus().extracting("metadata").extracting("labels").contains(consoleLabels);
        assertThat(client).podsForService("fabric8").runningStatus().hasSize(1).extracting("metadata").extracting("labels").contains(consoleLabels);
        assertThat(client).podsForService("fabric8").logs().doesNotContainText("Exception", "Error");
        assertThat(client).pods().logs().doesNotContainText("Exception", "Error");
        assertAssertionError(new Block() {

            @Override
            public void invoke() throws Exception {
                try {
                    assertThat(client.services().inNamespace("default").withName("doesNotExist").get().getMetadata()).name().isEqualTo("fabric8-console-controller");
                } catch (KubernetesClientException e) {
                    if (e.getCode() != 404) {
                        throw e;
                    } else {
                        throw new AssertionError(e);
                    }
                }
            }
        });
        assertAssertionError(new Block() {

            @Override
            public void invoke() throws Exception {
                try {
                    assertThat(client).pods().runningStatus().filterLabel("component", "doesNotExist").hasSize(1);
                } catch (KubernetesClientException e) {
                    if (e.getCode() != 404) {
                        throw e;
                    } else {
                        throw new AssertionError(e);
                    }
                }
            }
        });
        System.out.println("Done!");
    } catch (Throwable e) {
        System.out.println("Caught: " + e);
        e.printStackTrace();
    }
}
Also used : KubernetesClient(io.fabric8.kubernetes.client.KubernetesClient) DefaultKubernetesClient(io.fabric8.kubernetes.client.DefaultKubernetesClient) HashMap(java.util.HashMap) Asserts.assertAssertionError(io.fabric8.utils.Asserts.assertAssertionError) Block(io.fabric8.utils.Block) DefaultKubernetesClient(io.fabric8.kubernetes.client.DefaultKubernetesClient) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException)

Example 30 with Controller

use of io.fabric8.kubernetes.api.Controller in project fabric8 by fabric8io.

the class KubernetesAssert method deployments.

/**
 * Finds all the resources that create pod selections (Deployment, DeploymentConfig, ReplicaSet, ReplicationController)
 * and create a {@link HasPodSelectionAssert} to make assertions on their pods that they startup etc.
 *
 * @return the assertion object for the deployment
 */
public HasPodSelectionAssert deployments() {
    List<HasPodSelectionAssert> asserters = new ArrayList<>();
    List<HasMetadata> resources = new ArrayList<>();
    try {
        resources = KubernetesHelper.findKubernetesResourcesOnClasspath(new Controller(client));
    } catch (IOException e) {
        fail("Failed to load kubernetes resources on the classpath: " + e, e);
    }
    for (HasMetadata resource : resources) {
        HasPodSelectionAssert asserter = createPodSelectionAssert(resource);
        if (asserter != null) {
            asserters.add(asserter);
        }
    }
    String message = "No pod selection kinds found on the classpath such as Deployment, DeploymentConfig, ReplicaSet, ReplicationController";
    // TODO we don't yet support size > 1
    assertThat(asserters).describedAs(message).isNotEmpty();
    if (asserters.size() == 1) {
        return asserters.get(0);
    }
    return new MultiHasPodSelectionAssert(asserters);
}
Also used : HasMetadata(io.fabric8.kubernetes.api.model.HasMetadata) ArrayList(java.util.ArrayList) IOException(java.io.IOException) Controller(io.fabric8.kubernetes.api.Controller) ReplicationController(io.fabric8.kubernetes.api.model.ReplicationController)

Aggregations

Test (org.junit.Test)23 ReplicationController (io.fabric8.kubernetes.api.model.ReplicationController)16 Controller (io.fabric8.kubernetes.api.Controller)13 ResourceConfig (io.fabric8.maven.core.config.ResourceConfig)12 OpenShiftClient (io.fabric8.openshift.client.OpenShiftClient)12 KubernetesClient (io.fabric8.kubernetes.client.KubernetesClient)9 Deployment (io.fabric8.kubernetes.api.model.extensions.Deployment)8 DefaultKubernetesClient (io.fabric8.kubernetes.client.DefaultKubernetesClient)8 KubernetesClientException (io.fabric8.kubernetes.client.KubernetesClientException)8 Async (io.vertx.ext.unit.Async)8 ConfigMap (io.fabric8.kubernetes.api.model.ConfigMap)7 Service (io.fabric8.kubernetes.api.model.Service)6 File (java.io.File)6 IOException (java.io.IOException)6 ArrayList (java.util.ArrayList)6 HashMap (java.util.HashMap)6 HasMetadata (io.fabric8.kubernetes.api.model.HasMetadata)5 ReplicaSet (io.fabric8.kubernetes.api.model.extensions.ReplicaSet)5 DeploymentConfig (io.fabric8.openshift.api.model.DeploymentConfig)5 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)4