一、詳解各模塊
. ├── discovery # 定義DsicoveryClient客戶端。作用是用於發現k8s所支持GVR(Group, Version, Resources)。 ├── dynamic # 定義DynamicClient客戶端。可以用於訪問k8s Resources(如: Pod, Deploy...),也可以訪問用戶自定義資源(即: CRD)。 ├── informers # k8s中各種Resources的Informer機制的實現。 ├── kubernetes # 定義ClientSet客戶端。它只能用於訪問k8s Resources。每一種資源(如: Pod等)都可以看成是一個客端,而ClientSet是多個客戶端的集合,它對RestClient進行了封裝,引入了對Resources和Version的管理。通常來說ClientSet是client-gen來自動生成的。 ├── listers # 提供對Resources的獲取功能。對於Get()和List()而言,listers提供給二者的數據都是從緩存中讀取的。 ├── pkg ├── plugin # 提供第三方插件。如:GCP, OpenStack等。 ├── rest # 定義RestClient,實現了Restful的API。同時會支持Protobuf和Json格式數據。 ├── scale # 定義ScalClient。用於Deploy, RS, RC等的擴/縮容。 ├── tools # 定義諸如SharedInformer、Reflector、DealtFIFO和Indexer等常用工具。實現client查詢和緩存機制,減少client與api-server請求次數,減少api-server的壓力。 ├── transport └── util # 提供諸如WorkQueue、Certificate等常用方法。
二、代碼示例:
package main
import (
"context"
"flag"
"fmt"
"path/filepath"
"time"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/util/homedir"
)
func main() {
var kubeconfig *string
fmt.Println(homedir.HomeDir())
if home := homedir.HomeDir(); home != "" {
kubeconfig = flag.String("kubeconfig", filepath.Join(home, ".kube", "config"), "(optional) absolute path to the kubeconfig file")
} else {
kubeconfig = flag.String("kubeconfig", "~/.kube/config", "absolute path to the kubeconfig file")
}
flag.Parse()
// use the current context in kubeconfig
config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
if err != nil {
panic(err.Error())
}
// create the clientset
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
panic(err.Error())
}
for {
pods, err := clientset.CoreV1().Pods("").List(context.TODO(), metav1.ListOptions{})
if err != nil {
panic(err.Error())
}
fmt.Printf("There are %d pods in the cluster\n", len(pods.Items))
// Examples for error handling:
// - Use helper functions like e.g. errors.IsNotFound()
// - And/or cast to StatusError and use its properties like e.g. ErrStatus.Message
namespace := "default"
pod := "example-xxxxx"
if _, err = clientset.CoreV1().Pods(namespace).Get(context.TODO(), pod, metav1.GetOptions{}); err != nil {
if errors.IsNotFound(err) {
fmt.Printf("Pod %s in namespace %s not found\n", pod, namespace)
}
}else {
fmt.Printf("Found pod %s in namespace %s\n", pod, namespace)
}
time.Sleep(5 * time.Second)
}
}
列出pods的單項
fmt.Println(pods.Items[1].Name)
fmt.Println(pods.Items[1].CreationTimestamp)
fmt.Println(pods.Items[1].Labels)
fmt.Println(pods.Items[1].Namespace)
fmt.Println(pods.Items[1].Status.HostIP)
fmt.Println(pods.Items[1].Status.PodIP)
fmt.Println(pods.Items[1].Status.StartTime)
fmt.Println(pods.Items[1].Status.Phase) //狀態
fmt.Println(pods.Items[1].Status.ContainerStatuses[0].RestartCount) //重啟次數
fmt.Println(pods.Items[1].Status.ContainerStatuses[0].Image) //獲取重啟時間
//獲取NODE
fmt.Println("##################")
nodes, err := clientset.CoreV1().Nodes().List(metav1.ListOptions{})
fmt.Println(nodes.Items[0].Name)
fmt.Println(nodes.Items[0].CreationTimestamp) //加入集群時間
fmt.Println(nodes.Items[0].Status.NodeInfo)
fmt.Println(nodes.Items[0].Status.Conditions[len(nodes.Items[0].Status.Conditions)-1].Type)
fmt.Println(nodes.Items[0].Status.Allocatable.Memory().String())
獲取所有deployment
deployment,err:=clientset.AppsV1().Deployments("default").List(context.TODO(),metav1.ListOptions{})
if err !=nil{
panic(err.Error())
}
for idx,deploy:=range deployment.Items{
fmt.Printf("%d-%s\n",idx,deploy.Name)
}
