Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get pods under the service with client-go the client library of kubernetes?

Tags:

kubernetes

Anyone who can tell me how to get pods under the service with client-go the client library of kubernetes?

thanks

like image 357
sope Avatar asked Jan 09 '17 09:01

sope


People also ask

Does kubectl use client go?

client-go is the official client library of Kubernetes, which is used internally by Kubernetes as well. The Kubernetes command line tool kubectl is built on client-go.

How do I access the Kubernetes API from within a pod container?

From inside the pod, kubernetes api server can be accessible directly on "https://kubernetes.default". By default it uses the "default service account" for accessing the api server. So, we also need to pass a "ca cert" and "default service account token" to authenticate with the api server.


2 Answers

I found this accepted answer a little lacking, as far as clarity. This code works under 1.10. In this example, my svc deployments all have a controlled name based on the artifact that it is fronting, and the pods leverage that as well. Please note I am a Java programmer learning go, so there may be a little too much OO for some go enthusiasts

package main

import (
    "os"
    "log"
    "path/filepath"
    "k8s.io/client-go/tools/clientcmd"
    "k8s.io/client-go/kubernetes"
    typev1 "k8s.io/client-go/kubernetes/typed/core/v1"
    metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    corev1 "k8s.io/api/core/v1"
    "fmt"
    "strings"
    "errors"
    "k8s.io/apimachinery/pkg/labels"
)

func main(){
    kubeconfig := filepath.Join(
        os.Getenv("HOME"), ".kube", "config",
    )
    namespace:="FOO"
    k8sClient, err:= getClient(kubeconfig)
    if err!=nil{
        fmt.Fprintf(os.Stderr, "error: %v\n", err)
        os.Exit(1)
    }

    svc, err:=getServiceForDeployment("APP_NAME", namespace, k8sClient)
    if err!=nil{
        fmt.Fprintf(os.Stderr, "error: %v\n", err)
        os.Exit(2)
    }

    pods, err:=getPodsForSvc(svc, namespace, k8sClient)
    if err!=nil{
        fmt.Fprintf(os.Stderr, "error: %v\n", err)
        os.Exit(2)
    }
    
}

func getClient(configLocation string) (typev1.CoreV1Interface, error){
    kubeconfig := filepath.Clean(configLocation)
    config, err := clientcmd.BuildConfigFromFlags("", kubeconfig)
    if err != nil {
        log.Fatal(err)
    }
    clientset, err := kubernetes.NewForConfig(config)
    if err != nil {
        return nil, err
    }
    return clientset.CoreV1(), nil
}

func getServiceForDeployment(deployment string, namespace string, k8sClient typev1.CoreV1Interface) (*corev1.Service, error){
    listOptions := metav1.ListOptions{}
    svcs, err := k8sClient.Services(namespace).List(listOptions)
    if err != nil{
        log.Fatal(err)
    }
    for _, svc:=range svcs.Items{
        if strings.Contains(svc.Name, deployment){
            fmt.Fprintf(os.Stdout, "service name: %v\n", svc.Name)
            return &svc, nil
        }
    }
    return nil, errors.New("cannot find service for deployment")
}

func getPodsForSvc(svc *corev1.Service, namespace string, k8sClient typev1.CoreV1Interface) (*corev1.PodList, error){
    set := labels.Set(svc.Spec.Selector)
    listOptions:= metav1.ListOptions{LabelSelector: set.AsSelector().String()}
    pods, err:=  k8sClient.Pods(namespace).List(listOptions)
    for _,pod:= range pods.Items{
        fmt.Fprintf(os.Stdout, "pod name: %v\n", pod.Name)
    }
    return pods, err
}
like image 102
fpmoles Avatar answered Oct 22 '22 06:10

fpmoles


I have found the answer:

                services, err := clientset.Core().Services(name).List(api.ListOptions{})
                if err != nil {
                    log.Errorf("Get service from kubernetes cluster error:%v", err)
                    return
                }

                for _, service := range services.Items {
                    if name == "default" && service.GetName() == "kubernetes" {
                        continue
                    }
                    log.Infoln("namespace", name, "serviceName:", service.GetName(), "serviceKind:", service.Kind, "serviceLabels:", service.GetLabels(), service.Spec.Ports, "serviceSelector:", service.Spec.Selector)

                    // labels.Parser
                    set := labels.Set(service.Spec.Selector)

                    if pods, err := clientset.Core().Pods(name).List(api.ListOptions{LabelSelector: set.AsSelector()}); err != nil {
                        log.Errorf("List Pods of service[%s] error:%v", service.GetName(), err)
                    } else {
                        for _, v := range pods.Items {
                            log.Infoln(v.GetName(), v.Spec.NodeName, v.Spec.Containers)
                        }
                    }
                }
like image 42
sope Avatar answered Oct 22 '22 05:10

sope