Java api 操作 kubernetes

x33g5p2x  于2022-02-28 转载在 Java  
字(8.5k)|赞(0)|评价(0)|浏览(602)

Java api 操作 kubernetes

一、api接口访问方式

授权方式

调用k8s使用rest api形式一个是安全的地址https:127.0.0.1:6443,这个地址需要有认证权限的,可以是token方式或者是证书,这个也是我一开始使用的方式,无奈没有办法知道token什么时候过期,但是目前实验只要K8s正常启动一直没有换token也还是可以使用
查看kubernetes的token

不授权方式

第二个方式是不安全的地址http😕/127.0.0.1:8008,就是说可以不用认证权限就可以直接访问K8s了,因为真的不知道token什么时候过期,2是k8s不稳定老是重装我就得需要换token

输入如下命令:

vim /etc/kubernetes/manifests/kube-apiserver.yaml

在下图的地方添加以下,写好以后保存退出,他就会重启稍微等一下我们就可以访问一下地址

- --enable-swagger-ui=true
- --insecure-bind-address=0.0.0.0
- --insecure-port=8008

我们就可以访问了

二、Java api 操作 k8s

<dependency>
            <groupId>io.kubernetes</groupId>
            <artifactId>client-java</artifactId>
            <version>12.0.0</version>
            <scope>compile</scope>
        </dependency>

k8s初始化

private static ApiClient getApiClient(){

        String master = "https://127.0.0.1:6443";
        String oauthToken = "eyJhbGciOiJSUzI1NiIsImtpZCI6InNRRi1VVFpmUE9nQ3VNc25kcVFXV29nVGZWN0hJX1N5WndHX1p4STc2a3cifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJrdWJlLXN5c3RlbSIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VjcmV0Lm5hbWUiOiJrOHMtdG9rZW4tN3pmajIiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlcnZpYdC5uYW1lIjoiazhzIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQudWlkIjoiNWVlZjQ0MDQtYWY5OS00NDE4LTk2YTctZWFmYzlkNDJhNmYxIiwic3ViIjoic3lzdGVtOnNlcnZpY2VhY2NvdW50Omt1YmUtc3lzdGVtOms4cyJ9.npRtUn7_AM0yPmdHdwN76CKlNOkc8sWJcOuhCKHT-o58oRvg5_kDfCIZyfhV0UjepkLhq1xzP_mHbbUu8_u5SnTbpFhqslOoKywXsI17oDOIQk44nXyRkrGzsM4xNKN9kov4fzSpQqhHNGfXIMA1D0WGD2nZzh2CMklVhVzbWDDnLGgzhzBr9WNDuyBVXlJc40Tz_B0aTurxZ1yZ2P34VSK_vXW8mWWZxfCSRSf6L2vyHfKwhA4ogoqopHANwOpE0O1Fz8q50kclcyxc9a-GD3nPzYISLnGbDAsuKD4qEAi6QhnXVDdUEf9XYvzTvkBeTvL8g4YSGZrQ";

        ApiClient apiClient = new ClientBuilder()
                //设置 k8s 服务所在 ip地址
                .setBasePath(master)
                //是否开启 ssl 验证
                .setVerifyingSsl(false)
                //插入访问 连接用的 Token
                .setAuthentication(new AccessTokenAuthentication(oauthToken))
                .build();
        io.kubernetes.client.openapi.Configuration.setDefaultApiClient(apiClient);
        return apiClient;
    }

创建命名空间

@RequestMapping("/create/namespace")
    public Map<String, String> testNamespace(V1Namespace namespace){
        Map<String, String> message = new HashMap<>();
        //初始化k8s
        ApiClient apiClient = getApiClient();
        CoreV1Api coreV1Api = new CoreV1Api(apiClient);
        try {
            V1Namespace result  = coreV1Api.createNamespace(namespace, null, null, null);
            message.put("success", "应用命名空间创建成功!");
        } catch (ApiException e) {
            if (e.getCode() == 409) {
                message.put("error", "命名空间已重复!");
            }
            if (e.getCode() == 200) {
                message.put("success", "应用命名空间创建成功!");
            }
            if (e.getCode() == 201) {
                message.put("error", "命名空间已重复!");
            }
            if (e.getCode() == 401) {
                message.put("error", "无权限操作!");
            }
            message.put("error", "应用命名空间创建失败!");
        }
       return message;
    }

创建命名空间的参数值

{
	"apiVersion":"v1",
	"kind":"Namespace",
	"metadata":{"name":"test-namespace","labels":{"name":"test-namespace"}}
}

创建Deployment应用

@Data
@AllArgsConstructor
@NoArgsConstructor
public class DeploymentDTO {
    private String metadata_name;
    private String metadata_namespace;
    private String labels_workLayer;
    private Integer spec_replicas;
    private String containers_name;
    private String containers_image;
    private String containers_imagePullPolicy;
    private String remark;
}
@PostMapping("/create/deployments")
    public Map<String, String> createDeployments(@RequestBody DeploymentDTO deploymentDTO){
        Map<String, String> messages = new HashMap<>();

        // 赋值操作
        V1Deployment deployment = new V1Deployment();
        deployment.setApiVersion("apps/v1");
        deployment.kind("Deployment");

        // 赋值metadata
        V1ObjectMeta objectMeta = new V1ObjectMeta();
        objectMeta.name(deploymentDTO.getMetadata_name());
        objectMeta.namespace(deploymentDTO.getMetadata_namespace());
        Map<String, String> labels = new HashMap<>();
        labels.put("app","nginx");
        objectMeta.labels(labels);

        // 赋值spec
        V1DeploymentSpec deploymentSpec = new V1DeploymentSpec();

        //赋值spec-selector
        V1LabelSelector selector = new V1LabelSelector();
        Map<String, String> matchLabels = new HashMap<>();
        matchLabels.put("app","nginx");
        selector.matchLabels(matchLabels);

        //赋值template
        V1PodTemplateSpec templateSpec = new V1PodTemplateSpec();
        V1ObjectMeta metadata = new V1ObjectMeta();
        metadata.labels(labels);
        templateSpec.metadata(metadata);

        // spec-Template下的Spec
        V1PodSpec podSpec = new V1PodSpec();
        // spec-Template-spec-container
        List<V1Container> listContainer = new ArrayList<>();
        V1Container container = new V1Container();
        container.setName(deploymentDTO.getContainers_name());
        container.setImage(deploymentDTO.getContainers_image());
        container.setImagePullPolicy(deploymentDTO.getContainers_imagePullPolicy());

        // spec-Template-spec-container-ports
        List<V1ContainerPort> ports = new ArrayList<>();
        V1ContainerPort v1ContainerPort = new V1ContainerPort();
        v1ContainerPort.setContainerPort(88);
        container.setPorts(ports);

        listContainer.add(container);
        podSpec.setContainers(listContainer);
        templateSpec.setSpec(podSpec);

        deploymentSpec.setReplicas(deploymentDTO.getSpec_replicas());
        deploymentSpec.setTemplate(templateSpec);
        deploymentSpec.setSelector(selector);
        deployment.setMetadata(objectMeta);
        deployment.setSpec(deploymentSpec);
        
        ApiClient client = getApiClient();
        AppsV1Api apiInstance = new AppsV1Api(client);
        try {
            V1Deployment result = apiInstance.createNamespacedDeployment(objectMeta.getNamespace(), deployment, null, null, null);
            messages.put("success", "工作负载创建成功!");
        } catch (ApiException e) {
            if (e.getCode() == 409) {
                messages.put("error", "工作负载创建已重复!");
            } else if (e.getCode() == 200) {
                messages.put("success", "工作负载创建成功!");
            } else if (e.getCode() == 201) {
                messages.put("error", "工作负载创建已重复!");
            } else if (e.getCode() == 401) {
                messages.put("error", "无权限操作!");
            } else {
                messages.put("error", "工作负载创建失败!");
            }
        }
        return messages;
    }

创建Deployment的参数值

{
	"metadata_name":"nginx-deployment",
	"metadata_namespace":"test-hl2",
	"labels_workLayer":"svc",
	"spec_replicas":3,
	"containers_name":"ngninx-test",
	"containers_image":"nginx:latest",
	"containers_imagePullPolicy":"IfNotPresent",
	"remark":"测试项目"
}

创建Service服务

@Data
@AllArgsConstructor
@NoArgsConstructor
public class ServiceDTO {
    private String metadata_name;
    private String metadata_namespace;
    private String labels_workLayer;
    private String spec_type;
    private Integer spec_ports_port;
    private Integer spec_ports_targetPort;
    private String spec_ports_protocol;
}
@PostMapping("/create/service")
    public Map<String, String> createService(@RequestBody ServiceDTO serviceDTO) {
        Map<String, String> message = new HashMap<>();
        ApiClient client = getApiClient();
        CoreV1Api apiInstance = new CoreV1Api(client);

        //赋值
        V1Service body = new V1Service();
        body.setApiVersion("v1");
        body.setKind("Service");

        V1ObjectMeta objectMeta = new V1ObjectMeta();
        objectMeta.setName(serviceDTO.getMetadata_name());
        objectMeta.setNamespace(serviceDTO.getMetadata_namespace());

        //赋值spec
        V1ServiceSpec serviceSpec = new V1ServiceSpec();
        //spec-type
        serviceSpec.setType(serviceDTO.getSpec_type());
        //spec-ports
        List<V1ServicePort> servicePorts = new ArrayList<>();
        V1ServicePort servicePort = new V1ServicePort();
        servicePort.setPort(serviceDTO.getSpec_ports_port());
        servicePort.setProtocol(serviceDTO.getSpec_ports_protocol());
        servicePort.setTargetPort(new IntOrString(serviceDTO.getSpec_ports_targetPort()));
        servicePorts.add(servicePort);
        serviceSpec.ports(servicePorts);

        // spec-selector
        Map<String, String> selector = new HashMap<>();
        selector.put("app","nginx");
        serviceSpec.setSelector(selector);

        body.setMetadata(objectMeta);
        body.setSpec(serviceSpec);
        
        try {
            V1Service result = apiInstance.createNamespacedService(serviceDTO.getMetadata_namespace(), body, null, null, null);
            message.put("success", "工作负载服务创建成功!");
        } catch (ApiException e) {
            if (e.getCode() == 409) {
                message.put("error", "工作负载服务创建已重复!");
            } else if (e.getCode() == 200) {
                message.put("success", "工作负载服务创建成功!");
            } else if (e.getCode() == 201) {
                message.put("error", "工作负载服务创建已重复!");
            } else if (e.getCode() == 401) {
                message.put("error", "无权限操作!");
            } else if (e.getCode() == 400) {
                message.put("error", "后台参数错误!");
            } else if (e.getCode() == 400) {
                message.put("error", "没有命名空间或没有Deployment!");
            } else {
                message.put("error", "工作负载服务创建失败!");
            }
        }
        return message;
    }
}

相关文章