Kubernetes official java client six: OpenAPI basic operation

Welcome to my GitHub

https://github.com/zq2599/blog_demos
content: classification summary of all original articles and supporting source code, involving Java, Docker, Kubernetes, DevOPS, etc.;

Overview

  1. This article is the sixth in the "Kubernetes official java client" series. The java clients mentioned below all refer to client-jar.jar ;
  2. As mentioned in the previous article "Kubernetes Official Java Client Five: Basic Proto Operations" , the basic functions of the java client consist of two main contexts. The first is proto . The main function is to use the addition, deletion, modification, and check interface provided by the ProtoClient class. These The java classes involved in the input parameters and return objects used by the interface are all generated by K8S protobuf;
  3. In addition to using ProtoClient to add, delete, modify and check K8S resources, it also provides another more powerful way: OpenAPI. In this chapter, let's learn about OpenAPI related operations;

K8S OpenAPI

  1. Putting aside the java client first, let’s take a look at the OpenAPI of K8S itself, the address is: https://kubernetes.io/zh/docs/concepts/overview/kubernetes-api/, the key information is shown in the figure below, visible K8S provides OpenAPI specifications:
    Insert picture description here

  2. If you want to view the OpenAPI specification of the current K8S environment, please open the /etc/kubernetes/manifests/kube-apiserver.yaml file of the K8S environment and add the content in the red box below:
    Insert picture description here

  3. Please wait a moment after the modification is completed, the system will automatically update according to the changes in the file ( do not execute kubectl apply -f kube-apiserver.yaml , which will cause the newly created api-server pod to fail to start due to port occupation);

  4. Assuming that the host's IP address is 192.168.50.135, then visit on the browser: http://192.168.50.135:8080/openapi/v2, you can get all the OpenAPI information as shown below:
    Insert picture description here

  5. The original data in the above figure is not readable. Copy it to the online JSON formatting website. The content obtained is as shown in the figure below. For example, the API information for querying the pod list is very detailed:
    Insert picture description here

  6. The above is an introduction to the OpenAPI of K8S. Next, return to the java client itself to see which OpenAPI-related capabilities it provides;

OpenAPI for java client

  1. Open the source code of the java client project as shown in the figure below. Red box 1 is the sub-project related to OpenAPI. The function classes that provide services are in the package of red box 2, that is to say, rely on the API in red box 2 and red box 3. In the data structure, we can complete most of the operations related to K8S resource control:
    Insert picture description here

  2. Open the commonly used CoreV1Api.java , as shown in the red box in the figure below. The comments at the top have explained everything: these codes are generated by tools (how to generate them is not discussed in this article):
    Insert picture description here

  3. If you download the java client source code, you can see the complete OpenAPI interface document in the client-java-api sub-project:
    Insert picture description here

  4. In the code of "Kubernetes Official Java Client Part Five: Basic Proto Operation" , we tried to get the pod list, but the existing API of ProtoClient does not support the submission of more detailed business parameters. At this time, select the OpenAPI interface to enter the detailed The business parameters and interface details can be found in the document, along with the complete demo code, as shown in the figure below:
    Insert picture description here

  5. The listNamespacedPod interface in the above figure has two important parameters: fieldSelector and labelSelector , which are used for filtering. For detailed usage, please refer to the official K8S documentation. The address is: https://kubernetes.io/docs/concepts/overview/working- with-objects/, the red box in the following figure:
    Insert picture description here

  6. I figured out the OpenAPI specification of K8S, and the API service generated by the java client according to this specification, and there are detailed interface documents in hand, which can be coded for actual combat;

Source download

  1. If you don't want to code, you can download all the source code on GitHub. The address and link information are shown in the following table (https://github.com/zq2599/blog_demos):
name link Remarks
Project homepage https://github.com/zq2599/blog_demos The project's homepage on GitHub
git warehouse address (https) https://github.com/zq2599/blog_demos.git The warehouse address of the project source code, https protocol
git warehouse address (ssh) [email protected]:zq2599/blog_demos.git The warehouse address of the source code of the project, ssh protocol
  1. There are multiple folders in this git project. The application of this chapter is under the kubernetesclient folder, as shown in the red box below:
    Insert picture description here

Start coding

  1. Open the kubernetesclient project created in "One of the Official Java Clients of Kubernetes: Preparation" , and create a new sub-project openapi in it . Its pom.xml content is as follows. Note that spring-boot-starter-json has been excluded, so it is serialized The tool will become Gson (the original default is jackson):
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>com.bolingcavalry</groupId>
        <artifactId>kubernetesclient</artifactId>
        <version>1.0-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>

    <groupId>com.bolingcavalry</groupId>
    <artifactId>openapi</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>openapi</name>
    <description>Demo project for openapi client</description>
    <packaging>jar</packaging>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-json</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>io.kubernetes</groupId>
            <artifactId>client-java</artifactId>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.3.0.RELEASE</version>
            </plugin>
        </plugins>
    </build>

</project>
  1. Added OpenAPIDemoApplication.java, which is the guide class of the new project. There are also two web interfaces, one creates a namespace, and the other queries the pod list according to the namespace. The key position has been commented, so I won’t go into details:
package com.bolingcavalry.openapi;

import com.google.gson.GsonBuilder;
import io.kubernetes.client.openapi.ApiClient;
import io.kubernetes.client.openapi.ApiException;
import io.kubernetes.client.openapi.Configuration;
import io.kubernetes.client.openapi.apis.CoreV1Api;
import io.kubernetes.client.openapi.models.V1Namespace;
import io.kubernetes.client.openapi.models.V1NamespaceBuilder;
import io.kubernetes.client.openapi.models.V1PodList;
import io.kubernetes.client.util.ClientBuilder;
import io.kubernetes.client.util.KubeConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.io.FileReader;

@SpringBootApplication
@RestController
@Slf4j
public class OpenAPIDemoApplication {
    
    

    public static void main(String[] args) {
    
    
        SpringApplication.run(OpenAPIDemoApplication.class, args);
    }

    /**
     * 默认的全局设置
     * @return
     * @throws Exception
     */
    @PostConstruct
    private void setDefaultApiClient() throws Exception {
    
    
        // 存放K8S的config文件的全路径
        String kubeConfigPath = "/Users/zhaoqin/temp/202007/05/config";
        // 以config作为入参创建的client对象,可以访问到K8S的API Server
        ApiClient client = ClientBuilder
                .kubeconfig(KubeConfig.loadKubeConfig(new FileReader(kubeConfigPath)))
                .build();

        // 创建操作类
        Configuration.setDefaultApiClient(client);
    }

    @RequestMapping(value = "/openapi/createnamespace/{namespace}", method = RequestMethod.GET)
    public V1Namespace createnamespace(@PathVariable("namespace") String namespace) throws Exception {
    
    

        CoreV1Api coreV1Api = new CoreV1Api();

        V1Namespace v1Namespace = new V1NamespaceBuilder()
                .withNewMetadata()
                .withName(namespace)
                .endMetadata()
                .build();

        V1Namespace ns = coreV1Api.createNamespace(v1Namespace, null, null, null);

        // 使用Gson将集合对象序列化成JSON,在日志中打印出来
        log.info("ns info \n{}", new GsonBuilder().setPrettyPrinting().create().toJson(ns));

        return ns;
    }


    @RequestMapping(value = "/openapi/pods/{namespace}", method = RequestMethod.GET)
    public V1PodList pods(@PathVariable("namespace") String namespace) throws ApiException {
    
    

        CoreV1Api apiInstance = new CoreV1Api();

        // String | If 'true', then the output is pretty printed.
        String pretty = null;

        // 订阅事件相关的参数,这里用不上
        Boolean allowWatchBookmarks = false;

        // 连续查找的标志,类似于翻页
        String _continue = null;

        //  字段选择器
        String fieldSelector = "status.phase=Running";

        // 根据标签过滤
        // String labelSelector = "component=kube-apiserver";
        String labelSelector = null;

        Integer limit = null;
        String resourceVersion = null;
        Integer timeoutSeconds = null;
        Boolean watch = false;

        V1PodList v1PodList = apiInstance.listNamespacedPod(namespace,
                pretty,
                allowWatchBookmarks,
                _continue,
                fieldSelector,
                labelSelector,
                limit,
                resourceVersion,
                timeoutSeconds,
                watch);

        // 使用Gson将集合对象序列化成JSON,在日志中打印出来
        log.info("pod info \n{}", new GsonBuilder().setPrettyPrinting().create().toJson(v1PodList));

        return v1PodList;
    }

}
  1. The OpenAPIDemoApplication up and running, test creation namespace of the service, access the browser: http: // localhost: 8080 / openapi / createnamespace / dddeeefff, the browser returns the information as shown below:
    Insert picture description here

  2. Log in to the K8S host via SSH, execute the command to view the namespace, as shown in the red box in the figure below, it has been created successfully:
    Insert picture description here

  3. Try the Pod list again, the address is: http://localhost:8080/openapi/pods/kube-system, as shown below:
    Insert picture description here

  • At this point, the practice of the OpenAPI interface is completed. Now that the most basic functions of the java client have been practiced, we will start to learn the wonderful advanced functions in the next article;

Guess you like

Origin blog.csdn.net/boling_cavalry/article/details/107574722