如何使用 Kubernetes 的 Go 客户端观看一个服务上的事件。

huangapple go评论128阅读模式
英文:

How to watch events on a kubernetes service using its go client

问题

我希望在使用client-go时,每当Kubernetes上的服务发生更改时得到通知。

英文:

I would like to be informed when ever a service is changed on kubernetes using client-go.

答案1

得分: 20

可以这样完成:

package main

import (
	"fmt"
	"flag"
	"time"

	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/pkg/api/v1"
	"k8s.io/client-go/tools/clientcmd"
	"k8s.io/client-go/tools/cache"
	"k8s.io/client-go/pkg/fields"
)

var (
	kubeconfig = flag.String("kubeconfig", "./config", "kubeconfig 文件的绝对路径")
)

func main() {
	flag.Parse()
	config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
	if err != nil {
		panic(err.Error())
	}
	clientset, err := kubernetes.NewForConfig(config)
	if err != nil {
		panic(err.Error())
	}

	watchlist := cache.NewListWatchFromClient(clientset.Core().RESTClient(), "services", v1.NamespaceDefault,
		fields.Everything())
	_, controller := cache.NewInformer(
		watchlist,
		&v1.Service{},
		time.Second * 0,
		cache.ResourceEventHandlerFuncs{
			AddFunc: func(obj interface{}) {
				fmt.Printf("service added: %s \n", obj)
			},
			DeleteFunc: func(obj interface{}) {
				fmt.Printf("service deleted: %s \n", obj)
			},
			UpdateFunc:func(oldObj, newObj interface{}) {
				fmt.Printf("service changed \n")
			},
		},
	)
	stop := make(chan struct{})
	go controller.Run(stop)
	for{
		time.Sleep(time.Second)
	}
}

希望对你有所帮助!

英文:

this can be done like this:

package main

import (
	"fmt"
	"flag"
	"time"

	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/pkg/api/v1"
	"k8s.io/client-go/tools/clientcmd"
	"k8s.io/client-go/tools/cache"
	"k8s.io/client-go/pkg/fields"
)

var (
	kubeconfig = flag.String("kubeconfig", "./config", "absolute path to the kubeconfig file")
)

func main() {
    flag.Parse()
	config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
	if err != nil {
		panic(err.Error())
	}
	clientset, err := kubernetes.NewForConfig(config)
	if err != nil {
		panic(err.Error())
	}

	watchlist := cache.NewListWatchFromClient(clientset.Core().RESTClient(), "services", v1.NamespaceDefault,
		fields.Everything())
	_, controller := cache.NewInformer(
		watchlist,
		&v1.Service{},
		time.Second * 0,
		cache.ResourceEventHandlerFuncs{
			AddFunc: func(obj interface{}) {
				fmt.Printf("service added: %s \n", obj)
			},
			DeleteFunc: func(obj interface{}) {
				fmt.Printf("service deleted: %s \n", obj)
			},
			UpdateFunc:func(oldObj, newObj interface{}) {
				fmt.Printf("service changed \n")
			},
		},
	)
	stop := make(chan struct{})
	go controller.Run(stop)
	for{
		time.Sleep(time.Second)
	}
}

答案2

得分: 12

这是最新版本的client-go的用法示例,根据上面的代码。

package main

import (
	"fmt"
	"time"

	"github.com/golang/glog"

	"k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/fields"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/tools/cache"
	"k8s.io/client-go/tools/clientcmd"
)

func main() {
	config, err := clientcmd.BuildConfigFromFlags("", "")
	if err != nil {
		glog.Errorln(err)
	}
	clientset, err := kubernetes.NewForConfig(config)
	if err != nil {
		glog.Errorln(err)
	}

	watchlist := cache.NewListWatchFromClient(
		clientset.CoreV1().RESTClient(),
		string(v1.ResourceServices),
		v1.NamespaceAll,
		fields.Everything(),
	)
	_, controller := cache.NewInformer(
		watchlist,
		&v1.Service{},
		0,
		cache.ResourceEventHandlerFuncs{
			AddFunc: func(obj interface{}) {
				fmt.Printf("service added: %s \n", obj)
			},
			DeleteFunc: func(obj interface{}) {
				fmt.Printf("service deleted: %s \n", obj)
			},
			UpdateFunc: func(oldObj, newObj interface{}) {
				fmt.Printf("service changed \n")
			},
		},
	)
	stop := make(chan struct{})
	defer close(stop)
	go controller.Run(stop)
	for {
		time.Sleep(time.Second)
	}
}

以上是最新版本client-go的用法示例。

英文:

This is the latest version client-go's usage example. According the above code.

    package main

    import (
	    "fmt"
	    "time"

	     "github.com/golang/glog"

	     "k8s.io/api/core/v1"
	     "k8s.io/apimachinery/pkg/fields"
	     "k8s.io/client-go/kubernetes"
	     "k8s.io/client-go/tools/cache"
	     "k8s.io/client-go/tools/clientcmd"
    )

    func main() {
	    config, err := clientcmd.BuildConfigFromFlags("", "")
	    if err != nil {
	    	glog.Errorln(err)
	    }
	    clientset, err := kubernetes.NewForConfig(config)
	    if err != nil {
		    glog.Errorln(err)
	    }

	    watchlist := cache.NewListWatchFromClient(
		    clientset.CoreV1().RESTClient(),
		    string(v1.ResourceServices),
		    v1.NamespaceAll,
		    fields.Everything(),
	    )
	    _, controller := cache.NewInformer( // also take a look at NewSharedIndexInformer
		    watchlist,
		    &v1.Service{},
		    0, //Duration is int64
		    cache.ResourceEventHandlerFuncs{
			    AddFunc: func(obj interface{}) {
				    fmt.Printf("service added: %s \n", obj)
			    },
			    DeleteFunc: func(obj interface{}) {
				    fmt.Printf("service deleted: %s \n", obj)
			    },
			    UpdateFunc: func(oldObj, newObj interface{}) {
				    fmt.Printf("service changed \n")
			    },
		     },
	     )
	     // I found it in k8s scheduler module. Maybe it's help if you interested in.
	     //	serviceInformer := cache.NewSharedIndexInformer(watchlist, &v1.Service{}, 0, cache.Indexers{
	     //		cache.NamespaceIndex: cache.MetaNamespaceIndexFunc,
	     //	})
	     //	go serviceInformer.Run(stop)
	    stop := make(chan struct{})
	    defer close(stop)
     	go controller.Run(stop)
	    for {
		    time.Sleep(time.Second)
	    }
    }

答案3

得分: 9

这是一个使用SharedInformerFactory的简单示例。

package main

import (
    "fmt"
    "time"

    "github.com/golang/glog"

    kubeinformers "k8s.io/client-go/informers"
    "k8s.io/client-go/kubernetes"
    "k8s.io/client-go/tools/cache"
    "k8s.io/client-go/tools/clientcmd"
)

func main() {
    config, err := clientcmd.BuildConfigFromFlags("", "")
    if err != nil {
        glog.Errorln(err)
    }
    clientset, err := kubernetes.NewForConfig(config)
    if err != nil {
        glog.Errorln(err)
    }

    kubeInformerFactory := kubeinformers.NewSharedInformerFactory(clientset, time.Second*30)
    svcInformer := kubeInformerFactory.Core().V1().Services().Informer()

    svcInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{
        AddFunc: func(obj interface{}) {
            fmt.Printf("service added: %s \n", obj)
        },
        DeleteFunc: func(obj interface{}) {
            fmt.Printf("service deleted: %s \n", obj)
        },
        UpdateFunc: func(oldObj, newObj interface{}) {
            fmt.Printf("service changed: %s \n", newObj)
        },
    })

    stop := make(chan struct{})
    defer close(stop)
    kubeInformerFactory.Start(stop)
    for {
        time.Sleep(time.Second)
    }
}

希望对你有帮助!

英文:

This is a simple one using SharedInformerFactory.

package main
import (
"fmt"
"time"
"github.com/golang/glog"
kubeinformers "k8s.io/client-go/informers"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/tools/clientcmd"
)
func main() {
config, err := clientcmd.BuildConfigFromFlags("", "")
if err != nil {
glog.Errorln(err)
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
glog.Errorln(err)
}
kubeInformerFactory := kubeinformers.NewSharedInformerFactory(clientset, time.Second*30)
svcInformer := kubeInformerFactory.Core().V1().Services().Informer()
svcInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
fmt.Printf("service added: %s \n", obj)
},
DeleteFunc: func(obj interface{}) {
fmt.Printf("service deleted: %s \n", obj)
},
UpdateFunc: func(oldObj, newObj interface{}) {
fmt.Printf("service changed: %s \n", newObj)
},
},)
stop := make(chan struct{})
defer close(stop)
kubeInformerFactory.Start(stop)
for {
time.Sleep(time.Second)
}
}

答案4

得分: 9

package main

import (
    "fmt"
    "flag"
    "time"
    "log"

    "k8s.io/client-go/kubernetes"
    "k8s.io/client-go/pkg/api/v1"
    "k8s.io/client-go/tools/clientcmd"
    "k8s.io/client-go/tools/cache"
    "k8s.io/client-go/pkg/fields"
    metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    "k8s.io/apimachinery/pkg/watch"
)

var (
    kubeconfig = flag.String("kubeconfig", "./config", "kubeconfig文件的绝对路径")
)

func main() {
    flag.Parse()
    config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
    if err != nil {
        log.Fatal(err.Error())
    }
    clientset, err := kubernetes.NewForConfig(config)
    if err != nil {
        log.Fatal(err.Error())
    }

    watcher, err := client.CoreV1().Services(v1.NamespaceDefault,).Watch(metav1.ListOptions{})
    if err != nil {
        log.Fatal(err)
    }

    for event := range watcher.ResultChan() {
        svc := event.Object.(*v1.Service)

        switch event.Type {
        case watch.Added:
           fmt.Printf("Service %s/%s 添加", svc.ObjectMeta.Namespace, svc.ObjectMeta.Name)
        case watch.Modified:
           fmt.Printf("Service %s/%s 修改", svc.ObjectMeta.Namespace, svc.ObjectMeta.Name)
        case watch.Deleted:
           fmt.Printf("Service %s/%s 删除", svc.ObjectMeta.Namespace, svc.ObjectMeta.Name)
        }
    }

}

<details>
<summary>英文:</summary>

package main

import (
"fmt"
"flag"
"time"
"log"

&quot;k8s.io/client-go/kubernetes&quot;
&quot;k8s.io/client-go/pkg/api/v1&quot;
&quot;k8s.io/client-go/tools/clientcmd&quot;
&quot;k8s.io/client-go/tools/cache&quot;
&quot;k8s.io/client-go/pkg/fields&quot;
metav1 &quot;k8s.io/apimachinery/pkg/apis/meta/v1&quot;
&quot;k8s.io/apimachinery/pkg/watch&quot;

)

var (
kubeconfig = flag.String("kubeconfig", "./config", "absolute path to the kubeconfig file")
)

func main() {
flag.Parse()
config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
if err != nil {
log.Fatal(err.Error())
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
log.Fatal(err.Error())
}

watcher, err := client.CoreV1().Services(v1.NamespaceDefault,).Watch(metav1.ListOptions{})
if err != nil {
log.Fatal(err)
}
for event := range watcher.ResultChan() {
svc := event.Object.(*v1.Service)
switch event.Type {
case watch.Added:
fmt.Printf(&quot;Service %s/%s added&quot;, svc.ObjectMeta.Namespace, svc.ObjectMeta.Name)
case watch.Modified:
fmt.Printf(&quot;Service %s/%s modified&quot;, svc.ObjectMeta.Namespace, svc.ObjectMeta.Name)
case watch.Deleted:
fmt.Printf(&quot;Service %s/%s deleted&quot;, svc.ObjectMeta.Namespace, svc.ObjectMeta.Name)
}
}

}


</details>

huangapple
  • 本文由 发表于 2016年12月5日 21:24:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/40975307.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定