Skip to content

Instantly share code, notes, and snippets.

@agonzalezro
Last active July 14, 2017 09:30
Show Gist options
  • Save agonzalezro/532b39bad74831b21ae88690ac9f3f1a to your computer and use it in GitHub Desktop.
Save agonzalezro/532b39bad74831b21ae88690ac9f3f1a to your computer and use it in GitHub Desktop.
go run watchers.go -kubeconfig ~/.kube/config
package main
import (
"flag"
"fmt"
"log"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/pkg/api/v1"
"k8s.io/client-go/pkg/watch"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
)
var config *rest.Config
func buildConfig(kubeconfig string) (*rest.Config, error) {
if kubeconfig != "" {
return clientcmd.BuildConfigFromFlags("", kubeconfig)
}
return rest.InClusterConfig()
}
func main() {
kubeconfig := flag.String("f", "", "Path to a kube config (usually: ~/.kube/config). Only required if out-of-cluster.")
flag.Parse()
config, err := buildConfig(*kubeconfig)
if err != nil {
log.Fatal(err)
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
log.Fatal(err)
}
eventsCh := make(chan watch.Event, 1)
nsWatcher, err := clientset.Core().Namespaces().Watch(v1.ListOptions{})
if err != nil {
log.Fatal(err)
}
nsEventsCh := nsWatcher.ResultChan()
nodesWatcher, err := clientset.Core().Nodes().Watch(v1.ListOptions{})
if err != nil {
log.Fatal(err)
}
nodesEventsCh := nodesWatcher.ResultChan()
podsWatcher, err := clientset.Core().Pods("").Watch(v1.ListOptions{})
if err != nil {
log.Fatal(err)
}
podsEventsCh := podsWatcher.ResultChan()
secretsWatcher, err := clientset.Core().Secrets("").Watch(v1.ListOptions{})
if err != nil {
log.Fatal(err)
}
secretsEventsCh := secretsWatcher.ResultChan()
serviceWatcher, err := clientset.Core().Services("").Watch(v1.ListOptions{})
if err != nil {
log.Fatal(err)
}
serviceEventsCh := serviceWatcher.ResultChan()
eventsWatcher, err := clientset.Core().Events("").Watch(v1.ListOptions{})
if err != nil {
log.Fatal(err)
}
evEventsCh := eventsWatcher.ResultChan()
go func(podsEventsCh, secretsEventsCh, nsEventsCh, serviceEventsCh, evEventsCh, nodesEventsCh <-chan watch.Event) {
for {
select {
case event := <-evEventsCh:
eventsCh <- event
case event := <-podsEventsCh:
eventsCh <- event
case event := <-serviceEventsCh:
eventsCh <- event
case event := <-secretsEventsCh:
eventsCh <- event
case event := <-nsEventsCh:
eventsCh <- event
}
}
}(podsEventsCh, secretsEventsCh, nsEventsCh, serviceEventsCh, evEventsCh, nodesEventsCh)
for {
e := <-eventsCh
if e.Type == watch.Added {
fmt.Printf("%+v", e)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment