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));
    }
}


Logo

开源、云原生的融合云平台

更多推荐