client-go的使用及源码分析
1. client-go简介
1.1 client-go说明
1.2 示例代码
git clone https://github.com/huweihuang/client-go.git
cd client-go
#保证本地HOME目录有配置kubernetes集群的配置文件
go run client-go.gopackage main
import (
"flag"
"fmt"
"os"
"path/filepath"
"time"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
)
func main() {
var kubeconfig *string
if home := homeDir(); home != "" {
kubeconfig = flag.String("kubeconfig", filepath.Join(home, ".kube", "config"), "(optional) absolute path to the kubeconfig file")
} else {
kubeconfig = flag.String("kubeconfig", "", "absolute path to the kubeconfig file")
}
flag.Parse()
// uses the current context in kubeconfig
config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
if err != nil {
panic(err.Error())
}
// creates the clientset
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
panic(err.Error())
}
for {
pods, err := clientset.CoreV1().Pods("").List(metav1.ListOptions{})
if err != nil {
panic(err.Error())
}
fmt.Printf("There are %d pods in the cluster\n", len(pods.Items))
time.Sleep(10 * time.Second)
}
}
func homeDir() string {
if h := os.Getenv("HOME"); h != "" {
return h
}
return os.Getenv("USERPROFILE") // windows
}1.3 运行结果
2. client-go源码分析
2.1 kubeconfig
2.2 rest.config
2.3 clientset
2.3.1 NewForConfig
2.3.2 clientset的结构体
2.3.3 clientset.Interface
2.4 CoreV1Client
2.4.1 corev1.NewForConfig
2.4.2 CoreV1Client结构体
2.4.3 CoreV1Interface
2.4.4 PodsGetter
2.5 RESTClient
2.5.1 rest.RESTClientFor
2.5.2 NewRESTClient
2.5.3 RESTClient结构体
2.5.4 RESTClient.Interface
2.6 总结
3. client-go对k8s资源的调用
3.1 deployment
3.2 service
3.3 ingress
3.4 replicaSet
3.5 pod
3.6 statefulset
最后更新于