Kubernetes官方java客戶端之六:OpenAPI基本操作


歡迎訪問我的GitHub

https://github.com/zq2599/blog_demos

內容:所有原創文章分類匯總及配套源碼,涉及Java、Docker、Kubernetes、DevOPS等;

概覽

  1. 本文是《Kubernetes官方java客戶端》系列的第六篇,以下提到的java客戶端都是指client-jar.jar
  2. 前文《Kubernetes官方java客戶端之五:proto基本操作 》已經提到,java客戶端的基本功能由兩個主要脈絡組成,第一個是proto,主要功能是使用ProtoClient類提供的增刪改查接口,這些接口用到的入參和返回對象所涉及到的java類,都是通過K8S的protobuf生成的;
  3. 除了使用ProtoClient對K8S資源進行增刪改查,還提供了另一種更強大的方式:OpenAPI,本章咱們就來一起學習OpenAPI相關的操作;

K8S的OpenAPI

  1. 先拋開java客戶端不提,咱們來看看K8S本身的OpenAPI,地址是:https://kubernetes.io/zh/docs/concepts/overview/kubernetes-api/ ,關鍵信息如下圖所示,可見K8S提供了OpenAPI規范:
    在這里插入圖片描述

  2. 如果您想查看當前K8S環境的OpenAPI規范,請打開K8S環境的/etc/kubernetes/manifests/kube-apiserver.yaml文件,增加下圖紅框中的內容:
    在這里插入圖片描述

  3. 修改完畢后請稍候,系統會根據文件的變化自動更新(千萬不要執行kubectl apply -f kube-apiserver.yaml,這會導致新建api-server的pod,由於端口占用而啟動失敗);

  4. 假設宿主機IP地址是192.168.50.135,那么在瀏覽器上訪問:http://192.168.50.135:8080/openapi/v2,就能得到所有OpenAPI信息如下圖:
    在這里插入圖片描述

  5. 上圖的原始數據沒有可讀性,復制到在線JSON格式化網站,得到的內容如下圖,例如查詢pod列表的API信息已經非常詳細了:
    在這里插入圖片描述

  6. 以上就是對K8S的OpenAPI簡介,接下來回到java客戶端本身,看看它提供了哪些OpenAPI相關的能力;

java客戶端的OpenAPI

  1. 打開java客戶端工程的源碼如下圖,紅框1就是和OpenAPI相關的子工程,提供服務的功能類都在紅框2的package中,也就是說,依靠紅框2中的API以及紅框3中的數據結構,我們可以完成大部分K8S資源控制相關的操作:
    在這里插入圖片描述

  2. 打開常用的CoreV1Api.java,如下圖紅框,頂部的注釋已經說明了一切:這些代碼都是工具生成的(至於如何生成就不在本文中討論了):
    在這里插入圖片描述

  3. 如果您下載了java客戶端源碼,可以在client-java-api這個子工程中看到完整的OpenAPI接口文檔:
    在這里插入圖片描述

  4. 前文《Kubernetes官方java客戶端之五:proto基本操作 》的代碼中,咱們嘗試過獲取pod列表,但是ProtoClient的已有API不支持提交更詳細的業務參數,此時選擇OpenAPI接口即可輸入詳細的業務參數,接口詳細信息可以在文檔中查到,還帶有完整的demo代碼,如下圖所示:
    在這里插入圖片描述

  5. 上圖中的listNamespacedPod接口有兩個重要參數:fieldSelectorlabelSelector,這是過濾用的,詳細的用法請參考K8S官方文檔,地址是:https://kubernetes.io/docs/concepts/overview/working-with-objects/ ,如下圖紅框:
    在這里插入圖片描述

  6. 弄清楚了K8S的OpenAPI規范,以及java客戶端依據此規范生成的API服務,還有詳細的接口文檔在手,可以編碼實戰了;

源碼下載

  1. 如果您不想編碼,可以在GitHub下載所有源碼,地址和鏈接信息如下表所示(https://github.com/zq2599/blog_demos):
名稱 鏈接 備注
項目主頁 https://github.com/zq2599/blog_demos 該項目在GitHub上的主頁
git倉庫地址(https) https://github.com/zq2599/blog_demos.git 該項目源碼的倉庫地址,https協議
git倉庫地址(ssh) git@github.com:zq2599/blog_demos.git 該項目源碼的倉庫地址,ssh協議
  1. 這個git項目中有多個文件夾,本章的應用在kubernetesclient文件夾下,如下圖紅框所示:
    在這里插入圖片描述

開始編碼

  1. 打開《Kubernetes官方java客戶端之一:准備 》中創建的kubernetesclient工程,在里面新建子工程openapi,其pom.xml內容如下,要注意的是spring-boot-starter-json已經被排除,因此序列化工具會變為Gson(原本默認是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. 新增OpenAPIDemoApplication.java,這是新工程的引導類,也有兩個web接口,一個創建namespace,另一個按照namespace查詢pod列表,關鍵位置已添加了注釋,就不多贅述了:
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. OpenAPIDemoApplication運行起來,先測試創建namespace的服務,在瀏覽器訪問:http://localhost:8080/openapi/createnamespace/dddeeefff ,瀏覽器返回信息如下圖:
    在這里插入圖片描述

  2. SSH登錄K8S主機,執行命令查看namespace,如下圖紅框,已經創建成功:

在這里插入圖片描述

  1. 再試試Pod列表,地址是 :http://localhost:8080/openapi/pods/kube-system ,如下圖:
    在這里插入圖片描述
  • 至此,OpenAPI接口的實踐就完成了,現在已將java客戶端的最基本的功能都實踐過了,接下來的文章咱們將開始學習精彩的高級功能;

你不孤單,欣宸原創一路相伴

  1. Java系列
  2. Spring系列
  3. Docker系列
  4. kubernetes系列
  5. 數據庫+中間件系列
  6. DevOps系列

歡迎關注公眾號:程序員欣宸

微信搜索「程序員欣宸」,我是欣宸,期待與您一同暢游Java世界...
https://github.com/zq2599/blog_demos


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM