Search in sources :

Example 1 with ApiClient

use of io.kubernetes.client.openapi.ApiClient in project java by kubernetes-client.

the class KubectlExample method main.

public static void main(String[] args) throws java.io.IOException, KubectlException, ParseException {
    ApiClient client = Config.defaultClient();
    Options options = new Options();
    options.addOption(new Option("n", "namespace", true, "The namespace for the resource"));
    options.addOption(new Option("r", "replicas", true, "The number of replicas to scale to"));
    options.addOption(new Option("c", "container", true, "The container in a pod to connect to"));
    DefaultParser parser = new DefaultParser();
    CommandLine cli = parser.parse(options, args);
    args = cli.getArgs();
    String verb = args[0];
    String ns = cli.getOptionValue("n", "default");
    String kind = null;
    String name = null;
    switch(verb) {
        case "delete":
            kind = args[1];
            name = args[2];
            delete(getClassForKind(kind)).namespace(ns).name(name).execute();
        case "drain":
            name = args[1];
            drain().apiClient(client).name(name).execute();
            System.out.println("Node drained");
            System.exit(0);
        case "cordon":
            name = args[1];
            cordon().apiClient(client).name(name).execute();
            System.out.println("Node cordoned");
            System.exit(0);
        case "uncordon":
            name = args[1];
            uncordon().apiClient(client).name(name).execute();
            System.out.println("Node uncordoned");
            System.exit(0);
        case "top":
            String what = args[1];
            switch(what) {
                case "nodes":
                case "node":
                    List<Pair<V1Node, NodeMetrics>> nodes = top(V1Node.class, NodeMetrics.class).apiClient(client).metric("cpu").execute();
                    System.out.println(pad("Node") + "\tCPU\t\tMemory");
                    for (Pair<V1Node, NodeMetrics> node : nodes) {
                        System.out.println(pad(node.getLeft().getMetadata().getName()) + "\t" + node.getRight().getUsage().get("cpu").getNumber() + "\t" + node.getRight().getUsage().get("memory").getNumber());
                    }
                    System.exit(0);
                case "pods":
                case "pod":
                    List<Pair<V1Pod, PodMetrics>> pods = top(V1Pod.class, PodMetrics.class).apiClient(client).namespace(ns).metric("cpu").execute();
                    System.out.println(pad("Pod") + "\tCPU\t\tMemory");
                    for (Pair<V1Pod, PodMetrics> pod : pods) {
                        System.out.println(pad(pod.getLeft().getMetadata().getName()) + "\t" + podMetricSum(pod.getRight(), "cpu") + "\t" + podMetricSum(pod.getRight(), "memory"));
                    }
                    System.exit(0);
            }
            System.err.println("Unknown top argument: " + what);
            System.exit(-1);
        case "cp":
            String from = args[1];
            String to = args[2];
            if (from.indexOf(":") != -1) {
                String[] parts = from.split(":");
                name = parts[0];
                from = parts[1];
                copy().apiClient(client).namespace(ns).name(name).container(cli.getOptionValue("c", "")).fromPod(from).to(to).execute();
            } else if (to.indexOf(":") != -1) {
                String[] parts = to.split(":");
                name = parts[0];
                to = parts[1];
                copy().apiClient(client).namespace(ns).name(name).container(cli.getOptionValue("c", "")).from(from).toPod(to).execute();
            } else {
                System.err.println("Missing pod name for copy.");
                System.exit(-1);
            }
            System.out.println("Copied " + from + " -> " + to);
            System.exit(0);
        case "taint":
            name = args[1];
            String taintSpec = args[2];
            boolean remove = taintSpec.endsWith("-");
            int ix = taintSpec.indexOf("=");
            int ix2 = taintSpec.indexOf(":");
            if (remove) {
                taintSpec = taintSpec.substring(0, taintSpec.length() - 2);
                String key = ix == -1 ? taintSpec : taintSpec.substring(0, ix);
                String effect = ix == -1 ? null : taintSpec.substring(ix + 1);
                if (effect == null) {
                    taint().apiClient(client).name(name).removeTaint(key).execute();
                } else {
                    taint().apiClient(client).name(name).removeTaint(key, effect).execute();
                }
                System.exit(0);
            }
            if (ix2 == -1) {
                System.err.println("key:effect or key=value:effect is required.");
                System.exit(-1);
            }
            String key = taintSpec.substring(0, ix == -1 ? ix2 : ix);
            String value = ix == -1 ? null : taintSpec.substring(ix + 1, ix2);
            String effect = taintSpec.substring(ix2 + 1);
            if (value == null) {
                taint().apiClient(client).name(name).addTaint(key, effect).execute();
            } else {
                taint().apiClient(client).name(name).addTaint(key, value, effect).execute();
            }
            System.exit(0);
        case "portforward":
            name = args[1];
            KubectlPortForward forward = portforward().apiClient(client).name(name).namespace(ns);
            for (int i = 2; i < args.length; i++) {
                String port = args[i];
                String[] ports = port.split(":");
                System.out.println("Forwarding " + ns + "/" + name + " " + ports[0] + "->" + ports[1]);
                forward.ports(Integer.parseInt(ports[0]), Integer.parseInt(ports[1]));
            }
            forward.execute();
            System.exit(0);
        case "log":
            name = args[1];
            Streams.copy(log().apiClient(client).name(name).namespace(ns).container(cli.getOptionValue("c", "")).execute(), System.out);
            System.exit(0);
        case "scale":
            kind = args[1];
            name = args[2];
            if (!cli.hasOption("r")) {
                System.err.println("--replicas <n> is required");
                System.exit(-3);
            }
            int replicas = Integer.parseInt(cli.getOptionValue("r"));
            scale(getClassForKind(kind)).apiClient(client).namespace(ns).name(name).replicas(replicas).execute();
            System.out.println("Deployment scaled.");
            System.exit(0);
        case "version":
            System.out.println(version().apiClient(client));
            System.exit(0);
        case "label":
            kind = args[1];
            name = args[2];
            String labelKey = args[3];
            String labelValue = args[4];
            Class<? extends KubernetesObject> clazz = getClassForKind(kind);
            if (clazz == null) {
                System.err.println("Unknown kind: " + kind);
                System.exit(-2);
            }
            label(clazz).apiClient(client).namespace(ns).name(name).addLabel(labelKey, labelValue);
            System.exit(0);
        case "exec":
            name = args[1];
            String[] command = Arrays.copyOfRange(args, 2, args.length);
            KubectlExec e = exec().apiClient(client).namespace(ns).name(name).command(command).container(cli.getOptionValue("c", ""));
            System.exit(e.execute());
        case "api-resources":
            apiResources().apiClient(client).execute().stream().forEach(r -> System.out.printf("%s\t\t%s\t\t%s\t\t%s\n", r.getResourcePlural(), r.getGroup(), r.getKind(), r.getNamespaced()));
            System.exit(0);
        default:
            System.out.println("Unknown verb: " + verb);
            System.exit(-1);
    }
}
Also used : Options(org.apache.commons.cli.Options) V1Node(io.kubernetes.client.openapi.models.V1Node) NodeMetrics(io.kubernetes.client.custom.NodeMetrics) ApiClient(io.kubernetes.client.openapi.ApiClient) Kubectl.taint(io.kubernetes.client.extended.kubectl.Kubectl.taint) CommandLine(org.apache.commons.cli.CommandLine) KubectlExec(io.kubernetes.client.extended.kubectl.KubectlExec) PodMetrics(io.kubernetes.client.custom.PodMetrics) V1Pod(io.kubernetes.client.openapi.models.V1Pod) Option(org.apache.commons.cli.Option) KubectlPortForward(io.kubernetes.client.extended.kubectl.KubectlPortForward) DefaultParser(org.apache.commons.cli.DefaultParser) Pair(org.apache.commons.lang3.tuple.Pair)

Example 2 with ApiClient

use of io.kubernetes.client.openapi.ApiClient in project java by kubernetes-client.

the class YamlExample method main.

public static void main(String[] args) throws IOException, ApiException, ClassNotFoundException {
    V1Pod pod = new V1PodBuilder().withNewMetadata().withName("apod").endMetadata().withNewSpec().addNewContainer().withName("www").withImage("nginx").withNewResources().withLimits(new HashMap<>()).endResources().endContainer().endSpec().build();
    System.out.println(Yaml.dump(pod));
    V1Service svc = new V1ServiceBuilder().withNewMetadata().withName("aservice").endMetadata().withNewSpec().withSessionAffinity(V1ServiceSpec.SessionAffinityEnum.CLIENTIP).withType(V1ServiceSpec.TypeEnum.NODEPORT).addNewPort().withProtocol(V1ServicePort.ProtocolEnum.TCP).withName("client").withPort(8008).withNodePort(8080).withTargetPort(new IntOrString(8080)).endPort().endSpec().build();
    System.out.println(Yaml.dump(svc));
    // Read yaml configuration file, and deploy it
    ApiClient client = Config.defaultClient();
    Configuration.setDefaultApiClient(client);
    // See issue #474. Not needed at most cases, but it is needed if you are using war
    // packging or running this on JUnit.
    Yaml.addModelMap("v1", "Service", V1Service.class);
    // Example yaml file can be found in $REPO_DIR/test-svc.yaml
    File file = new File("test-svc.yaml");
    V1Service yamlSvc = (V1Service) Yaml.load(file);
    // Deployment and StatefulSet is defined in apps/v1, so you should use AppsV1Api instead of
    // CoreV1API
    CoreV1Api api = new CoreV1Api();
    V1Service createResult = api.createNamespacedService("default", yamlSvc, null, null, null, null);
    System.out.println(createResult);
    V1Service deleteResult = api.deleteNamespacedService(yamlSvc.getMetadata().getName(), "default", null, null, null, null, null, new V1DeleteOptions());
    System.out.println(deleteResult);
}
Also used : V1DeleteOptions(io.kubernetes.client.openapi.models.V1DeleteOptions) V1PodBuilder(io.kubernetes.client.openapi.models.V1PodBuilder) IntOrString(io.kubernetes.client.custom.IntOrString) V1ServiceBuilder(io.kubernetes.client.openapi.models.V1ServiceBuilder) V1Pod(io.kubernetes.client.openapi.models.V1Pod) V1Service(io.kubernetes.client.openapi.models.V1Service) ApiClient(io.kubernetes.client.openapi.ApiClient) File(java.io.File) CoreV1Api(io.kubernetes.client.openapi.apis.CoreV1Api)

Example 3 with ApiClient

use of io.kubernetes.client.openapi.ApiClient in project java by kubernetes-client.

the class DeployRolloutRestartExample method main.

public static void main(String[] args) throws IOException, ApiException {
    ApiClient client = Config.defaultClient();
    Configuration.setDefaultApiClient(client);
    AppsV1Api appsV1Api = new AppsV1Api(client);
    String deploymentName = "example-nginx";
    String imageName = "nginx:1.21.6";
    String namespace = "default";
    // Create an example deployment
    V1DeploymentBuilder deploymentBuilder = new V1DeploymentBuilder().withApiVersion("apps/v1").withKind("Deployment").withMetadata(new V1ObjectMeta().name(deploymentName).namespace(namespace)).withSpec(new V1DeploymentSpec().replicas(1).selector(new V1LabelSelector().putMatchLabelsItem("name", deploymentName)).template(new V1PodTemplateSpec().metadata(new V1ObjectMeta().putLabelsItem("name", deploymentName)).spec(new V1PodSpec().containers(Collections.singletonList(new V1Container().name(deploymentName).image(imageName))))));
    appsV1Api.createNamespacedDeployment(namespace, deploymentBuilder.build(), null, null, null, null);
    // Wait until example deployment is ready
    Wait.poll(Duration.ofSeconds(3), Duration.ofSeconds(60), () -> {
        try {
            System.out.println("Waiting until example deployment is ready...");
            return appsV1Api.readNamespacedDeployment(deploymentName, namespace, null).getStatus().getReadyReplicas() > 0;
        } catch (ApiException e) {
            e.printStackTrace();
            return false;
        }
    });
    System.out.println("Created example deployment!");
    // Trigger a rollout restart of the example deployment
    V1Deployment runningDeployment = appsV1Api.readNamespacedDeployment(deploymentName, namespace, null);
    // Explicitly set "restartedAt" annotation with current date/time to trigger rollout when patch
    // is applied
    runningDeployment.getSpec().getTemplate().getMetadata().putAnnotationsItem("kubectl.kubernetes.io/restartedAt", LocalDateTime.now().toString());
    try {
        String deploymentJson = client.getJSON().serialize(runningDeployment);
        PatchUtils.patch(V1Deployment.class, () -> appsV1Api.patchNamespacedDeploymentCall(deploymentName, namespace, new V1Patch(deploymentJson), null, null, "kubectl-rollout", null, null, null), V1Patch.PATCH_FORMAT_STRATEGIC_MERGE_PATCH, client);
        // Wait until deployment has stabilized after rollout restart
        Wait.poll(Duration.ofSeconds(3), Duration.ofSeconds(60), () -> {
            try {
                System.out.println("Waiting until example deployment restarted successfully...");
                return appsV1Api.readNamespacedDeployment(deploymentName, namespace, null).getStatus().getReadyReplicas() > 0;
            } catch (ApiException e) {
                e.printStackTrace();
                return false;
            }
        });
        System.out.println("Example deployment restarted successfully!");
    } catch (ApiException e) {
        e.printStackTrace();
    }
}
Also used : V1Deployment(io.kubernetes.client.openapi.models.V1Deployment) AppsV1Api(io.kubernetes.client.openapi.apis.AppsV1Api) V1ObjectMeta(io.kubernetes.client.openapi.models.V1ObjectMeta) V1Patch(io.kubernetes.client.custom.V1Patch) V1DeploymentSpec(io.kubernetes.client.openapi.models.V1DeploymentSpec) V1DeploymentBuilder(io.kubernetes.client.openapi.models.V1DeploymentBuilder) ApiClient(io.kubernetes.client.openapi.ApiClient) V1Container(io.kubernetes.client.openapi.models.V1Container) V1PodTemplateSpec(io.kubernetes.client.openapi.models.V1PodTemplateSpec) V1LabelSelector(io.kubernetes.client.openapi.models.V1LabelSelector) V1PodSpec(io.kubernetes.client.openapi.models.V1PodSpec) ApiException(io.kubernetes.client.openapi.ApiException)

Example 4 with ApiClient

use of io.kubernetes.client.openapi.ApiClient in project java by kubernetes-client.

the class GenericClientExample method main.

public static void main(String[] args) throws Exception {
    // The following codes demonstrates using generic client to manipulate pods
    V1Pod pod = new V1Pod().metadata(new V1ObjectMeta().name("foo").namespace("default")).spec(new V1PodSpec().containers(Arrays.asList(new V1Container().name("c").image("test"))));
    ApiClient apiClient = ClientBuilder.standard().build();
    GenericKubernetesApi<V1Pod, V1PodList> podClient = new GenericKubernetesApi<>(V1Pod.class, V1PodList.class, "", "v1", "pods", apiClient);
    V1Pod latestPod = podClient.create(pod).throwsApiException().getObject();
    System.out.println("Created!");
    V1Pod patchedPod = podClient.patch("default", "foo", V1Patch.PATCH_FORMAT_STRATEGIC_MERGE_PATCH, new V1Patch("{\"metadata\":{\"finalizers\":[\"example.io/foo\"]}}")).throwsApiException().getObject();
    System.out.println("Patched!");
    V1Pod deletedPod = podClient.delete("default", "foo").throwsApiException().getObject();
    if (deletedPod != null) {
        System.out.println("Received after-deletion status of the requested object, will be deleting in background!");
    }
    System.out.println("Deleted!");
}
Also used : V1Container(io.kubernetes.client.openapi.models.V1Container) V1PodList(io.kubernetes.client.openapi.models.V1PodList) V1ObjectMeta(io.kubernetes.client.openapi.models.V1ObjectMeta) V1Patch(io.kubernetes.client.custom.V1Patch) V1Pod(io.kubernetes.client.openapi.models.V1Pod) GenericKubernetesApi(io.kubernetes.client.util.generic.GenericKubernetesApi) ApiClient(io.kubernetes.client.openapi.ApiClient) V1PodSpec(io.kubernetes.client.openapi.models.V1PodSpec)

Example 5 with ApiClient

use of io.kubernetes.client.openapi.ApiClient in project java by kubernetes-client.

the class CopyExample method main.

public static void main(String[] args) throws IOException, ApiException, InterruptedException, CopyNotSupportedException {
    String podName = "kube-addon-manager-minikube";
    String namespace = "kube-system";
    ApiClient client = Config.defaultClient();
    Configuration.setDefaultApiClient(client);
    Copy copy = new Copy();
    InputStream dataStream = copy.copyFileFromPod(namespace, podName, "/etc/motd");
    Streams.copy(dataStream, System.out);
    copy.copyDirectoryFromPod(namespace, podName, null, "/etc", Paths.get("/tmp/etc"));
    System.out.println("Done!");
}
Also used : Copy(io.kubernetes.client.Copy) InputStream(java.io.InputStream) ApiClient(io.kubernetes.client.openapi.ApiClient)

Aggregations

ApiClient (io.kubernetes.client.openapi.ApiClient)61 Test (org.junit.Test)28 CoreV1Api (io.kubernetes.client.openapi.apis.CoreV1Api)13 V1Pod (io.kubernetes.client.openapi.models.V1Pod)12 IOException (java.io.IOException)11 V1PodList (io.kubernetes.client.openapi.models.V1PodList)9 ClientBuilder (io.kubernetes.client.util.ClientBuilder)6 V1ObjectMeta (io.kubernetes.client.openapi.models.V1ObjectMeta)5 Before (org.junit.Before)5 ApiException (io.kubernetes.client.openapi.ApiException)4 SharedInformerFactory (io.kubernetes.client.informer.SharedInformerFactory)3 V1Job (io.kubernetes.client.openapi.models.V1Job)3 V1JobList (io.kubernetes.client.openapi.models.V1JobList)3 V1Namespace (io.kubernetes.client.openapi.models.V1Namespace)3 OkHttpClient (okhttp3.OkHttpClient)3 NodeMetrics (io.kubernetes.client.custom.NodeMetrics)2 PodMetrics (io.kubernetes.client.custom.PodMetrics)2 V1Patch (io.kubernetes.client.custom.V1Patch)2 LeaderElectionConfig (io.kubernetes.client.extended.leaderelection.LeaderElectionConfig)2 LeaderElector (io.kubernetes.client.extended.leaderelection.LeaderElector)2