Some probelm when I use client-go for kubernetes watch list

9/18/2019

I have some when I use the code in StackOverflow. Such as

package main

import (
    "flag"
    "fmt"
    "time"

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

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)
    }
}

it have some errors:

  1. i can not find the package "k8s.io/client-go/pkg/api/v1" and "k8s.io/client-go/pkg/fields", i don't know how to find it:

    https://github.com/kubernetes/client-go

  2. the code

watchlist := cache.NewListWatchFromClient(clientset.Core().RESTClient(), "services", v1.NamespaceDefault,
        fields.Everything())

has the error:

Cannot use 'clientSet.CoreV1().RESTClient()' (type rest.Interface) as type Getter Type does not implement 'Getter' as some methods are missing: Get() *restclient.Request

Could anyone tell me how to resolve it? Thanks in advance.

-- edselwang
client-go
go
kubernetes

0 Answers