k8s java-client node、deployment、pod、service常用api实现

node
package com.k8s.k8sapi.controller;

import com.k8s.k8sapi.common.config.K8sInit;
import com.k8s.k8sapi.common.utils.ResultUtil;
import io.kubernetes.client.openapi.ApiClient;
import io.kubernetes.client.openapi.ApiException;
import io.kubernetes.client.openapi.apis.CoreV1Api;
import io.kubernetes.client.openapi.models.V1Node;
import io.kubernetes.client.openapi.models.V1NodeList;
import io.kubernetes.client.openapi.models.V1NodeStatus;
import io.kubernetes.client.openapi.models.V1ObjectMeta;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;


@RestController
@RequestMapping("api/v1/node")
public class NodeController {

    @Resource
    private K8sInit k8sInit;

    /**
     * 查看所有node节点信息
     * @return
     */
    @GetMapping("/listNode")
    public ArrayList<String> listNode() {
        ArrayList<String> res = new ArrayList<>();
        CoreV1Api apiInstance = new CoreV1Api(k8sInit.getConnection());
        String pretty = "true";

        try {
            V1NodeList result = apiInstance.listNode(pretty, true, null,
                    null, null, null, null, null, null);
            for(V1Node pod : result.getItems()) {
                String name = pod.getMetadata().getName();
                if(name != null) {
                    res.add(name);
                }
            }
        } catch (ApiException e) {
            System.err.println("Exception when calling CoreV1Api#listNode");
            System.err.println("Status code: " + e.getCode());
            System.err.println("Reason: " + e.getResponseBody());
            System.err.println("Response headers: " + e.getResponseHeaders());
            e.printStackTrace();
        }
        return res;
    }

    /**
     * 根据name查看指定node信息
     * @param name
     * @return
     */
    @GetMapping("/readNode/{name}")
    public ResultUtil readNode(@PathVariable String name) {
        CoreV1Api apiInstance = new CoreV1Api(k8sInit.getConnection());
        V1Node result;
        try {
            result = apiInstance.readNode(name, "true", true, true);
            System.out.println(result);
        } catch (ApiException e) {
            System.err.println("Exception when calling CoreV1Api#readNode");
            System.err.println("Status code: " + e.getCode());
            System.err.println("Reason: " + e.getResponseBody());
            System.err.println("Response headers: " + e.getResponseHeaders());
            e.printStackTrace();
            return ResultUtil.error(String.valueOf(e.getCode()), e.getMessage());
        }
        return ResultUtil.success(result);
    }


    @GetMapping("/replaceNode/{name}")
    public ResultUtil replaceNode(@PathVariable String name) {
        CoreV1Api apiInstance = new CoreV1Api(k8sInit.getConnection());
        V1Node body = new V1Node();
        V1ObjectMeta v1ObjectMeta = new V1ObjectMeta();

        v1ObjectMeta.setName(name);
        body.setMetadata(v1ObjectMeta);
        V1Node result;
        try {
            result = apiInstance.replaceNode(name, body, "true", null, null);
            System.out.println(result);
        } catch (ApiException e) {
            System.err.println("Exception when calling CoreV1Api#replaceNodeStatus");
            System.err.println("Status code: " + e.getCode());
            System.err.println("Reason: " + e.getResponseBody());
            System.err.println("Response headers: " + e.getResponseHeaders());
            e.printStackTrace();
            return ResultUtil.error(String.valueOf(e.getCode()), e.getMessage());
        }
        return ResultUtil.success(result);
    }


    @GetMapping("/createNode")
    public ResultUtil createNode() {
        CoreV1Api apiInstance = new CoreV1Api(k8sInit.getConnection());
        V1Node body = new V1Node();
        body.setApiVersion("v1");
        // body.setKind();
        V1Node result;
        try {
            result = apiInstance.createNode(body, "true", null, null);
            System.out.println(result);
        } catch (ApiException e) {
            System.err.println("Exception when calling CoreV1Api#createNode");
            System.err.println("Status code: " + e.getCode());
            System.err.println("Reason: " + e.getResponseBody());
            System.err.println("Response headers: " + e.getResponseHeaders());
            e.printStackTrace();
            return ResultUtil.error(String.valueOf(e.getCode()), e.getMessage());
        }
        return ResultUtil.success(result);
    }

}

deployment
package com.k8s.k8sapi.controller;

import com.google.gson.Gson;
import com.k8s.k8sapi.common.config.K8sInit;
import com.k8s.k8sapi.common.utils.ResultUtil;
import com.k8s.k8sapi.model.dto.DeploymentDTO;
import com.k8s.k8sapi.service.IDeploymentService;
import io.kubernetes.client.custom.V1Patch;
import io.kubernetes.client.openapi.ApiException;
import io.kubernetes.client.openapi.apis.AppsV1Api;
import io.kubernetes.client.openapi.models.*;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("api/v1/deployment")
public class DeploymentController {

    @Resource
    private K8sInit k8sInit;

    @Resource
    IDeploymentService IDeploymentService;

    /**
     * 根据name、namespace查看deployment的信息
     * https://blog.csdn.net/dfBeautifulLive/article/details/103735048?spm=1001.2014.3001.5501
     * @param namespace
     * @param name
     * @return
     */
    @GetMapping("/readNamespacedDeployment/{name}/{namespace}")
    public ResultUtil readNamespacedDeployment(@PathVariable String name,
                                                @PathVariable String namespace) {
        Gson gson = new Gson();
        AppsV1Api apiInstance = new AppsV1Api(k8sInit.getConnection());
        Map<String, Object> res = new HashMap<>();
        V1Deployment result;
        try {
            result = apiInstance.readNamespacedDeployment(name, namespace, "true", null, null);
        } catch (ApiException e) {
            return ResultUtil.error(String.valueOf(e.getCode()), e.getMessage());
        }
        return ResultUtil.success(gson.toJson(result));
    }

    /**
     * 根据name、namespace修改deployment的副本数
     * https://blog.csdn.net/dfBeautifulLive/article/details/103735048?spm=1001.2014.3001.5501
     * @param namespace
     * @param name
     * @param replicas
     * @return
     */
    @GetMapping("/patchNamespacedDeployment")
    public ResultUtil patchNamespacedDeployment(String namespace, String name, int replicas) {
        AppsV1Api apiInstance = new AppsV1Api(k8sInit.getConnection());
        // 更新副本的json串
        String jsonPatchStr = "[{\"op\":\"replace\",\"path\":\"/spec/replicas\", \"value\": " + replicas + " }]";
        V1Patch body = new V1Patch(jsonPatchStr);
        V1Deployment v1Deployment;
        try {
            v1Deployment = apiInstance.patchNamespacedDeployment(name,
                    namespace,
                    body,
                    null,
                    null,
                    null,
                    null);
        } catch (ApiException e) {
            // e.printStackTrace();
            return ResultUtil.error(String.valueOf(e.getCode()), e.getMessage());
        }
        return ResultUtil.success(v1Deployment);
    }


    /**
     * 列出所有namespace下的deployment
     * @return
     */
    @GetMapping("/listDeploymentForAllNamespaces")
    public ResultUtil listDeploymentForAllNamespaces() {
        Gson gson = new Gson();
        AppsV1Api apiInstance = new AppsV1Api(k8sInit.getConnection().setReadTimeout(10000).setConnectTimeout(10000));
        V1DeploymentList result;
        try {
            result = apiInstance.listDeploymentForAllNamespaces(null, null, null,
                    null, null, "true", null, null, null);
        } catch (ApiException e) {
            e.printStackTrace();
            return ResultUtil.error(String.valueOf(e.getCode()), e.getMessage());
        }
        return ResultUtil.success(gson.toJson(result));
    }

    /**
     * 列出指定namespace下的deployment
     * @param namespace
     * @return
     */
    @GetMapping("/listNamespacedDeployment/{namespace}")
    public ResultUtil listNamespacedDeployment(@PathVariable String namespace) {
        Gson gson = new Gson();
        AppsV1Api apiInstance = new AppsV1Api(k8sInit.getConnection());
        V1DeploymentList result;
        try {
            result = apiInstance.listNamespacedDeployment(namespace, "true", null,
                    null, null, null, null, null, null, null);
        } catch (ApiException e) {
            return ResultUtil.error(String.valueOf(e.getCode()), e.getMessage());
        }
        return ResultUtil.success(gson.toJson(result));
    }


    /**
     * 创建一个deployment
     * @param deploymentDTO
     * @return
     */
    @PostMapping("/createNamespacedDeployment")
    public ResultUtil createNamespacedDeployment(@RequestBody DeploymentDTO deploymentDTO) {
        Gson gson = new Gson();
        AppsV1Api apiInstance = new AppsV1Api(k8sInit.getConnection());
        V1Deployment result;

        // 使用对象封装deployment
        V1Deployment body = IDeploymentService.createV1Deployment(deploymentDTO);

        try {
            result = apiInstance.createNamespacedDeployment(
                    deploymentDTO.getNamespace(),
                    body,
                    "true",
                    null,
                    null);
            System.out.println(result);
        } catch (ApiException e) {
            return ResultUtil.error(String.valueOf(e.getCode()), e.getMessage());
        }
        return ResultUtil.success(gson.toJson(result));
    }

}

@Service
public class DeploymentServiceImpl implements IDeploymentService {
    @Resource
    private K8sInit k8sInit;

    @Override
    public V1Deployment createV1Deployment(DeploymentDTO deploymentDTO) {
        // labels
        Map<String,String> matchLabels = new HashMap<>();
        matchLabels.put("app", deploymentDTO.getMetadataLabelsApp());

        // ports
        List<V1ContainerPort> portList = new ArrayList<>();
        V1ContainerPort port = new V1ContainerPort();
        port.setName(deploymentDTO.getPortName());
        port.setContainerPort(81);
        portList.add(port);

        V1Deployment body =  new V1DeploymentBuilder()
                .withApiVersion("apps/v1")
                .withKind("Deployment")
                .withNewMetadata()
                .withName(deploymentDTO.getDeploymentName())
                .withNamespace(deploymentDTO.getNamespace())
                .endMetadata()
                .withNewSpec()
                .withReplicas(deploymentDTO.getReplicas())
                .withNewSelector()
                .withMatchLabels(matchLabels)
                .endSelector()
                .withNewTemplate()
                .withNewMetadata()
                .withLabels(matchLabels)
                .endMetadata()
                .withNewSpec()
                .withContainers(
                        new V1Container()
                                .name(deploymentDTO.getMetadataLabelsApp())
                                .image(deploymentDTO.getImage())
                                .imagePullPolicy("IfNotPresent")
                                .ports(portList)
                )
                .endSpec()
                .endTemplate()
                .endSpec()
                .build();
        return body;
    }
}
pod
package com.k8s.k8sapi.controller;

import com.k8s.k8sapi.common.config.K8sInit;
import com.k8s.k8sapi.common.utils.ResultUtil;
import com.k8s.k8sapi.model.dto.V1PodDTO;
import com.k8s.k8sapi.service.IPodService;
import io.kubernetes.client.custom.V1Patch;
import io.kubernetes.client.openapi.ApiException;
import io.kubernetes.client.openapi.apis.CoreV1Api;
import io.kubernetes.client.openapi.models.*;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("api/v1/pod")
public class PodController {

    @Resource
    private K8sInit k8sInit;

    @Resource
    IPodService podService;

    /**
     * 列出namespace下的所有pod
     * @param namespace
     * @return
     */
    @GetMapping("/listNamespacedPod/{namespace}")
    public ArrayList<String> listNamespacedPod(@PathVariable String namespace) {
        ArrayList<String> res = new ArrayList<>();
        CoreV1Api apiInstance = new CoreV1Api(k8sInit.getConnection());
        String pretty = "true";
        V1PodList result = new V1PodList();
        try {
            result = apiInstance.listNamespacedPod(namespace, pretty, true,
                    null, null, null, null, null,
                    null, null);
            for(V1Pod pod : result.getItems()) {
                String name = pod.getMetadata().getName();
                if(name != null) {
                    res.add(name);
                }
            }
        } catch (ApiException e) {
            System.err.println("---Exception when calling CoreV1Api#listNamespacedPod");
            System.err.println("---Status code: " + e.getCode());
            System.err.println("---Reason: " + e.getResponseBody());
            System.err.println("---Response headers: " + e.getResponseHeaders());
            e.printStackTrace();

        }

        return res;
    }

    /**
     * 在指定的namespace下创建pod
     * {
     * 	"apiVersion":"v1",
     * 	"kind":"Pod",
     * 	"metadata":{
     *         "name":"memory-demo"
     *     },
     *     "spec": {
     *         "containers": {
     *             "name": "memory-demo-ctr",
     *             "image": "polinux/stress",
     *             "command": ["/bin/bash", "-ce", "tail -f /dev/null"],
     *             "imagePullPolicy": "IfNotPresent"
     *         }
     *     }
     * }
     * @param namespace 指定namespace
     * @param v1PodDTO
     * @return
     */
    @PostMapping("/createNamespacePod/{namespace}")
    public ResultUtil createNamespacePod(@PathVariable String namespace,
                                         @RequestBody V1PodDTO v1PodDTO) {
        CoreV1Api apiInstance = new CoreV1Api(k8sInit.getConnection());
        // System.out.println(v1PodDTO);
        V1Pod body = podService.creatV1Pod(v1PodDTO);
        V1Pod result;
        try {
            result = apiInstance.createNamespacedPod(namespace, body, "true", null, null);
            System.out.println(result);
        } catch (ApiException e) {
            return ResultUtil.error(String.valueOf(e.getCode()), e.getMessage());
        }
        return ResultUtil.success(result);
    }

    /**
     * 根据name、namespace删除pod TODO:能删除,会报错 Expected a string but was BEGIN_OBJECT
     * @param name
     * @param namespace
     * @return
     */
    @GetMapping("/deleteNamespacePod")
    public ResultUtil deleteNamespacePod(@RequestParam String name, @RequestParam String namespace) {
        CoreV1Api apiInstance = new CoreV1Api(k8sInit.getConnection());
        V1DeleteOptions body = new V1DeleteOptions();
        V1Status result;
        try {
            apiInstance.deleteNamespacedPod(name, namespace, "true", null, null,
                    null, null, null);
        } catch (ApiException e) {
            return ResultUtil.error(String.valueOf(e.getCode()), e.getMessage());
        }
        return ResultUtil.success();
    }

    /**
     * 查询指定pod
     * @param name pod的名字
     * @param namespace 命名空间
     * @return
     */
    @GetMapping("/readNamespacedPod")
    public ResultUtil readNamespacedPod(@RequestParam String name,
                                        @RequestParam String namespace) {
        CoreV1Api apiInstance = new CoreV1Api(k8sInit.getConnection());
        V1Pod result;
        try {
            result = apiInstance.readNamespacedPod(name, namespace, "true", true, true);
        } catch (ApiException e) {
            return ResultUtil.error(String.valueOf(e.getCode()), e.getMessage());
        }
        return ResultUtil.success(result);
    }


    @GetMapping("/patchNamespacedPod/{name}/{namespace}")
    public ResultUtil patchNamespacedPod(@PathVariable(required = true) String name,
                                         @PathVariable(required = true) String namespace) {
                                         // @RequestBody V1PatchDTO v1PatchDTO) {
        CoreV1Api apiInstance = new CoreV1Api(k8sInit.getConnection());
        // V1Patch body = podService.createV1Patch(v1PatchDTO);
        String str = "[{\"op\": \"replace\", \"path\": \"/metadata/labels/test\", \"value\":\"false\"}]";
        V1Patch body = new V1Patch(str);
        V1Pod result;
        try {
            result = apiInstance.patchNamespacedPod(name, namespace, body, "true", null, null, true);

        } catch (ApiException e) {
            e.printStackTrace();
            return ResultUtil.error(String.valueOf(e.getCode()), e.getMessage());
        }
        return ResultUtil.success(result);
    }

    @GetMapping("/replaceNode/{name}")
    public ResultUtil replaceNode(@PathVariable String name){
        CoreV1Api apiInstance = new CoreV1Api(k8sInit.getConnection());
        V1Node result;
        Map<String, String> labels = new HashMap<>();
        labels.put("name", "memory-demo-label");
        V1Node body = new V1Node().
                kind("Pod").apiVersion("v1").metadata(
                        new V1ObjectMeta().name("memory-demo").labels(labels));
        try {
            result = apiInstance.replaceNode(name, body, "true", null, null);
            System.out.println(result);
        } catch (ApiException e) {
            System.err.println("Exception when calling CoreV1Api#replaceNode");
            System.err.println("Status code: " + e.getCode());
            System.err.println("Reason: " + e.getResponseBody());
            System.err.println("Response headers: " + e.getResponseHeaders());
            e.printStackTrace();
            return ResultUtil.error(String.valueOf(e.getCode()), e.getMessage());
        }
        return ResultUtil.success(result);
    }


}

service
package com.k8s.k8sapi.controller;

import com.google.gson.Gson;
import com.k8s.k8sapi.common.config.K8sInit;
import com.k8s.k8sapi.common.utils.ResultUtil;
import com.k8s.k8sapi.model.dto.ServiceDTO;
import com.k8s.k8sapi.service.IServiceService;
import io.kubernetes.client.openapi.ApiClient;
import io.kubernetes.client.openapi.ApiException;
import io.kubernetes.client.openapi.apis.CoreV1Api;
import io.kubernetes.client.openapi.models.V1DeleteOptions;
import io.kubernetes.client.openapi.models.V1Service;
import io.kubernetes.client.openapi.models.V1ServiceList;
import io.kubernetes.client.openapi.models.V1Status;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;

@RestController
@RequestMapping("api/v1/service")
public class ServiceController {

    @Resource
    private K8sInit k8sInit;

    @Resource
    private IServiceService serviceService;

    /**
     * 获取指定namespace下的service
     * @param namespace
     * @return
     */
    @GetMapping("/listNamespacedService/{namespace}")
    public ArrayList<String> listNamespacedService(@PathVariable String namespace) {
        ArrayList<String> res = new ArrayList<>();
        ApiClient client = k8sInit.getConnection();
        CoreV1Api apiInstance = new CoreV1Api(client);
        String pretty = "true";
        try {
            V1ServiceList result = apiInstance.listNamespacedService(namespace, pretty, true,
                    null, null, null, null, null, null, null);
            for(V1Service service : result.getItems()) {
                String name = service.getMetadata().getName();
                if(name != null) {
                    res.add(name);
                }
            }
        } catch (ApiException e) {
            System.err.println("Exception when calling CoreV1Api#listNamespacedService");
            System.err.println("Status code: " + e.getCode());
            System.err.println("Reason: " + e.getResponseBody());
            System.err.println("Response headers: " + e.getResponseHeaders());
            e.printStackTrace();
        }
        return res;
    }

    /**
     * 获取全部service
     * @return
     */
    @GetMapping("/listServiceForAllNamespaces")
    public ArrayList<String> listServiceForAllNamespaces() {
        ArrayList<String> res = new ArrayList<>();
        CoreV1Api apiInstance = new CoreV1Api(k8sInit.getConnection());
        String pretty = "true";
        try {
            V1ServiceList result = apiInstance.listServiceForAllNamespaces(true, null,
                    null, null, null, pretty, null, null, null);
            for(V1Service service : result.getItems()) {
                String name = service.getMetadata().getName();
                if(name != null) {
                    res.add(name);
                }
            }
        } catch (ApiException e) {
            System.err.println("Exception when calling CoreV1Api#listServiceForAllNamespaces");
            System.err.println("Status code: " + e.getCode());
            System.err.println("Reason: " + e.getResponseBody());
            System.err.println("Response headers: " + e.getResponseHeaders());
            e.printStackTrace();
        }
        return res;
    }

    /**
     * 获取指定service信息
     * @param name
     * @param namespace
     * @return
     */
    @GetMapping("/readNamespacedService/{name}/{namespace}")
    public ResultUtil readNamespacedService(@PathVariable String name,
                                            @PathVariable String namespace) {
        Gson gson = new Gson();
        CoreV1Api apiInstance = new CoreV1Api(k8sInit.getConnection());
        V1Service result;
        try {
            result = apiInstance.readNamespacedService(name, namespace, null, true, true);
        } catch (ApiException e) {
            return ResultUtil.error(String.valueOf(e.getCode()), e.getMessage());
        }
        return ResultUtil.success(gson.toJson(result));
    }

    /**
     * 创建一个service
     * @param namespace
     * @param serviceDTO
     * @return
     */
    @PostMapping("/createNamespacedService/{namespace}")
    public ResultUtil createNamespacedService(@PathVariable String namespace,
                                              @RequestBody ServiceDTO serviceDTO) {
        Gson gson = new Gson();
        CoreV1Api apiInstance = new CoreV1Api(k8sInit.getConnection());
        V1Service result;
        V1Service body = serviceService.createV1Service(serviceDTO);
        try {
            result = apiInstance.createNamespacedService(namespace, body, "true", null, null);
            System.out.println(result);
        } catch (ApiException e) {
            return ResultUtil.error(String.valueOf(e.getCode()), e.getMessage());
        }
        return ResultUtil.success(gson.toJson(result));
    }

    /**
     * 删除service
     * @param name service的名称
     * @param namespace 命名空间
     * @return
     */
    @GetMapping("/deleteNamespacedService/{name}/{namespace}")
    public ResultUtil deleteNamespacedService(@PathVariable String name,
                                              @PathVariable String namespace) {
        Gson gson = new Gson();
        CoreV1Api apiInstance = new CoreV1Api(k8sInit.getConnection());
        V1DeleteOptions body = new V1DeleteOptions();
        V1Status result;
        try {
            result = apiInstance.deleteNamespacedService(name, namespace, "true", null,
                    null, true, null, body);
            System.out.println(result);
        } catch (ApiException e) {
            return ResultUtil.error(String.valueOf(e.getCode()), e.getMessage());
        }
        return ResultUtil.success(gson.toJson(result));
    }
}


  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,您可以按照以下步骤使用Kubernetes的java-client实现Deployment的部署及更新操作: 1. 引入Kubernetes的java-client依赖,例如: ``` <dependency> <groupId>io.kubernetes</groupId> <artifactId>client-java</artifactId> <version>11.0.0</version> </dependency> ``` 2. 创建Kubernetes的Client对象,例如: ``` ApiClient client = Config.defaultClient(); client.setBasePath("https://your_kubernetes_api_server_url"); ``` 3. 创建Deployment对象,例如: ``` Deployment deployment = new DeploymentBuilder() .withNewMetadata().withName("your_deployment_name").endMetadata() .withNewSpec() .withReplicas(3) .withNewTemplate() .withNewMetadata().withLabels(Collections.singletonMap("app", "your_app_name")).endMetadata() .withNewSpec() .addNewContainer() .withName("your_container_name") .withImage("your_container_image") .addNewPort().withContainerPort(80).endPort() .endContainer() .endSpec() .endTemplate() .withNewSelector().withMatchLabels(Collections.singletonMap("app", "your_app_name")).endSelector() .endSpec() .build(); ``` 4. 使用Client对象创建或更新Deployment对象,例如: ``` AppsV1Api api = new AppsV1Api(client); // 创建Deployment api.createNamespacedDeployment("your_namespace", deployment, null, null, null); // 更新Deployment api.replaceNamespacedDeployment("your_deployment_name", "your_namespace", deployment, null, null, null); ``` 以上就是使用Kubernetes的java-client实现Deployment的部署及更新操作的简单示例,您可以根据自己的实际需求进行调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值