Code Monkey home page Code Monkey logo

client-go-examples's Introduction

Kubernetes client-go examples

! Support development of this project > patreon.com/iximiuz

A collection of mini-programs demonstrating various client-go use cases augmented by a preconfigured online development environment. Inspired by client-go/examples.

The intention is to test a (more or less) fresh version of Go and k8s.io packages against the currently maintained Kubernetes release branches.

What is tested at the moment:

  • go 1.22.0
  • k8s.io/client-go 0.26.13 0.27.10 0.28.6 0.29.1 (maintained release branches)
  • Kubernetes 1.26.14 1.27.11 1.28.7 1.29.2 (best-effort match with versions supported by kind)

Setup

Most examples expect at least two Kubernetes clusters - shared1 and shared2.

curl -sLS https://get.arkade.dev | sudo sh
arkade get kind kubectl

kind create cluster --name shared1
kind create cluster --name shared2

Run

Oversimplified (for now):

cd <program>
make test

# or from the root folder:
make test-all

TODO

Contribution

Contributions are always welcome! Want to participate but don't know where to start? The TODO list above could give you some ideas. Before jumping to the code, please create an issue describing the addition/change first. This will allow me to coordinate the effort and make sure multiple people don't work on the same task.

client-go-examples's People

Contributors

dylanhitt avatar iximiuz avatar jasstkn avatar maxgio92 avatar nikhil-thomas 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  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  avatar  avatar  avatar  avatar

Watchers

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

client-go-examples's Issues

Thoughts on a common lib repeated functions?

This is done a lot

home, err := os.UserHomeDir()
if err != nil {
	panic(err)
}

cfg, err := clientcmd.BuildConfigFromFlags("", path.Join(home, ".kube/config"))
if err != nil {
	panic(err.Error())
}

client := kubernetes.NewForConfigOrDie(cfg)
desired := corev1.ConfigMap{
	ObjectMeta: metav1.ObjectMeta{
		Name:      name,
		Namespace: namespace,
	},
	Data: map[string]string{"foo": "bar"},
}

Thoughts on a pkg/common or common/ or . I thin it will help better focus on the example that's trying to be displayed rather than the setup.

Owner reference

I'd like to submit a PR for this in near future as I'm in midst of an implementation.

Let me know if that's acceptable

Cheers! ๐Ÿ˜„

Using klog in the examples

Thank you for the blogposts and for these snippets! I think it's very useful to see the timestamps in the examples that you have, I was wondering if you'd be ok if I submit a change replacing fmt.Printf with klog.Infof

Example for `retry.RetryOnConflict`

The repository should include an example of retry.RetryOnConflict.

Current implementation idea:

Folder Name: retry-on-conflict
General Flow:

  • Create pod - keep reference
  • UpdateStatus pod - ignore reference to emulate the object changing unexpectedly from either another controller or external source
  • Implement retry function. To display the use we could use a timer to demonstrate performing long running task to validate the status of an object. For instance sometimes when working with CRDs that create resources external to k8s, gathering status can take a significant amount of time. A very naive solution would be just using a flag and skipping fetch on the first try. Not quite sure, but a simple explanation would be better than a complex example. Maybe someone has some thoughts on how to emulate this situation easily.
err := retry.RetryOnConflict(retry.DefaultRetry, func() error {
    pod, err := c.Pods("ns").Get(name, metav1.GetOptions{})
    if err != nil {
        return err
    }
    
    // emulate long running tasks to get current status with timers
    
    _, err = c.Pods("ns").UpdateStatus(pod)
})

I'd like to submit a PR for this as I recently hit this position in a custom controller. @iximiuz I'd like to hear thoughts.

Example for create object from file via dynamic API

I need code to create object from file just like kubectl since I don't want to depend on kubectl executable.

The following code works for creating Deployment, Service etc but not work for ClusterRole, ClusterRoleBind etc. The error is:
client.Resource.Namespace.Create failed: the server could not find the requested resource.

Could you help to fix it?

package main

import (
	"context"
	"flag"
	"fmt"
	"io/fs"
	"os"
	"path/filepath"
	"sort"

	"github.com/thanos-io/thanos/pkg/errors"
	apiv1 "k8s.io/api/core/v1"
	apiErrors "k8s.io/apimachinery/pkg/api/errors"
	"k8s.io/apimachinery/pkg/api/meta"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
	"k8s.io/apimachinery/pkg/runtime/schema"
	"k8s.io/client-go/dynamic"
	"k8s.io/client-go/tools/clientcmd"
	"k8s.io/client-go/util/homedir"
	"sigs.k8s.io/yaml"
)

func kind2Resource(group, version, kind string) (gvr schema.GroupVersionResource, err error) {
	// https://www.cnblogs.com/zhangmingcheng/p/16128224.html
	// https://iximiuz.com/en/posts/kubernetes-api-structure-and-terminology/
	// https://github.com/kubernetes/kubernetes/issues/18622
	// kubectl api-resources
	gvk := schema.GroupVersionKind{Group: group, Version: version, Kind: kind}
	gvr, _ = meta.UnsafeGuessKindToResource(gvk)
	//fmt.Printf("%s %s %s -> %+v\n", group, version, kind, gvr)
	return
}

func createObject(client dynamic.Interface, fp string) (err error) {
	fmt.Printf("Reading %s...\n", fp)
	var b []byte
	if b, err = os.ReadFile(fp); err != nil {
		err = errors.Wrapf(err, "os.ReadFile failed")
		return
	}
	m := make(map[string]interface{})
	if err = yaml.Unmarshal(b, &m); err != nil {
		err = errors.Wrapf(err, "yaml.Unmarshal failed")
		return
	}

	obj := unstructured.Unstructured{Object: m}
	var apiVersion, kind, namespace string
	apiVersion = obj.GetAPIVersion()
	kind = obj.GetKind()
	namespace = obj.GetNamespace()
	if namespace == "" {
		namespace = apiv1.NamespaceDefault
	}
	gv, _ := schema.ParseGroupVersion(apiVersion)
	var gvr schema.GroupVersionResource
	if gvr, err = kind2Resource(gv.Group, gv.Version, kind); err != nil {
		return
	}
	var result *unstructured.Unstructured
	result, err = client.Resource(gvr).Namespace(namespace).Create(context.TODO(), &obj, metav1.CreateOptions{})
	if err != nil {
		err = errors.Wrapf(err, "client.Resource.Namespace.Create failed")
		return
	}
	fmt.Printf("Created resource %q.\n", result.GetName())
	return
}

func main() {
	// Initialize client
	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")
	}
	pth := flag.String("f", ".", "path of manifest file or directory")
	flag.Parse()

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

	// Get manifest list
	var fi fs.FileInfo
	if fi, err = os.Stat(*pth); err != nil {
		panic(err)
	}
	var fps []string
	if fi.IsDir() {
		var des []fs.DirEntry
		if des, err = os.ReadDir(*pth); err != nil {
			panic(err)
		}
		for _, de := range des {
			if de.IsDir() {
				continue
			}
			fn := de.Name()
			ext := filepath.Ext(fn)
			if ext != ".yaml" && ext != "yml" {
				continue
			}
			fps = append(fps, filepath.Join(*pth, fn))
		}
		sort.Strings(fps)
	} else {
		fps = append(fps, *pth)
	}

	// Create resource for each manifest
	for _, fp := range fps {
		if err = createObject(client, fp); err != nil {
			if !apiErrors.IsAlreadyExists(err) {
				fmt.Println(err)
			}
		}
	}
}

# blackboxExporter-clusterRoleBinding.yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  labels:
    app.kubernetes.io/component: exporter
    app.kubernetes.io/name: blackbox-exporter
    app.kubernetes.io/part-of: kube-prometheus
    app.kubernetes.io/version: 0.22.0
  name: blackbox-exporter
  namespace: monitoring
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: blackbox-exporter
subjects:
- kind: ServiceAccount
  name: blackbox-exporter
  namespace: monitoring

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.