在kubernetes仪表板中,您可以查看命名空间的事件:例如" 拉动图像" hello-world",成功拉动图像" hello-world"等。
有没有办法使用它的客户端来获取所有这些事件?
非常感谢。
答案 0 :(得分:1)
使用NewInformer()
功能为特定类型的事件创建通知。
以下是最小示例(source):
import (
"fmt"
"log"
"net/http"
"time"
"k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/client/cache"
"k8s.io/kubernetes/pkg/client/restclient"
client "k8s.io/kubernetes/pkg/client/unversioned"
"k8s.io/kubernetes/pkg/fields"
"k8s.io/kubernetes/pkg/util/wait"
)
func podCreated(obj interface{}) {
pod := obj.(*api.Pod)
fmt.Println("Pod created: " + pod.ObjectMeta.Name)
}
func podDeleted(obj interface{}) {
pod := obj.(*api.Pod)
fmt.Println("Pod deleted: " + pod.ObjectMeta.Name)
}
func watchPods(client *client.Client, store cache.Store) cache.Store {
//Define what we want to look for (Pods)
watchlist := cache.NewListWatchFromClient(client, "pods", api.NamespaceAll, fields.Everything())
resyncPeriod := 30 * time.Minute
//Setup an informer to call functions when the watchlist changes
eStore, eController := framework.NewInformer(
watchlist,
&api.Pod{},
resyncPeriod,
framework.ResourceEventHandlerFuncs{
AddFunc: podCreated,
DeleteFunc: podDeleted,
},
)
//Run the controller as a goroutine
go eController.Run(wait.NeverStop)
return eStore
}
func main() {
//Configure cluster info
config := &
restclient.Config{
Host: "https://xxx.yyy.zzz:443",
Username: "kube",
Password: "supersecretpw",
Insecure: true,
}
//Create a new client to interact with cluster and freak if it doesn't work
kubeClient, err := client.New(config)
if err != nil {
log.Fatalln("Client not created sucessfully:", err)
}
//Create a cache to store Pods
var podsStore cache.Store
//Watch for Pods
podsStore = watchPods(kubeClient, podsStore)
//Keep alive
log.Fatal(http.ListenAndServe(":8080", nil))
}