package main
import (
"context"
"fmt"
"k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
)
func main() {
// uses the current context in kubeconfig
// path-to-kubeconfig -- for example, /root/.kube/config
config, err := clientcmd.BuildConfigFromFlags("", "C:\\Users\\HJW\\.kube\\config")
if err!= nil{
panic(err)
}
// creates the clientset
clientset, err := kubernetes.NewForConfig(config)
if err!= nil{
panic(err)
}
// access the API to list pods
pods, err := clientset.CoreV1().Pods("").List(context.TODO(), v1.ListOptions{})
if err!= nil{
panic(err)
}
fmt.Printf("There are %d pods in the cluster\n", len(pods.Items))
for _, d := range pods.Items{
fmt.Printf("namespace:%v \t name:%v \t statu:%+v \n", d.Namespace,d.Name,d.Status.Phase)
}
}
这个代码的作用就是把第一篇文章中得到的9个pod的具体信息展现出来。
下面我们来整一下K8S的informer机制,K8S组件之间的通信都是通过HTTP协议,全部通过informer机制进行消息的传递和同步。
下面简单整个例子,写个代码,主要作用是监控我电脑里面的K8S环境的POD的创建,更新与删除。
package main
import (
"context"
"fmt"
"github.com/labstack/gommon/log"
"k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/informers"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/tools/clientcmd"
"time"
)
func main() {
// uses the current context in kubeconfig
// path-to-kubeconfig -- for example, /root/.kube/config
config, err := clientcmd.BuildConfigFromFlags("", "C:\\Users\\HJW\\.kube\\config")
if err!= nil{
panic(err)
}
// creates the clientset
clientset, err := kubernetes.NewForConfig(config)
if err!= nil{
panic(err)
}
stopCh := make(chan struct{})
defer close(stopCh)
sharedInformers := informers.NewSharedInformerFactory(clientset,time.Minute)
informer := sharedInformers.Core().V1().Pods().Informer()
// access the API to list pods
pods, err := clientset.CoreV1().Pods("").List(context.TODO(), v1.ListOptions{})
if err!= nil{
panic(err)
}
fmt.Printf("There are %d pods in the cluster\n", len(pods.Items))
for _, d := range pods.Items{
fmt.Printf("namespace:%v \t name:%v \t statu:%+v \n", d.Namespace,d.Name,d.Status.Phase)
}
informer.AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
mObj := obj.(v1.Object)
log.Printf("New Pod Added to Stror: %s",mObj.GetName())
},
UpdateFunc: func(oldObj, newObj interface{}) {
oObj := oldObj.(v1.Object)
nObj := newObj.(v1.Object)
log.Printf("%s Pod Updated to %s", oObj.GetName(),nObj.GetName())
},
DeleteFunc: func(obj interface{}) {
mObj := obj.(v1.Object)
log.Printf("Pod Delete from Store: %s",mObj.GetName())
},
})
informer.Run(stopCh)
}
stopch对象的作用是在程序退出之前提前通知informer退出,因为informer是一直在运行的。写完代码之后我们运行,运行之后可以看到这个
代码返回了原来环境里面就存在的9个pod的信息,因为刚运行,所以informer机制把这几个pod都识别成刚创建的,然后每隔一分钟,同步一下,之后就是同步信息不断循环打印。那我们现在试一下新建一个pod。因为我是WIN10系统,使用bash命令有很多不方便,我也不想VIM一个新的YAML文件。那我打开git bash这个软件,这样就可以使用bash命令了,然后把API Server的代理打开。
然后使用API Server直接创建一个pod
$ curl http://localhost:8080/api/v1/namespaces/default/pods -H "Content-Type:application/
json" -X POST -d '{
"apiVersion": "v1",
"kind": "Pod",
"metadata": {
"name": "examplepod"
},
"spec": {
"containers": [
{
"name": "examplepod-container",
"image": "busybox",
"imagePullPolicy": "IfNotPresent",
"command": [
"sh",
"-c"
],
"args": [
"echo \"Hello Kubernetes!\"; sleep 3600"
]
}
]
}
}'
这里注意一下,在bash里面要把他们写成一行
curl http://localhost:8080/api/v1/namespaces/default/pods -H "Content-Type:application/json" -X POST -d '{"apiVersion": "v1","kind": "Pod","metadata": {"name": "examplepod"},"spec": {"containers": [{"name": "examplepod-container","image": "busybox","imagePullPolicy": "IfNotPresent","command": ["sh","-c"],"args": ["echo \"Hello Kubernetes!\"; sleep 3600"]}]}}'
然后就创建好了
这时候我们在用kubectl get pods -A查看环境中的pod数量
多了一个examplepod,这也是我们创建的,好,然后看goland里面返回的,可以看到,已经监控到这个pod的创建,并且更新了。
然后我们再使用
curl http://localhost:8080/api/v1/namespaces/default/pods/examplepod -X DELETE
这个命令删除创建的pod
bash会返回删除时间,然后我们再查询pod
pod就从runing变成了终止状态,最后被删除,然后goland里面也有对应的删除信息返回。