What’s in Kubernetes client-go — Part 1

client-go

  • client-go is an API client for Kubernetes that supports all API kinds which are officially part of Kubernetes e.g Pods, Services, Deployments, etc
  • Apart from standard CRUD verbs, it also supports a special verb Watch for Kubernetes like API’s
  • To use this in your projects, you need to import this as k8s.io/client-go

Packages and their usages

  1. kubernetes package contains the clients to access Kubernetes API. It provides typed clients for all types officially part of Kubernetes. For example, you are writing a Kubernetes app that will list all pods in a cluster
  • For out of the cluster apps configurations
var kubeconfig *string
if home := homedir.HomeDir(); home != "" {
kubeconfig = flag.String("kubeconfig", filepath.Join(home, ".kube", "config"), "(optional) absolute path to the kubeconfig file")
} else {
kubeconfig = flag.String("kubeconfig", "", "absolute path to the kubeconfig file")
}
flag.Parse()
// use the current context in kubeconfig
config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
if err != nil {
panic(err.Error())
}
// create the clientset
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
panic(err.Error())
}
pods, err := clientset.CoreV1().Pods("").List(context.TODO(), metav1.ListOptions{})
if err != nil {
panic(err.Error())
}
fmt.Printf("There are %d pods in the cluster\n", len(pods.Items))
  • For in-cluster apps configurations
config, err := rest.InClusterConfig()
if err != nil {
panic(err.Error())
}
// creates the clientset
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
panic(err.Error())
}
pods, err := clientset.CoreV1().Pods("").List(context.TODO(), metav1.ListOptions{})
if err != nil {
panic(err.Error())
}
fmt.Printf("There are %d pods in the cluster\n", len(pods.Items))
dClient := discovery.NewDiscoveryClient(clientset)

// returns supported groups and resources for all groups and versions.
allGroups, allResources, err := dClient.ServerGroupsAndResources()
if err != nil {
return nil, err
}

// returns the supported resources for a group and version.
rs, err := dClient.ServerResourcesForGroupVersion("apps/v1")
if err != nil {
return nil, err
}

// returns the supported resources with the version preferred by the server.
preferredResources, err := dClient.ServerPreferredResources()
if err != nil {
return nil, err
}


// Get Kubernetes API Server version info
versionInfo, err := dClient.ServerVersion()
if err != nil {
return nil, err
}
var kubeconfig *string
if home := homedir.HomeDir(); home != "" {
kubeconfig = flag.String("kubeconfig", filepath.Join(home, ".kube", "config"), "(optional) absolute path to the kubeconfig file")
} else {
kubeconfig = flag.String("kubeconfig", "", "absolute path to the kubeconfig file")
}
flag.Parse()

namespace := "default"

config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
if err != nil {
panic(err)
}
client, err := dynamic.NewForConfig(config)
if err != nil {
panic(err)
}

deploymentRes := schema.GroupVersionResource{Group: "apps", Version: "v1", Resource: "deployments"}

deployment := &unstructured.Unstructured{
Object: map[string]interface{}{
"apiVersion": "apps/v1",
"kind": "Deployment",
"metadata": map[string]interface{}{
"name": "demo-deployment",
},
"spec": map[string]interface{}{
"replicas": 2,
"selector": map[string]interface{}{
"matchLabels": map[string]interface{}{
"app": "demo",
},
},
"template": map[string]interface{}{
"metadata": map[string]interface{}{
"labels": map[string]interface{}{
"app": "demo",
},
},

"spec": map[string]interface{}{
"containers": []map[string]interface{}{
{
"name": "web",
"image": "nginx:1.12",
"ports": []map[string]interface{}{
{
"name": "http",
"protocol": "TCP",
"containerPort": 80,
},
},
},
},
},
},
},
},
}

// Create Deployment
fmt.Println("Creating deployment...")
result, err := client.Resource(deploymentRes).Namespace(namespace).Create(context.TODO(), deployment, metav1.CreateOptions{})
if err != nil {
panic(err)
}
fmt.Printf("Created deployment %q.\n", result.GetName())
  • clientcmd uses for building clients from a kubeconfig file, which can be used to create clients to interact with the Kubernetes API Server.
config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
if err != nil {
panic(err)
}
  • cache useful for writing controllers. It contains most of the logic related to Kubernetes client-side caching.
  • Get input from the API server as events.
  • Offer a client-like interface called Lister to get and list objects from the in-memory cache.
  • Register event handlers for adds, removes, and updates.
  • Implement the in-memory cache using a store.
import (
...
"k8s.io/client-go/informers"
)
...
clientset, err := kubernetes.NewForConfig(config)
informerFactory := informers.NewSharedInformerFactory(clientset, time.Second*30)
podInformer := informerFactory.Core().V1().Pods()
podInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: func(new interface{}) {...},
UpdateFunc: func(old, new interface{}) {...},
DeleteFunc: func(obj interface{}) {...},
})
informerFactory.Start(wait.NeverStop)
informerFactory.WaitForCacheSync(wait.NeverStop)

--

--

--

Strong Interest in CloudNative, Distributed Systems, and System Design. https://www.linkedin.com/in/viveksyngh/

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Groovy Slurper in Python

Docker tutorial — how to install Docker on Ubuntu

Docker tutorial - how to install Docker on Ubuntu

New features,tech stack of instagram

City as MyData Operator

Squirrel Weekly (01/12) 🐿️

Interview Questions on Scheduled Apex in Salesforce

IT-Sputnik Bitrix24 Integration

Pyaudio Installation Error Finally Solved For Windows PC

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Vivek Kumar Singh

Vivek Kumar Singh

Strong Interest in CloudNative, Distributed Systems, and System Design. https://www.linkedin.com/in/viveksyngh/

More from Medium

Kubernetes Horizontal Auto Scaling with Golang microservice — Hands-on

Why we built our own k8s Redis operator — Part 1

10 Things You Should Know Before Writing a Kubernetes Controller

Understanding the Kubernetes Control Plane 101