基于WEB的K8S调度仿真评价平台设计2-informer监控pod资源

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里面也有对应的删除信息返回。
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值