Skip to content

Instantly share code, notes, and snippets.

@tom-code
Created January 18, 2019 16:46
Show Gist options
  • Select an option

  • Save tom-code/59883fdc7dcd639d81d8014196c1ffa0 to your computer and use it in GitHub Desktop.

Select an option

Save tom-code/59883fdc7dcd639d81d8014196c1ffa0 to your computer and use it in GitHub Desktop.
goku2
package main
import (
"fmt"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/api/core/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
"time"
//"k8s.io/apimachinery/pkg/types"
//"encoding/json"
)
func makeList(cs *kubernetes.Clientset) map[string]string {
m := make(map[string]string)
pods, err := cs.CoreV1().Pods("").List(metav1.ListOptions{ })
if err != nil {
panic(err.Error())
}
for _, pod := range pods.Items {
name := pod.Namespace+ "/" +pod.Name
m[name] = "x"
}
return m
}
func watchLoop(cs *kubernetes.Clientset, zz func()) {
watch, err := cs.CoreV1().Pods("").Watch(metav1.ListOptions{})
if err != nil {
panic(err.Error())
}
events := watch.ResultChan()
for {
select {
case ev, _ := <-events: {
if ev.Object == nil {
fmt.Println("watch returned nil - recreate")
watch.Stop()
watch, _ = cs.CoreV1().Pods("").Watch(metav1.ListOptions{})
events = watch.ResultChan()
continue
//os.Exit(0)
}
pod := ev.Object.(*v1.Pod)
if pod == nil {
fmt.Println("can't get pod?")
continue
}
fmt.Printf("\nevent %s %s\n", ev.Type, pod.Name)
}
case <- time.After(5*time.Minute): {
fmt.Println("5min")
}
}
fmt.Println("a1")
zz()
fmt.Println("a2")
}
}
func main() {
/*config, err := rest.InClusterConfig()
if err != nil {
panic(err.Error())
}*/
map1 := make(map[string]string)
config, err := clientcmd.BuildConfigFromFlags("", "admin.conf")
if err != nil {
panic(err.Error())
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
panic(err.Error())
}
watchLoop(clientset, func() {
lst := makeList(clientset)
for key := range lst {
_, present := map1[key]
if !present {
fmt.Printf("new item %s\n", key)
}
}
for key := range map1 {
_, present := lst[key]
if !present {
fmt.Printf("deleted item %s\n", key)
}
}
map1 = lst
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment