如何使用它的go客户端观看kubernetes事件细节?



在 kubernetes 仪表板中,您可以查看命名空间的事件:例如"拉取镜像"你好世界",成功拉取镜像"你好世界"等

有没有办法使用 it's go 客户端获取所有这些事件?

多谢。

使用 NewInformer() 函数为特定类型的事件创建通知。

下面是一个最小示例(来源(:

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 := &amp
    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))
}

最新更新