Skip to content

Instantly share code, notes, and snippets.

@sjenning
Created August 2, 2018 23:06
Show Gist options
  • Select an option

  • Save sjenning/97431ac53ef75007b54696f2d38ca33b to your computer and use it in GitHub Desktop.

Select an option

Save sjenning/97431ac53ef75007b54696f2d38ca33b to your computer and use it in GitHub Desktop.
pod-running-timer
package main
import (
"fmt"
"os"
"time"
"k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/tools/clientcmd"
)
func main() {
startTimes := make(map[types.UID]time.Time)
config, err := clientcmd.BuildConfigFromFlags("", os.Getenv("KUBECONFIG"))
if err != nil {
panic(err.Error())
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
panic(err.Error())
}
fmt.Println("starting watch on pods")
watcher := cache.NewListWatchFromClient(clientset.CoreV1().RESTClient(), "pods", v1.NamespaceAll, fields.Everything())
_, informer := cache.NewIndexerInformer(watcher, &v1.Pod{}, 0, cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
pod, ok := obj.(*v1.Pod)
if !ok {
return
}
startTimes[pod.UID] = time.Now()
},
UpdateFunc: func(old interface{}, new interface{}) {
pod, ok := new.(*v1.Pod)
if !ok {
return
}
if pod.Status.Phase != v1.PodRunning {
return
}
startTime, ok := startTimes[pod.UID]
if !ok {
return
}
delta := time.Since(startTime)
fmt.Printf("pod %v (UID %v) Running in %vms\n", pod.Name, pod.UID, delta.Nanoseconds()/1000000)
delete(startTimes, pod.UID)
},
DeleteFunc: func(obj interface{}) {},
}, cache.Indexers{})
informer.Run(nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment