Kubernetes fabric8 JavaAPI

wanchen發表於2020-05-21

Kubernetes fabric8 JavaAPI

一、依賴準備

<dependency>
	<groupId>io.fabric8</groupId>
	<artifactId>kubernetes-client</artifactId>
	<version>4.9.0</version>
</dependency>
下列展示程式碼中可能包含演示需要的依賴包,需要手動匯入。全文手動原創,非其他部落格及官方轉載。

二、程式碼例子及分析

1.客戶端的建立

​ Kubernetes 的資源預設是對內部是可見並可以訪問的,我們可以通過以下方式去訪問Kubernetes 獲取我們想要的資源。

  1. 對於Kubernetes 可以通過 JavaAPI 通過安全證照檔案、Token或admin.conf配置外部訪問
  2. 同樣也可以配置這些配置檔案通過HTTP訪問apiService訪問
  3. 內部也可以通過kube-proxy將內部資料暴露出來進行訪問的方式。
JavaAPI訪問

​ 1.1 通過安全證照訪問

需要安全證照檔案:apiserver-kubelet-client.crt、apiserver-kubelet-client.key、ca.crt

//建立 Config 用於建立 Client
Config config = new ConfigBuilder()
                    .withMasterUrl("ip")
                    .withCaCertData("ca.crt內容")
                    .withClientCertData("apiserver-kubelet-client.crt內容")
                    .withClientKeyData("apiserver-kubelet-client.key內容")
                    .build();
// 建立Client
KubernetesClient kubernetesClient = new DefaultKubernetesClient(config);

​ 1.2 通過配置檔案訪問

需要配置檔案:admin.conf

config = Config.fromKubeconfig("admin.conf內容");
KubernetesClient kubernetesClient = new DefaultKubernetesClient(config);

​ 1.3 kube-proxy 配置後通過 HTTP 直接訪問

首先在伺服器中開啟kube-proxy代理暴露8080埠:nohup kubectl proxy --port=8080 &

config = new ConfigBuilder().withMasterUrl("http://127.0.0.1:8080").build();
KubernetesClient kubernetesClient = new DefaultKubernetesClient(config);
//通過http訪問k8s中的路徑資源
HttpClient httpClient = HttpClientBuilder.create().build();

HttpGet httpGet = new HttpGet("http://127.0.0.1:8080/apis/devices.kubeedge.io/v1alpha1/devices");
		HttpResponse response = null;
		response = httpClient.execute(httpGet);
		HttpEntity responseEntity = response.getEntity();
		StatusLine statusLine = response.getStatusLine();
		int code = statusLine.getStatusCode();
		String result = EntityUtils.toString(responseEntity);

​ 1.4 http瀏覽器直接訪問K8S資源的,這裡暫不講解。

2.訪問操作pod、nodeSpace等基礎資源
//檢視Pod
MixedOperation<Pod, PodList, DoneablePod, PodResource<Pod, DoneablePod>> operation  = client.pods();
//建立Pod,獲取資源處理類,在傳入組裝號的Pod類
NonNamespaceOperation pods =client.pods().inNamespace("default");
//配置Pod,還可以通過 pod 類組裝,想要執行 這裡的引數是不夠的,僅作演示
Pod pod1 =new PodBuilder().withNewMetadata().withName("pod1").withNamespace("default").and().build();
pods.create(pod1);
//刪除同上
pods.delete(pod1);
3.訪問操作複雜管理器Deployment控制器
import io.fabric8.kubernetes.api.model.*;
import io.fabric8.kubernetes.api.model.apps.Deployment;
import io.fabric8.kubernetes.api.model.apps.DeploymentSpec;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wanchen.chen
 * @ClassName K8sDeploymentConf
 * @Despriction: 用於組合 Deployment
 * @date 2020/5/17 23:40
 * @Version 1.0
 **/
public class K8sDeploymentConf {

    /**
     *
     * @param appName
     * @param image
     * @param nodeName
     * @return
     */
    public static Deployment getDepandDeployment(String appName,String image,String nodeName){
        //引數傳遞
        String appGroup = "appGroup";
        //引數
        Map<String,String> labels = new HashMap<String,String>();
        labels.put("app",appGroup);
        Map<String,String> nodeSelector = new HashMap<String,String>();
        nodeSelector.put("name",nodeName);
        //mataData 資料組裝
        ObjectMeta mataData = new ObjectMeta();
        mataData.setName(appName);
        mataData.setLabels(labels);
        //映象設定
        Container container = new Container();
        container.setName(appName);
        container.setImage(image);
        container.setImagePullPolicy("IfNotPresent");
        SecurityContext sc = new SecurityContext();
        sc.setPrivileged(true);
        container.setSecurityContext(sc);
        List<Container> containers = new ArrayList<>();
        containers.add(container);
        //Spec 資料組裝
        //1.selector
        LabelSelector ls =new LabelSelector();
        ls.setMatchLabels(labels);
        //2.template
        ObjectMeta empMataData = new ObjectMeta();
        empMataData.setLabels(labels);
        PodSpec pods = new PodSpec();
        pods.setHostNetwork(true);
        pods.setNodeSelector(nodeSelector);
        pods.setContainers(containers);
        //2.2 組裝
        PodTemplateSpec pt = new PodTemplateSpec();
        pt.setMetadata(empMataData);
        pt.setSpec(pods);
        //3.spec 組合
        DeploymentSpec ds = new DeploymentSpec();
        ds.setReplicas(1);
        ds.setSelector(ls);
        ds.setTemplate(pt);
        //Deployment 設定
        Deployment deployment =new Deployment();
        deployment.setApiVersion("apps/v1");
        deployment.setKind("Deployment");
        deployment.setMetadata(mataData);
        deployment.setSpec(ds);
        return deployment;
    }

}

Deployment操作:

//將基礎Client轉換為AppsAPIGroupClient,用於操作deployment
AppsAPIGroupClient oclient =client.adapt(AppsAPIGroupClient.class);
MixedOperation<Deployment, DeploymentList, DoneableDeployment, RollableScalableResource<Deployment, DoneableDeployment>> operation1
                =oclient.deployments();
//將資源轉換為JSON 檢視
DeploymentList deploymentList =operation1.list();
List<Deployment> deployments = deploymentList.getItems();
JSONArray jsonArray=JSON.parseArray(JSON.toJSONString(deployments));
//建立Deployment,返回建立好的Deployment檔案
oclient.deployments().create(K8sDeploymentConf.getDepandDeployment("appName","image","nodeName"));
//刪除同上,返回結果為boolean型別資料
oclient.deployments().delete(K8sDeploymentConf.getDepandDeployment("appName","image","nodeName"));

三、部落格參考及持續更新

感謝以下部落格作業的辛苦創作,參考部落格:

https://www.jianshu.com/p/6bce2c2d1853

https://blog.csdn.net/Ay_Ly/article/details/90404445

相關文章