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

歡迎訪問我的GitHub

https://github.com/zq2599/blog_demos

內(nèi)容:所有原創(chuàng)文章分類匯總及配套源碼,涉及Java、Docker、Kubernetes、DevOPS等;

概覽

  1. 本文是《Kubernetes官方java客戶端》系列的第六篇,以下提到的<font color="blue">java客戶端</font>都是指<font color="red">client-jar.jar</font>;
  2. 前文《Kubernetes官方java客戶端之五:proto基本操作 》已經(jīng)提到,java客戶端的基本功能由兩個主要脈絡組成,第一個是<font color="blue">proto</font>,主要功能是使用<font color="blue">ProtoClient</font>類提供的增刪改查接口,這些接口用到的入?yún)⒑头祷貙ο笏婕暗降膉ava類,都是通過K8S的protobuf生成的;
  3. 除了使用ProtoClient對K8S資源進行增刪改查,還提供了另一種更強大的方式:OpenAPI,本章咱們就來一起學習OpenAPI相關的操作;

K8S的OpenAPI

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

    在這里插入圖片描述

  2. 如果您想查看當前K8S環(huán)境的OpenAPI規(guī)范,請打開K8S環(huán)境的/etc/kubernetes/manifests/kube-apiserver.yaml文件,增加下圖紅框中的內(nèi)容:


    在這里插入圖片描述
  3. 修改完畢后請稍候,系統(tǒng)會根據(jù)文件的變化自動更新(<font color="red">千萬不要執(zhí)行kubectl apply -f kube-apiserver.yaml</font>,這會導致新建api-server的pod,由于端口占用而啟動失?。?

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

    在這里插入圖片描述

  5. 上圖的原始數(shù)據(jù)沒有可讀性,復制到在線JSON格式化網(wǎng)站,得到的內(nèi)容如下圖,例如查詢pod列表的API信息已經(jīng)非常詳細了:


    在這里插入圖片描述
  6. 以上就是對K8S的OpenAPI簡介,接下來回到<font color="blue">java客戶端</font>本身,看看它提供了哪些OpenAPI相關的能力;

java客戶端的OpenAPI

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


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


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


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

    在這里插入圖片描述

  5. 上圖中的<font color="blue">listNamespacedPod</font>接口有兩個重要參數(shù):<font color="red">fieldSelector</font>和<font color="red">labelSelector</font>,這是過濾用的,詳細的用法請參考K8S官方文檔,地址是:https://kubernetes.io/docs/concepts/overview/working-with-objects/ ,如下圖紅框:

    在這里插入圖片描述

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

源碼下載

  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協(xié)議
git倉庫地址(ssh) git@github.com:zq2599/blog_demos.git 該項目源碼的倉庫地址,ssh協(xié)議
  1. 這個git項目中有多個文件夾,本章的應用在<font color="blue">kubernetesclient</font>文件夾下,如下圖紅框所示:


    在這里插入圖片描述

開始編碼

  1. 打開《Kubernetes官方java客戶端之一:準備 》中創(chuàng)建的<font color="blue">kubernetesclient</font>工程,在里面新建子工程<font color="red">openapi</font>,其pom.xml內(nèi)容如下,要注意的是spring-boot-starter-json已經(jīng)被排除,因此序列化工具會變?yōu)镚son(原本默認是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接口,一個創(chuàng)建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作為入?yún)?chuàng)建的client對象,可以訪問到K8S的API Server
        ApiClient client = ClientBuilder
                .kubeconfig(KubeConfig.loadKubeConfig(new FileReader(kubeConfigPath)))
                .build();

        // 創(chuàng)建操作類
        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;

        // 訂閱事件相關的參數(shù),這里用不上
        Boolean allowWatchBookmarks = false;

        // 連續(xù)查找的標志,類似于翻頁
        String _continue = null;

        //  字段選擇器
        String fieldSelector = "status.phase=Running";

        // 根據(jù)標簽過濾
        // 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. 將<font color="blue">OpenAPIDemoApplication</font>運行起來,先測試創(chuàng)建<font color="blue">namespace</font>的服務,在瀏覽器訪問:http://localhost:8080/openapi/createnamespace/dddeeefff ,瀏覽器返回信息如下圖:

    在這里插入圖片描述

  2. SSH登錄K8S主機,執(zhí)行命令查看namespace,如下圖紅框,已經(jīng)創(chuàng)建成功:

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

你不孤單,欣宸原創(chuàng)一路相伴

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

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

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

?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容