Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

go

kubernetes

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

like image 787
Ramin Mir. Avatar asked Dec 05 '16 13:12

Ramin Mir.


People also ask

How can I watch Kubernetes events?

To collect or watch the events, you can run kubectl get events --watch in deployment and collect the output with a third-party logging tool. To watch Kubernetes events, many free and paid third-party tools help provide visibility and reporting of events in a Kubernetes cluster resource.

How do I get event logs in Kubernetes?

The easiest way to collect event logs is to simply run kubectl get events --watch in a deployment, and collect its output with the Banzai Cloud Logging operator.

How do you check events in pods?

You can use kubectl get events --output json to check the data structure. $ kubectl get events --output json { "apiVersion": "v1", "items": [ { "apiVersion": "v1", "count": 259, "eventTime": null, "firstTimestamp": "2020-04-15T12:00:46Z", "involvedObject": { <------ **this** "apiVersion": "v1", "fieldPath": "spec.


1 Answers

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)
    }
}
like image 139
Ramin Mir. Avatar answered Sep 19 '22 19:09

Ramin Mir.