Search in sources :

Example 1 with SharedInformerFactory

use of io.fabric8.kubernetes.client.informers.SharedInformerFactory in project kubernetes-client by fabric8io.

the class SharedInformerFactoryImplTest method testSharedIndexInformerForCustomResourceNoType.

@Test
void testSharedIndexInformerForCustomResourceNoType() {
    // Given
    SharedInformerFactory sharedInformerFactory = new SharedInformerFactoryImpl(mockBaseClient, executorService);
    CustomResourceDefinitionContext context = new CustomResourceDefinitionContext.Builder().withKind("Dummy").withScope("Namespaced").withVersion("v1").withGroup("demos.fabric8.io").withPlural("dummies").build();
    // When
    SharedIndexInformer<GenericKubernetesResource> informer = sharedInformerFactory.inNamespace("ns1").sharedIndexInformerForCustomResource(context, 10 * 1000L);
    // Then
    assertThat(informer).isNotNull();
}
Also used : CustomResourceDefinitionContext(io.fabric8.kubernetes.client.dsl.base.CustomResourceDefinitionContext) SharedInformerFactoryImpl(io.fabric8.kubernetes.client.informers.impl.SharedInformerFactoryImpl) GenericKubernetesResource(io.fabric8.kubernetes.api.model.GenericKubernetesResource) Test(org.junit.jupiter.api.Test)

Example 2 with SharedInformerFactory

use of io.fabric8.kubernetes.client.informers.SharedInformerFactory in project kubernetes-client by fabric8io.

the class SharedInformerExample method main.

public static void main(String[] args) throws InterruptedException {
    try (final KubernetesClient client = new KubernetesClientBuilder().build()) {
        SharedInformerFactory sharedInformerFactory = client.informers();
        SharedIndexInformer<Pod> podInformer = sharedInformerFactory.sharedIndexInformerFor(Pod.class, 30 * 1000L);
        logger.info("Informer factory initialized.");
        podInformer.addEventHandler(new ResourceEventHandler<Pod>() {

            @Override
            public void onAdd(Pod pod) {
                logger.info("{} pod added", pod.getMetadata().getName());
            }

            @Override
            public void onUpdate(Pod oldPod, Pod newPod) {
                logger.info("{} pod updated", oldPod.getMetadata().getName());
            }

            @Override
            public void onDelete(Pod pod, boolean deletedFinalStateUnknown) {
                logger.info("{} pod deleted", pod.getMetadata().getName());
            }
        });
        logger.info("Starting all registered informers");
        sharedInformerFactory.startAllRegisteredInformers();
        Pod testPod = new PodBuilder().withNewMetadata().withName(POD_NAME).withLabels(Collections.singletonMap("app", POD_NAME)).endMetadata().withNewSpec().addNewContainer().withName("myapp-container").withImage("busybox:1.28").withCommand("sh", "-c", "echo The app is running!; sleep 10").endContainer().addNewInitContainer().withName("init-myservice").withImage("busybox:1.28").withCommand("sh", "-c", "echo inititalizing...; sleep 5").endInitContainer().endSpec().build();
        client.pods().inNamespace("default").create(testPod);
        logger.info("Pod created");
        Thread.sleep(3000L);
        Lister<Pod> podLister = new Lister<>(podInformer.getIndexer(), "default");
        Pod myPod = podLister.get(POD_NAME);
        logger.info("PodLister has {}", podLister.list().size());
        if (myPod != null) {
            logger.info("***** myapp-pod created {}", myPod.getMetadata().getCreationTimestamp());
        }
        // Wait for some time now
        TimeUnit.MINUTES.sleep(3);
        sharedInformerFactory.stopAllRegisteredInformers();
    }
}
Also used : KubernetesClient(io.fabric8.kubernetes.client.KubernetesClient) SharedInformerFactory(io.fabric8.kubernetes.client.informers.SharedInformerFactory) Pod(io.fabric8.kubernetes.api.model.Pod) KubernetesClientBuilder(io.fabric8.kubernetes.client.KubernetesClientBuilder) Lister(io.fabric8.kubernetes.client.informers.cache.Lister) PodBuilder(io.fabric8.kubernetes.api.model.PodBuilder)

Example 3 with SharedInformerFactory

use of io.fabric8.kubernetes.client.informers.SharedInformerFactory in project kubernetes-client by fabric8io.

the class CustomResourceInformerExample method main.

public static void main(String[] args) {
    try (KubernetesClient client = new KubernetesClientBuilder().build()) {
        SharedInformerFactory sharedInformerFactory = client.informers();
        SharedIndexInformer<Dummy> podInformer = sharedInformerFactory.sharedIndexInformerForCustomResource(Dummy.class, 60 * 1000L);
        logger.info("Informer factory initialized.");
        podInformer.addEventHandler(new ResourceEventHandler<Dummy>() {

            @Override
            public void onAdd(Dummy pod) {
                logger.info("{} dummy added", pod.getMetadata().getName());
            }

            @Override
            public void onUpdate(Dummy oldPod, Dummy newPod) {
                logger.info("{} dummy updated", oldPod.getMetadata().getName());
            }

            @Override
            public void onDelete(Dummy pod, boolean deletedFinalStateUnknown) {
                logger.info("{} dummy deleted", pod.getMetadata().getName());
            }
        });
        sharedInformerFactory.addSharedInformerEventListener(ex -> logger.error("Exception occurred, but caught: {}", ex.getMessage()));
        logger.info("Starting all registered informers");
        sharedInformerFactory.startAllRegisteredInformers();
        Executors.newSingleThreadExecutor().submit(() -> {
            Thread.currentThread().setName("HAS_SYNCED_THREAD");
            try {
                for (; ; ) {
                    logger.info("podInformer.hasSynced() : {}", podInformer.hasSynced());
                    Thread.sleep(10 * 1000L);
                }
            } catch (InterruptedException inEx) {
                Thread.currentThread().interrupt();
                logger.warn("HAS_SYNCED_THREAD interrupted: {}", inEx.getMessage());
            }
        });
        final Dummy toCreate = new Dummy();
        toCreate.getMetadata().setName("dummy");
        if (client.getConfiguration().getNamespace() != null) {
            toCreate.getMetadata().setNamespace(client.getConfiguration().getNamespace());
        } else if (client.getNamespace() != null) {
            toCreate.getMetadata().setNamespace(client.getNamespace());
        } else {
            toCreate.getMetadata().setNamespace(client.namespaces().list().getItems().stream().findFirst().map(HasMetadata::getMetadata).map(ObjectMeta::getNamespace).orElse("default"));
        }
        client.customResources(Dummy.class).createOrReplace(toCreate);
        // Wait for some time now
        TimeUnit.MINUTES.sleep(5);
    } catch (InterruptedException interruptedException) {
        Thread.currentThread().interrupt();
        logger.warn("interrupted: {}", interruptedException.getMessage());
    }
}
Also used : KubernetesClient(io.fabric8.kubernetes.client.KubernetesClient) HasMetadata(io.fabric8.kubernetes.api.model.HasMetadata) SharedInformerFactory(io.fabric8.kubernetes.client.informers.SharedInformerFactory) KubernetesClientBuilder(io.fabric8.kubernetes.client.KubernetesClientBuilder) Dummy(io.fabric8.kubernetes.examples.crds.Dummy)

Example 4 with SharedInformerFactory

use of io.fabric8.kubernetes.client.informers.SharedInformerFactory in project kubernetes-client by fabric8io.

the class DefaultSharedIndexInformerIT method testPodSharedIndexInformerGetsEvents.

@Test
public void testPodSharedIndexInformerGetsEvents() throws InterruptedException {
    // Given
    CountDownLatch addEvents = new CountDownLatch(1);
    CountDownLatch updateEvents = new CountDownLatch(0);
    SharedInformerFactory informerFactory = client.informers();
    SharedIndexInformer<Pod> podInformer = informerFactory.sharedIndexInformerFor(Pod.class, RESYNC_PERIOD);
    podInformer.addEventHandler(new TestResourceEventHandler<>(addEvents, updateEvents));
    // When
    informerFactory.startAllRegisteredInformers();
    addEvents.await(2 * RESYNC_PERIOD, TimeUnit.MILLISECONDS);
    // Then
    assertThat(addEvents.getCount()).isZero();
    informerFactory.stopAllRegisteredInformers();
}
Also used : SharedInformerFactory(io.fabric8.kubernetes.client.informers.SharedInformerFactory) Pod(io.fabric8.kubernetes.api.model.Pod) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.Test)

Example 5 with SharedInformerFactory

use of io.fabric8.kubernetes.client.informers.SharedInformerFactory in project integ-examples by fvaleri.

the class CakeOperator method main.

public static void main(String[] args) {
    try (KubernetesClient client = new DefaultKubernetesClient()) {
        String namespace = client.getNamespace();
        if (namespace == null) {
            LOG.warn("No namespace found via config, assuming default");
            namespace = "default";
        }
        LOG.info("Using namespace {}", namespace);
        OperationContext namespaced = new OperationContext().withNamespace(namespace);
        // an infomer creates a watcher for a specific resource type and caches related events
        // you can subscribe to these events by registering a resource event handler
        SharedInformerFactory informerFactory = client.informers();
        SharedIndexInformer<Pod> podSharedIndexInformer = informerFactory.sharedIndexInformerFor(Pod.class, namespaced, RESYNC_PERIOD_MS);
        SharedIndexInformer<Cake> cakeSharedIndexInformer = informerFactory.sharedIndexInformerForCustomResource(Cake.class, namespaced, RESYNC_PERIOD_MS);
        LOG.debug("Informer factories initialized");
        MixedOperation<Cake, CakeList, Resource<Cake>> cakeClient = client.customResources(Cake.class, CakeList.class);
        CakeController cakeController = new CakeController(client, cakeClient, podSharedIndexInformer, cakeSharedIndexInformer, namespace);
        LOG.debug("Controller initialized");
        cakeController.create();
        informerFactory.startAllRegisteredInformers();
        informerFactory.addSharedInformerEventListener(e -> LOG.error("Exception occurred", e));
        cakeController.run();
    } catch (KubernetesClientException e) {
        LOG.error("Kubernetes client exception: {}", e.getMessage());
    }
}
Also used : OperationContext(io.fabric8.kubernetes.client.dsl.base.OperationContext) KubernetesClient(io.fabric8.kubernetes.client.KubernetesClient) DefaultKubernetesClient(io.fabric8.kubernetes.client.DefaultKubernetesClient) CakeList(it.fvaleri.integ.model.v1alpha1.CakeList) Pod(io.fabric8.kubernetes.api.model.Pod) Cake(it.fvaleri.integ.model.v1alpha1.Cake) Resource(io.fabric8.kubernetes.client.dsl.Resource) CakeController(it.fvaleri.integ.controller.CakeController) SharedInformerFactory(io.fabric8.kubernetes.client.informers.SharedInformerFactory) DefaultKubernetesClient(io.fabric8.kubernetes.client.DefaultKubernetesClient) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException)

Aggregations

SharedInformerFactory (io.fabric8.kubernetes.client.informers.SharedInformerFactory)8 Pod (io.fabric8.kubernetes.api.model.Pod)5 KubernetesClient (io.fabric8.kubernetes.client.KubernetesClient)4 PodBuilder (io.fabric8.kubernetes.api.model.PodBuilder)3 KubernetesClientBuilder (io.fabric8.kubernetes.client.KubernetesClientBuilder)3 Test (org.junit.jupiter.api.Test)3 GenericKubernetesResource (io.fabric8.kubernetes.api.model.GenericKubernetesResource)2 Resource (io.fabric8.kubernetes.client.dsl.Resource)2 CustomResourceDefinitionContext (io.fabric8.kubernetes.client.dsl.base.CustomResourceDefinitionContext)2 Cake (it.fvaleri.integ.model.v1alpha1.Cake)2 CakeList (it.fvaleri.integ.model.v1alpha1.CakeList)2 HasMetadata (io.fabric8.kubernetes.api.model.HasMetadata)1 DefaultKubernetesClient (io.fabric8.kubernetes.client.DefaultKubernetesClient)1 KubernetesClientException (io.fabric8.kubernetes.client.KubernetesClientException)1 OperationContext (io.fabric8.kubernetes.client.dsl.base.OperationContext)1 Lister (io.fabric8.kubernetes.client.informers.cache.Lister)1 SharedInformerFactoryImpl (io.fabric8.kubernetes.client.informers.impl.SharedInformerFactoryImpl)1 Dummy (io.fabric8.kubernetes.examples.crds.Dummy)1 CakeController (it.fvaleri.integ.controller.CakeController)1 CountDownLatch (java.util.concurrent.CountDownLatch)1