Search in sources :

Example 1 with KubernetesClientBuilder

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

the class BindingExample method main.

@SuppressWarnings("java:S106")
public static void main(String[] args) {
    final String podName = "binding-example-" + UUID.randomUUID();
    try (final KubernetesClient client = new KubernetesClientBuilder().build()) {
        final String namespace;
        if (client.getConfiguration().getNamespace() != null) {
            namespace = client.getConfiguration().getNamespace();
        } else if (client.getNamespace() != null) {
            namespace = client.getNamespace();
        } else {
            namespace = client.namespaces().list().getItems().stream().findFirst().orElseThrow(() -> new IllegalStateException("No namespace available")).getMetadata().getName();
        }
        client.pods().inNamespace(namespace).create(new PodBuilder().withMetadata(new ObjectMetaBuilder().withName(podName).build()).withSpec(new PodSpecBuilder().withSchedulerName("random-scheduler-name-which-does-not-exist").addNewContainer().withName(podName).withImage("nginx:latest").endContainer().build()).build());
        final Node firstNode = client.nodes().list().getItems().stream().findFirst().orElseThrow(() -> new IllegalStateException("No nodes available"));
        client.bindings().inNamespace(namespace).create(new BindingBuilder().withNewMetadata().withName(podName).endMetadata().withNewTarget().withKind(firstNode.getKind()).withApiVersion(firstNode.getApiVersion()).withName(firstNode.getMetadata().getName()).endTarget().build());
        System.out.printf("Successfully bound Pod %s to Node %s%n", podName, firstNode.getMetadata().getName());
    }
}
Also used : PodSpecBuilder(io.fabric8.kubernetes.api.model.PodSpecBuilder) KubernetesClient(io.fabric8.kubernetes.client.KubernetesClient) BindingBuilder(io.fabric8.kubernetes.api.model.BindingBuilder) KubernetesClientBuilder(io.fabric8.kubernetes.client.KubernetesClientBuilder) PodBuilder(io.fabric8.kubernetes.api.model.PodBuilder) Node(io.fabric8.kubernetes.api.model.Node) ObjectMetaBuilder(io.fabric8.kubernetes.api.model.ObjectMetaBuilder)

Example 2 with KubernetesClientBuilder

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

the class CRDExample method main.

/**
 * Example of Cluster and Namespaced scoped K8S Custom Resources.
 * To test Cluster scoped resource use "--cluster" as first argument.
 * To test Namespaced resource provide namespace as first argument (namespace must exists in K8S).
 *
 * @param args Either "--cluster" or namespace name.
 */
public static void main(String[] args) {
    boolean resourceNamespaced = true;
    String namespace = null;
    if (args.length > 0) {
        if ("--cluster".equals(args[0])) {
            resourceNamespaced = false;
        } else {
            namespace = args[0];
        }
    }
    try (final KubernetesClient client = new KubernetesClientBuilder().build()) {
        if (resourceNamespaced) {
            if (namespace == null) {
                namespace = client.getNamespace();
            }
            if (namespace == null) {
                System.err.println("No namespace specified and no default defined!");
                return;
            }
            System.out.println("Using namespace: " + namespace);
        } else {
            System.out.println("Creating cluster scoped resource");
        }
        if (LOG_ROOT_PATHS) {
            RootPaths rootPaths = client.rootPaths();
            if (rootPaths != null) {
                List<String> paths = rootPaths.getPaths();
                if (paths != null) {
                    System.out.println("Supported API Paths:");
                    for (String path : paths) {
                        System.out.println("    " + path);
                    }
                    System.out.println();
                }
            }
        }
        CustomResourceDefinitionList crds = client.apiextensions().v1().customResourceDefinitions().list();
        List<CustomResourceDefinition> crdsItems = crds.getItems();
        System.out.println("Found " + crdsItems.size() + " CRD(s)");
        CustomResourceDefinition dummyCRD = null;
        final String dummyCRDName = CustomResource.getCRDName(Dummy.class);
        for (CustomResourceDefinition crd : crdsItems) {
            ObjectMeta metadata = crd.getMetadata();
            if (metadata != null) {
                String name = metadata.getName();
                System.out.println("    " + name + " => " + metadata.getSelfLink());
                if (dummyCRDName.equals(name)) {
                    dummyCRD = crd;
                }
            }
        }
        if (dummyCRD != null) {
            System.out.println("Found CRD: " + dummyCRD.getMetadata().getSelfLink());
        } else {
            dummyCRD = CustomResourceDefinitionContext.v1CRDFromCustomResourceType(Dummy.class).editSpec().editVersion(0).withNewSchema().withNewOpenAPIV3Schema().withTitle("dummy").withType("object").addToRequired("spec").addToProperties("spec", new JSONSchemaPropsBuilder().withType("object").addToProperties("foo", new JSONSchemaPropsBuilder().withType("string").build()).addToProperties("bar", new JSONSchemaPropsBuilder().withType("string").build()).build()).endOpenAPIV3Schema().endSchema().endVersion().endSpec().build();
            client.apiextensions().v1().customResourceDefinitions().create(dummyCRD);
            System.out.println("Created CRD " + dummyCRD.getMetadata().getName());
        }
        // wait a beat for the endpoints to be ready
        Thread.sleep(5000);
        // lets create a client for the CRD
        NonNamespaceOperation<Dummy, DummyList, Resource<Dummy>> dummyClient = client.resources(Dummy.class, DummyList.class);
        if (resourceNamespaced) {
            dummyClient = ((MixedOperation<Dummy, DummyList, Resource<Dummy>>) dummyClient).inNamespace(namespace);
        }
        CustomResourceList<Dummy> dummyList = dummyClient.list();
        List<Dummy> items = dummyList.getItems();
        System.out.println("  found " + items.size() + " dummies");
        for (Dummy item : items) {
            System.out.println("    " + item);
        }
        Dummy dummy = new Dummy();
        ObjectMeta metadata = new ObjectMeta();
        metadata.setName("foo");
        dummy.setMetadata(metadata);
        DummySpec dummySpec = new DummySpec();
        Date now = new Date();
        dummySpec.setBar("beer: " + now);
        dummySpec.setFoo("cheese: " + now);
        dummy.setSpec(dummySpec);
        Dummy created = dummyClient.createOrReplace(dummy);
        System.out.println("Upserted " + dummy);
        created.getSpec().setBar("otherBar");
        dummyClient.createOrReplace(created);
        System.out.println("Watching for changes to Dummies");
        dummyClient.withResourceVersion(created.getMetadata().getResourceVersion()).watch(new Watcher<Dummy>() {

            @Override
            public void eventReceived(Action action, Dummy resource) {
                System.out.println("==> " + action + " for " + resource);
                if (resource.getSpec() == null) {
                    logger.error("No Spec for resource {}", resource);
                }
            }

            @Override
            public void onClose(WatcherException cause) {
            }
        });
        System.in.read();
    } catch (KubernetesClientException e) {
        logger.error(e.getMessage(), e);
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }
}
Also used : DummySpec(io.fabric8.kubernetes.examples.crds.DummySpec) JSONSchemaPropsBuilder(io.fabric8.kubernetes.api.model.apiextensions.v1.JSONSchemaPropsBuilder) KubernetesClientBuilder(io.fabric8.kubernetes.client.KubernetesClientBuilder) ObjectMeta(io.fabric8.kubernetes.api.model.ObjectMeta) KubernetesClient(io.fabric8.kubernetes.client.KubernetesClient) RootPaths(io.fabric8.kubernetes.api.model.RootPaths) CustomResourceDefinition(io.fabric8.kubernetes.api.model.apiextensions.v1.CustomResourceDefinition) Resource(io.fabric8.kubernetes.client.dsl.Resource) CustomResource(io.fabric8.kubernetes.client.CustomResource) DummyList(io.fabric8.kubernetes.examples.crds.DummyList) Date(java.util.Date) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException) WatcherException(io.fabric8.kubernetes.client.WatcherException) WatcherException(io.fabric8.kubernetes.client.WatcherException) CustomResourceDefinitionList(io.fabric8.kubernetes.api.model.apiextensions.v1.CustomResourceDefinitionList) Dummy(io.fabric8.kubernetes.examples.crds.Dummy) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException)

Example 3 with KubernetesClientBuilder

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

the class UploadDirectoryToPod method main.

public static void main(String[] args) {
    try (KubernetesClient k8s = new KubernetesClientBuilder().build()) {
        File fileToUpload = new File("/tmp/test-dir-src");
        // <- Namespace of Pod
        k8s.pods().inNamespace("default").withName(// <- Name of Pod
        "my-pod").dir(// <- Path of directory inside Pod
        "/tmp/test-dir").upload(// <- Local Path of directory
        fileToUpload.toPath());
    }
}
Also used : KubernetesClient(io.fabric8.kubernetes.client.KubernetesClient) KubernetesClientBuilder(io.fabric8.kubernetes.client.KubernetesClientBuilder) File(java.io.File)

Example 4 with KubernetesClientBuilder

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

the class BuildConfigExamples method main.

@SuppressWarnings("java:S106")
public static void main(String[] args) throws InterruptedException {
    try (KubernetesClient kubernetesClient = new KubernetesClientBuilder().build()) {
        final OpenShiftClient client = kubernetesClient.adapt(OpenShiftClient.class);
        final String namespace;
        if (client.getNamespace() != null) {
            namespace = client.getNamespace();
            logger.info("Using configured namespace: {}", namespace);
        } else {
            final Namespace ns = client.namespaces().create(new NamespaceBuilder().withNewMetadata().withName(NAMESPACE).addToLabels("this", "rocks").endMetadata().build());
            namespace = ns.getMetadata().getName();
            logger.info("Created namespace: {}", namespace);
        }
        client.serviceAccounts().inNamespace(namespace).create(new ServiceAccountBuilder().withNewMetadata().withName("fabric8").endMetadata().build());
        final ImageStream is = client.imageStreams().inNamespace(namespace).create(new ImageStreamBuilder().withNewMetadata().withName("example-camel-cdi").endMetadata().withNewSpec().addNewTag().withName("latest").endTag().withDockerImageRepository("fabric8/example-camel-cdi").endSpec().withNewStatus().withDockerImageRepository("").endStatus().build());
        logger.info("Created image stream: {}", is.getMetadata().getName());
        final String buildConfigName = "custom-build-config";
        final BuildConfig buildConfig = client.buildConfigs().inNamespace(namespace).create(new BuildConfigBuilder().withNewMetadata().withName(buildConfigName).endMetadata().withNewSpec().withServiceAccount("fabric8").withNewSource().withType("Git").withNewGit().withUri("https://github.com/fabric8io/example-camel-cdi.git").endGit().endSource().withNewResources().addToLimits("mykey", new Quantity("10")).addToRequests("mykey", new Quantity("10")).endResources().withNewStrategy().withType("Source").withNewSourceStrategy().withNewFrom().withName("java-sti:latest").withKind("DockerImage").endFrom().endSourceStrategy().endStrategy().withNewOutput().withNewTo().withKind("DockerImage").withName("example-camel-cdi:latest").endTo().endOutput().addNewTrigger().withType("GitHub").withNewGithub().withSecret("secret101").endGithub().endTrigger().endSpec().build());
        logger.info("Created Build Config: {}", buildConfig.getMetadata().getName());
        final Build build = client.buildConfigs().inNamespace(namespace).withName("custom-build-config").instantiate(new BuildRequestBuilder().withNewMetadata().withName(buildConfigName).endMetadata().build());
        logger.info("Instantiated Build: {}", build.getMetadata().getName());
        client.buildConfigs().inNamespace(namespace).withName(buildConfigName).withSecret("secret101").withType("github").trigger(new WebHookTriggerBuilder().withSecret("secret101").build());
        logger.info("Triggered Build Config: {}", buildConfigName);
        Thread.sleep(6000);
        logger.info("Builds:");
        for (Build b : client.builds().inNamespace(namespace).list().getItems()) {
            logger.info("\t\t\t{}", b.getMetadata().getName());
            logger.info("\t\t\t\t\t Log:");
            client.builds().inNamespace(namespace).withName(b.getMetadata().getName()).watchLog(System.out);
        }
        logger.info("Done");
    }
}
Also used : KubernetesClient(io.fabric8.kubernetes.client.KubernetesClient) ServiceAccountBuilder(io.fabric8.kubernetes.api.model.ServiceAccountBuilder) ImageStream(io.fabric8.openshift.api.model.ImageStream) Quantity(io.fabric8.kubernetes.api.model.Quantity) BuildConfigBuilder(io.fabric8.openshift.api.model.BuildConfigBuilder) Namespace(io.fabric8.kubernetes.api.model.Namespace) NamespaceBuilder(io.fabric8.kubernetes.api.model.NamespaceBuilder) ImageStreamBuilder(io.fabric8.openshift.api.model.ImageStreamBuilder) KubernetesClientBuilder(io.fabric8.kubernetes.client.KubernetesClientBuilder) Build(io.fabric8.openshift.api.model.Build) BuildRequestBuilder(io.fabric8.openshift.api.model.BuildRequestBuilder) OpenShiftClient(io.fabric8.openshift.client.OpenShiftClient) BuildConfig(io.fabric8.openshift.api.model.BuildConfig) WebHookTriggerBuilder(io.fabric8.openshift.api.model.WebHookTriggerBuilder)

Example 5 with KubernetesClientBuilder

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

the class ListBuildConfigs method main.

public static void main(String[] args) {
    try (OpenShiftClient client = new KubernetesClientBuilder().build().adapt(OpenShiftClient.class)) {
        if (!client.supportsOpenShiftAPIGroup(OpenShiftAPIGroups.BUILD)) {
            logger.warn("This cluster does not support the API Group {}", OpenShiftAPIGroups.BUILD);
            return;
        }
        BuildConfigList list = client.buildConfigs().list();
        if (list == null) {
            logger.error("No list returned!");
            return;
        }
        List<BuildConfig> items = list.getItems();
        for (BuildConfig item : items) {
            logger.info("BuildConfig {} has version: {}", item.getMetadata().getName(), item.getApiVersion());
        }
    } catch (KubernetesClientException e) {
        logger.error("Failed: {}", e.getMessage(), e);
    }
}
Also used : KubernetesClientBuilder(io.fabric8.kubernetes.client.KubernetesClientBuilder) OpenShiftClient(io.fabric8.openshift.client.OpenShiftClient) BuildConfig(io.fabric8.openshift.api.model.BuildConfig) BuildConfigList(io.fabric8.openshift.api.model.BuildConfigList) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException)

Aggregations

KubernetesClientBuilder (io.fabric8.kubernetes.client.KubernetesClientBuilder)78 KubernetesClient (io.fabric8.kubernetes.client.KubernetesClient)70 KubernetesClientException (io.fabric8.kubernetes.client.KubernetesClientException)25 ConfigBuilder (io.fabric8.kubernetes.client.ConfigBuilder)23 OpenShiftClient (io.fabric8.openshift.client.OpenShiftClient)15 Pod (io.fabric8.kubernetes.api.model.Pod)10 Namespace (io.fabric8.kubernetes.api.model.Namespace)7 NamespaceBuilder (io.fabric8.kubernetes.api.model.NamespaceBuilder)7 WatcherException (io.fabric8.kubernetes.client.WatcherException)6 HasMetadata (io.fabric8.kubernetes.api.model.HasMetadata)5 PodBuilder (io.fabric8.kubernetes.api.model.PodBuilder)5 Config (io.fabric8.kubernetes.client.Config)5 File (java.io.File)5 ObjectMetaBuilder (io.fabric8.kubernetes.api.model.ObjectMetaBuilder)4 Quantity (io.fabric8.kubernetes.api.model.Quantity)4 ExecWatch (io.fabric8.kubernetes.client.dsl.ExecWatch)4 Resource (io.fabric8.kubernetes.client.dsl.Resource)4 CountDownLatch (java.util.concurrent.CountDownLatch)4 GenericKubernetesResource (io.fabric8.kubernetes.api.model.GenericKubernetesResource)3 ConfigMap (io.fabric8.kubernetes.api.model.ConfigMap)2