Search in sources :

Example 1 with V1Node

use of io.kubernetes.client.openapi.models.V1Node 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 V1Node

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

the class InformerExample method main.

public static void main(String[] args) throws Exception {
    CoreV1Api coreV1Api = new CoreV1Api();
    ApiClient apiClient = coreV1Api.getApiClient();
    OkHttpClient httpClient = apiClient.getHttpClient().newBuilder().readTimeout(0, TimeUnit.SECONDS).build();
    apiClient.setHttpClient(httpClient);
    SharedInformerFactory factory = new SharedInformerFactory(apiClient);
    // Node informer
    SharedIndexInformer<V1Node> nodeInformer = factory.sharedIndexInformerFor(// the informer-factory.
    (CallGeneratorParams params) -> {
        return coreV1Api.listNodeCall(null, null, null, null, null, null, params.resourceVersion, null, params.timeoutSeconds, params.watch, null);
    }, V1Node.class, V1NodeList.class);
    nodeInformer.addEventHandler(new ResourceEventHandler<V1Node>() {

        @Override
        public void onAdd(V1Node node) {
            System.out.printf("%s node added!\n", node.getMetadata().getName());
        }

        @Override
        public void onUpdate(V1Node oldNode, V1Node newNode) {
            System.out.printf("%s => %s node updated!\n", oldNode.getMetadata().getName(), newNode.getMetadata().getName());
        }

        @Override
        public void onDelete(V1Node node, boolean deletedFinalStateUnknown) {
            System.out.printf("%s node deleted!\n", node.getMetadata().getName());
        }
    });
    factory.startAllRegisteredInformers();
    V1Node nodeToCreate = new V1Node();
    V1ObjectMeta metadata = new V1ObjectMeta();
    metadata.setName("noxu");
    nodeToCreate.setMetadata(metadata);
    V1Node createdNode = coreV1Api.createNode(nodeToCreate, null, null, null, null);
    Thread.sleep(3000);
    Lister<V1Node> nodeLister = new Lister<V1Node>(nodeInformer.getIndexer());
    V1Node node = nodeLister.get("noxu");
    System.out.printf("noxu created! %s\n", node.getMetadata().getCreationTimestamp());
    factory.stopAllRegisteredInformers();
    Thread.sleep(3000);
    System.out.println("informer stopped..");
}
Also used : OkHttpClient(okhttp3.OkHttpClient) V1Node(io.kubernetes.client.openapi.models.V1Node) V1ObjectMeta(io.kubernetes.client.openapi.models.V1ObjectMeta) Lister(io.kubernetes.client.informer.cache.Lister) ApiClient(io.kubernetes.client.openapi.ApiClient) CallGeneratorParams(io.kubernetes.client.util.CallGeneratorParams) SharedInformerFactory(io.kubernetes.client.informer.SharedInformerFactory) CoreV1Api(io.kubernetes.client.openapi.apis.CoreV1Api)

Example 3 with V1Node

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

the class CoreV1Api method createNodeWithHttpInfo.

/**
 * create a Node
 *
 * @param body (required)
 * @param pretty If &#39;true&#39;, then the output is pretty printed. (optional)
 * @param dryRun When present, indicates that modifications should not be persisted. An invalid or
 *     unrecognized dryRun directive will result in an error response and no further processing of
 *     the request. Valid values are: - All: all dry run stages will be processed (optional)
 * @param fieldManager fieldManager is a name associated with the actor or entity that is making
 *     these changes. The value must be less than or 128 characters long, and only contain
 *     printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. (optional)
 * @param fieldValidation fieldValidation determines how the server should respond to
 *     unknown/duplicate fields in the object in the request. Introduced as alpha in 1.23, older
 *     servers or servers with the &#x60;ServerSideFieldValidation&#x60; feature disabled will
 *     discard valid values specified in this param and not perform any server side field
 *     validation. Valid values are: - Ignore: ignores unknown/duplicate fields. - Warn: responds
 *     with a warning for each unknown/duplicate field, but successfully serves the request. -
 *     Strict: fails the request on unknown/duplicate fields. (optional)
 * @return ApiResponse&lt;V1Node&gt;
 * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the
 *     response body
 * @http.response.details
 *     <table summary="Response Details" border="1">
 * <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
 * <tr><td> 200 </td><td> OK </td><td>  -  </td></tr>
 * <tr><td> 201 </td><td> Created </td><td>  -  </td></tr>
 * <tr><td> 202 </td><td> Accepted </td><td>  -  </td></tr>
 * <tr><td> 401 </td><td> Unauthorized </td><td>  -  </td></tr>
 * </table>
 */
public ApiResponse<V1Node> createNodeWithHttpInfo(V1Node body, String pretty, String dryRun, String fieldManager, String fieldValidation) throws ApiException {
    okhttp3.Call localVarCall = createNodeValidateBeforeCall(body, pretty, dryRun, fieldManager, fieldValidation, null);
    Type localVarReturnType = new TypeToken<V1Node>() {
    }.getType();
    return localVarApiClient.execute(localVarCall, localVarReturnType);
}
Also used : Type(java.lang.reflect.Type) V1Node(io.kubernetes.client.openapi.models.V1Node)

Example 4 with V1Node

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

the class CoreV1Api method replaceNodeAsync.

/**
 * (asynchronously) replace the specified Node
 *
 * @param name name of the Node (required)
 * @param body (required)
 * @param pretty If &#39;true&#39;, then the output is pretty printed. (optional)
 * @param dryRun When present, indicates that modifications should not be persisted. An invalid or
 *     unrecognized dryRun directive will result in an error response and no further processing of
 *     the request. Valid values are: - All: all dry run stages will be processed (optional)
 * @param fieldManager fieldManager is a name associated with the actor or entity that is making
 *     these changes. The value must be less than or 128 characters long, and only contain
 *     printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. (optional)
 * @param fieldValidation fieldValidation determines how the server should respond to
 *     unknown/duplicate fields in the object in the request. Introduced as alpha in 1.23, older
 *     servers or servers with the &#x60;ServerSideFieldValidation&#x60; feature disabled will
 *     discard valid values specified in this param and not perform any server side field
 *     validation. Valid values are: - Ignore: ignores unknown/duplicate fields. - Warn: responds
 *     with a warning for each unknown/duplicate field, but successfully serves the request. -
 *     Strict: fails the request on unknown/duplicate fields. (optional)
 * @param _callback The callback to be executed when the API call finishes
 * @return The request call
 * @throws ApiException If fail to process the API call, e.g. serializing the request body object
 * @http.response.details
 *     <table summary="Response Details" border="1">
 * <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
 * <tr><td> 200 </td><td> OK </td><td>  -  </td></tr>
 * <tr><td> 201 </td><td> Created </td><td>  -  </td></tr>
 * <tr><td> 401 </td><td> Unauthorized </td><td>  -  </td></tr>
 * </table>
 */
public okhttp3.Call replaceNodeAsync(String name, V1Node body, String pretty, String dryRun, String fieldManager, String fieldValidation, final ApiCallback<V1Node> _callback) throws ApiException {
    okhttp3.Call localVarCall = replaceNodeValidateBeforeCall(name, body, pretty, dryRun, fieldManager, fieldValidation, _callback);
    Type localVarReturnType = new TypeToken<V1Node>() {
    }.getType();
    localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback);
    return localVarCall;
}
Also used : Type(java.lang.reflect.Type) V1Node(io.kubernetes.client.openapi.models.V1Node)

Example 5 with V1Node

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

the class CoreV1Api method readNodeStatusWithHttpInfo.

/**
 * read status of the specified Node
 *
 * @param name name of the Node (required)
 * @param pretty If &#39;true&#39;, then the output is pretty printed. (optional)
 * @return ApiResponse&lt;V1Node&gt;
 * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the
 *     response body
 * @http.response.details
 *     <table summary="Response Details" border="1">
 * <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
 * <tr><td> 200 </td><td> OK </td><td>  -  </td></tr>
 * <tr><td> 401 </td><td> Unauthorized </td><td>  -  </td></tr>
 * </table>
 */
public ApiResponse<V1Node> readNodeStatusWithHttpInfo(String name, String pretty) throws ApiException {
    okhttp3.Call localVarCall = readNodeStatusValidateBeforeCall(name, pretty, null);
    Type localVarReturnType = new TypeToken<V1Node>() {
    }.getType();
    return localVarApiClient.execute(localVarCall, localVarReturnType);
}
Also used : Type(java.lang.reflect.Type) V1Node(io.kubernetes.client.openapi.models.V1Node)

Aggregations

V1Node (io.kubernetes.client.openapi.models.V1Node)29 Type (java.lang.reflect.Type)14 Test (org.junit.Test)8 CoreV1Api (io.kubernetes.client.openapi.apis.CoreV1Api)4 V1NodeList (io.kubernetes.client.openapi.models.V1NodeList)4 ApiClient (io.kubernetes.client.openapi.ApiClient)3 V1ObjectMeta (io.kubernetes.client.openapi.models.V1ObjectMeta)3 Pair (org.apache.commons.lang3.tuple.Pair)3 NodeMetrics (io.kubernetes.client.custom.NodeMetrics)2 PodMetrics (io.kubernetes.client.custom.PodMetrics)2 SharedInformerFactory (io.kubernetes.client.informer.SharedInformerFactory)2 Lister (io.kubernetes.client.informer.cache.Lister)2 V1Pod (io.kubernetes.client.openapi.models.V1Pod)2 CallGeneratorParams (io.kubernetes.client.util.CallGeneratorParams)2 ArrayList (java.util.ArrayList)2 ImmutablePair (org.apache.commons.lang3.tuple.ImmutablePair)2 JobMasterAPI (edu.iu.dsc.tws.proto.jobmaster.JobMasterAPI)1 Metrics (io.kubernetes.client.Metrics)1 ContainerMetrics (io.kubernetes.client.custom.ContainerMetrics)1 NodeMetricsList (io.kubernetes.client.custom.NodeMetricsList)1