Search in sources :

Example 1 with GenericKubernetesResourceList

use of io.fabric8.kubernetes.api.model.GenericKubernetesResourceList in project kubernetes-client by fabric8io.

the class CustomResourceTest method testListWithLabels.

@Test
void testListWithLabels() {
    String jsonObject = "{\"metadata\":{\"continue\":\"\",\"resourceVersion\":\"539617\",\"selfLink\":\"test.fabric8.io/v1alpha1/namespaces/ns1/hellos/\"},\"apiVersion\":\"test.fabric8.io/v1alpha1\",\"kind\":\"HelloList\",\"items\":[{\"apiVersion\": \"test.fabric8.io/v1alpha1\",\"kind\": \"Hello\"," + "\"metadata\": {\"name\": \"example-hello\", \"labels\": {\"scope\":\"test\"}},\"spec\": {\"size\": 3},\"uid\":\"3525437a-6a56-11e9-8787-525400b18c1d\"}]}";
    server.expect().get().withPath("/apis/test.fabric8.io/v1alpha1/namespaces/ns1/hellos?labelSelector=org%3Dfabric8" + Utils.toUrlEncoded(",") + "scope%3Dtest").andReturn(HttpURLConnection.HTTP_CREATED, jsonObject).once();
    Map<String, String> labels = new HashMap<>();
    labels.put("org", "fabric8");
    labels.put("scope", "test");
    GenericKubernetesResourceList list = client.genericKubernetesResources(customResourceDefinitionContext).inNamespace("ns1").withLabels(labels).list();
    List<GenericKubernetesResource> items = list.getItems();
    assertNotNull(items);
    assertEquals(1, items.size());
}
Also used : HashMap(java.util.HashMap) GenericKubernetesResourceList(io.fabric8.kubernetes.api.model.GenericKubernetesResourceList) GenericKubernetesResource(io.fabric8.kubernetes.api.model.GenericKubernetesResource) Test(org.junit.jupiter.api.Test)

Example 2 with GenericKubernetesResourceList

use of io.fabric8.kubernetes.api.model.GenericKubernetesResourceList in project kubernetes-client by fabric8io.

the class GenericKubernetesResourceExample method main.

public static void main(String[] args) throws Exception {
    final ConfigBuilder configBuilder = new ConfigBuilder();
    configBuilder.withWatchReconnectInterval(500);
    configBuilder.withWatchReconnectLimit(5);
    try (KubernetesClient client = new KubernetesClientBuilder().withConfig(configBuilder.build()).build()) {
        String namespace = "default";
        CustomResourceDefinition prometheousRuleCrd = client.apiextensions().v1beta1().customResourceDefinitions().load(GenericKubernetesResourceExample.class.getResourceAsStream("/prometheous-rule-crd.yml")).get();
        client.apiextensions().v1beta1().customResourceDefinitions().createOrReplace(prometheousRuleCrd);
        logger.info("Successfully created Prometheous custom resource definition");
        // Creating Custom Resources Now:
        ResourceDefinitionContext crdContext = CustomResourceDefinitionContext.fromCrd(prometheousRuleCrd);
        client.load(GenericKubernetesResourceExample.class.getResourceAsStream("/prometheous-rule-cr.yml")).inNamespace(namespace).createOrReplace();
        logger.info("Created Custom Resource successfully too");
        // Listing all custom resources in given namespace:
        NonNamespaceOperation<GenericKubernetesResource, GenericKubernetesResourceList, Resource<GenericKubernetesResource>> resourcesInNamespace = client.genericKubernetesResources(crdContext).inNamespace(namespace);
        GenericKubernetesResourceList list = resourcesInNamespace.list();
        List<GenericKubernetesResource> items = list.getItems();
        logger.info("Custom Resources :- ");
        for (GenericKubernetesResource customResource : items) {
            ObjectMeta metadata = customResource.getMetadata();
            final String name = metadata.getName();
            logger.info(name);
        }
        // Watching custom resources now
        logger.info("Watching custom resources now");
        final CountDownLatch closeLatch = new CountDownLatch(1);
        resourcesInNamespace.watch(new Watcher<GenericKubernetesResource>() {

            @Override
            public void eventReceived(Action action, GenericKubernetesResource resource) {
                logger.info("{}: {}", action, resource);
            }

            @Override
            public void onClose(WatcherException e) {
                logger.debug("Watcher onClose");
                closeLatch.countDown();
                if (e != null) {
                    logger.error(e.getMessage(), e);
                }
            }
        });
        closeLatch.await(10, TimeUnit.MINUTES);
        // Cleanup
        logger.info("Deleting custom resources...");
        resourcesInNamespace.withName("prometheus-example-rules").delete();
        client.apiextensions().v1beta1().customResourceDefinitions().withName(prometheousRuleCrd.getMetadata().getName()).delete();
    } catch (KubernetesClientException e) {
        logger.error("Could not create resource: {}", e.getMessage(), e);
    }
}
Also used : ObjectMeta(io.fabric8.kubernetes.api.model.ObjectMeta) KubernetesClient(io.fabric8.kubernetes.client.KubernetesClient) CustomResourceDefinition(io.fabric8.kubernetes.api.model.apiextensions.v1beta1.CustomResourceDefinition) GenericKubernetesResource(io.fabric8.kubernetes.api.model.GenericKubernetesResource) Resource(io.fabric8.kubernetes.client.dsl.Resource) CountDownLatch(java.util.concurrent.CountDownLatch) GenericKubernetesResource(io.fabric8.kubernetes.api.model.GenericKubernetesResource) WatcherException(io.fabric8.kubernetes.client.WatcherException) CustomResourceDefinitionContext(io.fabric8.kubernetes.client.dsl.base.CustomResourceDefinitionContext) ResourceDefinitionContext(io.fabric8.kubernetes.client.dsl.base.ResourceDefinitionContext) KubernetesClientBuilder(io.fabric8.kubernetes.client.KubernetesClientBuilder) GenericKubernetesResourceList(io.fabric8.kubernetes.api.model.GenericKubernetesResourceList) ConfigBuilder(io.fabric8.kubernetes.client.ConfigBuilder) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException)

Example 3 with GenericKubernetesResourceList

use of io.fabric8.kubernetes.api.model.GenericKubernetesResourceList in project kubernetes-client by fabric8io.

the class GenericCustomResourceIT method testCrud.

@Test
public void testCrud() throws IOException {
    // Test Create via file
    GenericKubernetesResource object = resourceClient.load(getClass().getResourceAsStream("/test-rawcustomresource.yml")).create();
    assertThat(object.getMetadata().getName()).isEqualTo("otter");
    // Test Create via raw json string
    String rawJsonCustomResourceObj = "{\"apiVersion\":\"jungle.example.com/v1\"," + "\"kind\":\"Animal\",\"metadata\": {\"name\": \"walrus\"}," + "\"spec\": {\"image\": \"my-awesome-walrus-image\"}}";
    object = resourceClient.createOrReplace(Serialization.unmarshal(rawJsonCustomResourceObj, GenericKubernetesResource.class));
    assertAnimal(object, "walrus", "my-awesome-walrus-image");
    // Test replace with object
    ((HashMap<String, String>) object.get("spec")).put("image", "new-walrus-image");
    object = resourceClient.createOrReplace(object);
    assertAnimal(object, "walrus", "new-walrus-image");
    // Test Get:
    object = resourceClient.withName("otter").get();
    assertThat(object.getMetadata().getName()).isEqualTo("otter");
    // Test List:
    GenericKubernetesResourceList list = resourceClient.list();
    assertThat(list.getItems().size()).isGreaterThanOrEqualTo(2);
    // List with labels:
    list = resourceClient.withLabel("foo", "bar").list();
    assertThat(list.getItems().size()).isGreaterThanOrEqualTo(1);
    // Test Update
    GenericKubernetesResource updated = resourceClient.withName("walrus").get();
    ((HashMap<String, Object>) updated.get("spec")).put("image", "my-updated-awesome-walrus-image");
    object = resourceClient.withName("walrus").edit(r -> updated);
    assertAnimal(object, "walrus", "my-updated-awesome-walrus-image");
    // Test Delete:
    resourceClient.withName("otter").delete();
    resourceClient.delete();
}
Also used : BeforeClass(org.junit.BeforeClass) GenericKubernetesResource(io.fabric8.kubernetes.api.model.GenericKubernetesResource) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) RunWith(org.junit.runner.RunWith) Watcher(io.fabric8.kubernetes.client.Watcher) Session(org.arquillian.cube.kubernetes.api.Session) HashMap(java.util.HashMap) WatcherException(io.fabric8.kubernetes.client.WatcherException) Resource(io.fabric8.kubernetes.client.dsl.Resource) CustomResourceDefinitionContext(io.fabric8.kubernetes.client.dsl.base.CustomResourceDefinitionContext) ClusterEntity(io.fabric8.commons.ClusterEntity) Serialization(io.fabric8.kubernetes.client.utils.Serialization) Map(java.util.Map) ArquillianResource(org.jboss.arquillian.test.api.ArquillianResource) ArquillianConditionalRunner(org.arquillian.cube.requirement.ArquillianConditionalRunner) ClassRule(org.junit.ClassRule) Before(org.junit.Before) AfterClass(org.junit.AfterClass) Awaitility.await(org.awaitility.Awaitility.await) Assert.assertNotNull(org.junit.Assert.assertNotNull) Assert.assertTrue(org.junit.Assert.assertTrue) RequiresKubernetes(org.arquillian.cube.kubernetes.impl.requirement.RequiresKubernetes) Test(org.junit.Test) IOException(java.io.IOException) TimeUnit(java.util.concurrent.TimeUnit) CountDownLatch(java.util.concurrent.CountDownLatch) NonNamespaceOperation(io.fabric8.kubernetes.client.dsl.NonNamespaceOperation) Assert.assertNull(org.junit.Assert.assertNull) GenericKubernetesResourceList(io.fabric8.kubernetes.api.model.GenericKubernetesResourceList) Assert.assertFalse(org.junit.Assert.assertFalse) KubernetesClient(io.fabric8.kubernetes.client.KubernetesClient) AssumingK8sVersionAtLeast(io.fabric8.commons.AssumingK8sVersionAtLeast) Collections(java.util.Collections) Assert.assertEquals(org.junit.Assert.assertEquals) InputStream(java.io.InputStream) HashMap(java.util.HashMap) GenericKubernetesResourceList(io.fabric8.kubernetes.api.model.GenericKubernetesResourceList) GenericKubernetesResource(io.fabric8.kubernetes.api.model.GenericKubernetesResource) Test(org.junit.Test)

Example 4 with GenericKubernetesResourceList

use of io.fabric8.kubernetes.api.model.GenericKubernetesResourceList in project kubernetes-client by fabric8io.

the class GenericResourceIT method testGenericBuiltinResourceWithoutMetadata.

@Test
public void testGenericBuiltinResourceWithoutMetadata() {
    GenericKubernetesResource configMap = new GenericKubernetesResource();
    configMap.setKind("ConfigMap");
    configMap.setApiVersion("v1");
    configMap.setMetadata(new ObjectMetaBuilder().withName("my-map").build());
    NamespaceableResource<GenericKubernetesResource> resource = client.resource(configMap);
    GenericKubernetesResource result = resource.createOrReplace();
    assertNotNull(result);
    MixedOperation<GenericKubernetesResource, GenericKubernetesResourceList, Resource<GenericKubernetesResource>> resources = client.genericKubernetesResources("v1", "ConfigMap");
    assertTrue(!resources.list().getItems().isEmpty());
}
Also used : GenericKubernetesResourceList(io.fabric8.kubernetes.api.model.GenericKubernetesResourceList) GenericKubernetesResource(io.fabric8.kubernetes.api.model.GenericKubernetesResource) Resource(io.fabric8.kubernetes.client.dsl.Resource) NamespaceableResource(io.fabric8.kubernetes.client.dsl.NamespaceableResource) ArquillianResource(org.jboss.arquillian.test.api.ArquillianResource) ObjectMetaBuilder(io.fabric8.kubernetes.api.model.ObjectMetaBuilder) GenericKubernetesResource(io.fabric8.kubernetes.api.model.GenericKubernetesResource) Test(org.junit.Test)

Example 5 with GenericKubernetesResourceList

use of io.fabric8.kubernetes.api.model.GenericKubernetesResourceList in project kubernetes-client by fabric8io.

the class InformTest method testInformGeneric.

@Test
void testInformGeneric() throws InterruptedException {
    // Given
    GenericKubernetesResource dummy = new GenericKubernetesResource();
    dummy.setMetadata(new ObjectMetaBuilder().withName("one").withNamespace("test").build());
    dummy.setKind("dummy");
    dummy.setApiVersion("demos.fabric8.io/v1");
    GenericKubernetesResourceList list = new GenericKubernetesResourceList();
    list.setMetadata(new ListMetaBuilder().withResourceVersion("1").build());
    list.setItems(Arrays.asList(dummy));
    server.expect().withPath("/apis/demos.fabric8.io/v1/namespaces/test/dummies?labelSelector=my-label").andReturn(HttpURLConnection.HTTP_OK, list).once();
    server.expect().withPath("/apis/demos.fabric8.io/v1/namespaces/test/dummies?labelSelector=my-label&resourceVersion=1&allowWatchBookmarks=true&watch=true").andUpgradeToWebSocket().open().waitFor(EVENT_WAIT_PERIOD_MS).andEmit(new WatchEvent(dummy, "DELETED")).done().once();
    final CountDownLatch deleteLatch = new CountDownLatch(1);
    final CountDownLatch addLatch = new CountDownLatch(1);
    final ResourceEventHandler<GenericKubernetesResource> handler = new ResourceEventHandler<GenericKubernetesResource>() {

        @Override
        public void onAdd(GenericKubernetesResource obj) {
            addLatch.countDown();
        }

        @Override
        public void onDelete(GenericKubernetesResource obj, boolean deletedFinalStateUnknown) {
            deleteLatch.countDown();
        }

        @Override
        public void onUpdate(GenericKubernetesResource oldObj, GenericKubernetesResource newObj) {
        }
    };
    // When
    CustomResourceDefinitionContext context = new CustomResourceDefinitionContext.Builder().withKind("Dummy").withScope("Namespaced").withVersion("v1").withGroup("demos.fabric8.io").withPlural("dummies").build();
    SharedIndexInformer<GenericKubernetesResource> informer = client.genericKubernetesResources(context).withLabel("my-label").inform(handler);
    assertTrue(deleteLatch.await(10, TimeUnit.SECONDS));
    assertTrue(addLatch.await(10, TimeUnit.SECONDS));
    informer.stop();
}
Also used : ResourceEventHandler(io.fabric8.kubernetes.client.informers.ResourceEventHandler) CustomResourceDefinitionContext(io.fabric8.kubernetes.client.dsl.base.CustomResourceDefinitionContext) ListMetaBuilder(io.fabric8.kubernetes.api.model.ListMetaBuilder) ListMetaBuilder(io.fabric8.kubernetes.api.model.ListMetaBuilder) PodListBuilder(io.fabric8.kubernetes.api.model.PodListBuilder) PodBuilder(io.fabric8.kubernetes.api.model.PodBuilder) ObjectMetaBuilder(io.fabric8.kubernetes.api.model.ObjectMetaBuilder) GenericKubernetesResourceList(io.fabric8.kubernetes.api.model.GenericKubernetesResourceList) WatchEvent(io.fabric8.kubernetes.api.model.WatchEvent) ObjectMetaBuilder(io.fabric8.kubernetes.api.model.ObjectMetaBuilder) CountDownLatch(java.util.concurrent.CountDownLatch) GenericKubernetesResource(io.fabric8.kubernetes.api.model.GenericKubernetesResource) Test(org.junit.jupiter.api.Test)

Aggregations

GenericKubernetesResourceList (io.fabric8.kubernetes.api.model.GenericKubernetesResourceList)9 GenericKubernetesResource (io.fabric8.kubernetes.api.model.GenericKubernetesResource)7 Resource (io.fabric8.kubernetes.client.dsl.Resource)3 CustomResourceDefinitionContext (io.fabric8.kubernetes.client.dsl.base.CustomResourceDefinitionContext)3 HashMap (java.util.HashMap)3 CountDownLatch (java.util.concurrent.CountDownLatch)3 Test (org.junit.Test)3 Test (org.junit.jupiter.api.Test)3 ObjectMetaBuilder (io.fabric8.kubernetes.api.model.ObjectMetaBuilder)2 KubernetesClient (io.fabric8.kubernetes.client.KubernetesClient)2 WatcherException (io.fabric8.kubernetes.client.WatcherException)2 IOException (java.io.IOException)2 ArquillianResource (org.jboss.arquillian.test.api.ArquillianResource)2 AssumingK8sVersionAtLeast (io.fabric8.commons.AssumingK8sVersionAtLeast)1 ClusterEntity (io.fabric8.commons.ClusterEntity)1 ListMetaBuilder (io.fabric8.kubernetes.api.model.ListMetaBuilder)1 ObjectMeta (io.fabric8.kubernetes.api.model.ObjectMeta)1 PodBuilder (io.fabric8.kubernetes.api.model.PodBuilder)1 PodListBuilder (io.fabric8.kubernetes.api.model.PodListBuilder)1 WatchEvent (io.fabric8.kubernetes.api.model.WatchEvent)1