Code Monkey home page Code Monkey logo

k8s-discovery's Introduction

K8s-Discovery

PkgGoDev Release language Go Report Card License CII Best Practices

K8s Discovery, is an effort to reduce the boiler plate code for the client-go or kubernetes based cloud native GoLang developers.

The main aspect of this is around saving and cleaning the code for in-cluster and out-cluster configurations.

Usage

Run go get to get the k8s-discovery module as follows.

go get github.com/gkarthiks/k8s-discovery

Declare a variable as var k8s *discovery.K8s and initialize it as k8s, _ = discovery.NewK8s(). Now the k8s will hold the interface that will provide the clientset for Kubernetes communication that is pulled either via in-cluster or via kubeconfig file.

Available APIs at the moment

NewK8s: Will return a new kubernetes clientset's interface that is formulated either via in-cluster configuration or kubeconfog file.

GetVersion: Queries the Kubernetes for the version in v0.0.0-master+$Format:%h$

GetNamespace: Gets the namespace of the running pod if running inside the cluster, if outside returns based on the POD_NAMESPACE environment variable. This environment variable also takes precedence if provided in a pod.

Available client

K8s Discovery provides the client set for kubernetes client with hassle free configuration as well as the metrics client. The MetricsClientSet can be used to query the metrics against the containers. There is also a RestConfig exposed via discovery to make use of the rest api.

Example

package main

import (
	"context"
	"fmt"
	"log"
	"strconv"

	discovery "github.com/gkarthiks/k8s-discovery"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	metricsTypes "k8s.io/metrics/pkg/apis/metrics/v1beta1"
)

var (
	k8s *discovery.K8s
)

func main() {
	k8s, _ = discovery.NewK8s()
	namespace, _ := k8s.GetNamespace()
	version, _ := k8s.GetVersion()
	fmt.Printf("Specified Namespace: %s\n", namespace)
	fmt.Printf("Version of running Kubernetes: %s\n", version)
	
	
	
	
	cronJobs, err := k8s.Clientset.BatchV1beta1().CronJobs(namespace).List(context.Background(), metav1.ListOptions{})
	if err != nil {
		log.Panic(err.Error())
	}
	for idx, crons := range cronJobs.Items {
		fmt.Printf("%d -> %s\n", idx, crons.Name)
	}
	
	
	
	
	fmt.Println("==== Moving towards the metrics query ====")
	
	podMetrics, err := k8s.MetricsClientSet.MetricsV1beta1().PodMetricses(namespace).List(context.Background(), metav1.ListOptions{})
	if err != nil {
		panic(err)
	}

	var podMetric metricsTypes.PodMetrics
	getPodUsageMetrics := func(pod metricsTypes.PodMetrics) {
		for _, container := range pod.Containers {
			cpuQuantityDec := container.Usage.Cpu().AsDec().String()
			cpuUsageFloat, _ := strconv.ParseFloat(cpuQuantityDec, 64)

			fmt.Printf( "CPU Usage Float: %v\n", cpuUsageFloat)

			memoryQuantityDec := container.Usage.Memory().AsDec().String()
			memoryUsageFloat, _ := strconv.ParseFloat(memoryQuantityDec, 64)
			fmt.Printf("Memory Usage Float: %v\n\n", memoryUsageFloat)
		}
	}

	for _, podMetric = range podMetrics.Items {
		getPodUsageMetrics(podMetric)
	}
	
	
	
}

Note:

For GCP or managed kubernetes, you have to import the auth module, else an error message stating no Auth Provider found for name "gcp" will be thrown. The import looks like the below for the sample program. Special mention @ringods.

import (
	"context"
	"fmt"
	"log"
	"strconv"

	discovery "github.com/gkarthiks/k8s-discovery"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	metricsTypes "k8s.io/metrics/pkg/apis/metrics/v1beta1"
	_ "k8s.io/client-go/plugin/pkg/client/auth"
)

Contributing

For contributions please refer the contributing guidelines.

k8s-discovery's People

Contributors

gkarthiks avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

k8s-discovery's Issues

getClientset alternative

Hi! I have been happily using your library, and I ran across a very succinct alternative that also works in a pod in a cluster and outside a cluster that you might want to use in your library. From Lars Ekman:

func getClientset() (*kubernetes.Clientset, error) {
        config, err := rest.InClusterConfig()
        if err != nil {
                kubeconfig :=
                        clientcmd.NewDefaultClientConfigLoadingRules().GetDefaultFilename()
                config, err = clientcmd.BuildConfigFromFlags("", kubeconfig)
                if err != nil {
                        return nil, err
                }
        }
        return kubernetes.NewForConfig(config)
}

Clientset is `nil` after `NewK8s()`

Hello,

I'm trying your code to remove the plumbing for in- and out of cluster K8s access. I started with this small example:

package k8s

import (
	"fmt"

	discovery "github.com/gkarthiks/k8s-discovery"
)

var (
	k8s *discovery.K8s
)

// GetKubernetesConnection tries to create a connection either from a local .kube/config file or from in-cluster service account
func GetKubernetesConnection() {
	k8s, _ = discovery.NewK8s()

	namespace, _ := k8s.GetNamespace()
	fmt.Printf("Specified Namespace: %s\n", namespace)

	version, _ := k8s.GetVersion()
	fmt.Printf("Version of running Kubernetes: %s\n", version)
}

The function is called from main.go. When running, I get a panic:

INFO[0000] Program running from outside of the cluster  
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x1d82986]

goroutine 1 [running]:
github.com/gkarthiks/k8s-discovery.(*K8s).GetVersion(0x0, 0x2185a60, 0xc00037e1f0, 0x10436e7, 0x2aa56c0)
        /Users/ringods/Projects/golang/pkg/mod/github.com/gkarthiks/[email protected]/discovery.go:69 +0x26
github.com/cumundi/sqe-processing/pkg/k8s.GetKubernetesConnection()
        /Users/ringods/Projects/cumundi/sqe-processing/pkg/k8s/runner.go:17 +0x43
main.main()
        /Users/ringods/Projects/cumundi/sqe-processing/pkg/cmd/sqe-starter/main.go:19 +0x20

I am testing this now out of cluster, with a kubeconfig having the current context set to a GKE cluster. I am fully authenticated and any kubectl command correctly communicates with the cluster.

Any idea what might be wrong?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.