Accessing Kubernetes CRDs from the client-go package

The Kubernetes API server is easily extendable by Custom Resource Defintions. However, actually accessing these resources from the popular client-go library is a bit more complex and not thoroughly documented. This article contains a short guide on how to access Kubernetes CRDs from your own Go code.

Motivation

I came across this challenge while wanting to integrate a third-party storage vendor into a Kubernetes cluster in my day job at Mittwald. The plan was to use Custom Resource Definitions to define things like Filesystem Pools and Filesystems. Then, a custom Operator could listen for these resources being created and deleted and take care of the actual provisioning of these resources.

Defining and creating a Custom Resource

For this article, we’ll work with an easy example: Custom Resource Definitions can be easily created using kubectl, and for this example, we will start with a single simple resource definition:

 1 apiVersion: "apiextensions.k8s.io/v1beta1"
 2 kind: "CustomResourceDefinition"
 3 metadata:
 4   name: "projects.example.martin-helmich.de"
 5 spec:
 6   group: "example.martin-helmich.de"
 7   version: "v1alpha1"
 8   scope: "Namespaced"
 9   names:
10     plural: "projects"
11     singular: "project"
12     kind: "Project"
13   validation:
14     openAPIV3Schema:
15       required: ["spec"]
16       properties:
17         spec:
18           required: ["replicas"]
19           properties:
20             replicas:
21               type: "integer"
22               minimum: 1

For defining a Custom Resource Definition, you will need to think of an API Group Name (in this case, example.martin-helmich.de). By convention, this is usually the Domain Name of a domain that you control (for example, your organization’s domain) in order to prevent naming conflicts. The CRD’s name then follows the pattern <plural-resource-name>.<api-group-name>, so in this case projects.example.martin-helmich.de.

Also, be careful when choosing your definition version (spec.version in the example above). As long as your definitions are still evolving, it’s usually a good idea to declare your first definition with an alpha API group version. To users of your custom resource, this will clearly communicate that the definitions might still change, later.

Often, you want to validate which kind of data users supply for your custom resources. This is what the spec.validation.openAPIV3Schema is for: This contains a JSON Schema that describes the format that your resources should have.

After saving the CRD in a file, you can use kubectl to create your resource definition:

> kubectl apply -f projects-crd.yaml
customresourcedefinition "projects.example.martin-helmich.de" created

After you have created your Custom Resource Definition, you can create objects. These are defined like regular Kubernetes objects (like, for example, Pods, Deployments and others). Only the kind and apiVersion vary:

1 apiVersion: "example.martin-helmich.de/v1alpha1"
2 kind: "Project"
3 metadata:
4   name: "example-project"
5   namespace: "default"
6 spec:
7   replicas: 1

You can create custom resources like any other object with kubectl:

> kubectl apply -f project.yaml
project "example-project" created

You can even use kubectl get to retrieve your custom resources back from the Kubernetes API. Most other commands like kubectl edit, apply or delete will work, as well:

> kubectl get projects
NAME               AGE
example-project    2m

Creating a Golang client

Next, we’ll use the client-go package to access these custom resources. For this example, I’ll assume that you are working in a Go project with the package name github.com/martin-helmich/kubernetes-crd-example (yes, that repository actually exists) and have the client-go library installed with Glide.

Note Many documentations work working with CRDs will assume that you are working with some kind of code generation to generate client libraries automatically. However, this process is documented sparsely, and from reading a few heated discussions on Github, I got the impression that it's still very much a work-in-progress. We'll stick with a manually implemented client, for now.

Step 1: Define types

Start by defining the types for your custom resource. I’ve found it to be a good practice to organize these types by the API group version; so for example, you could create a file api/types/v1alpha1/project.go with the following contents:

 1 package v1alpha1
 2 
 3 import metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
 4 
 5 type ProjectSpec struct {
 6     Replicas int `json:"replicas"`
 7 }
 8 
 9 type Project struct {
10 	metav1.TypeMeta   `json:",inline"`
11 	metav1.ObjectMeta `json:"metadata,omitempty"`
12 
13     Spec ProjectSpec `json:"spec"`
14 }
15 
16 type ProjectList struct {
17 	metav1.TypeMeta `json:",inline"`
18 	metav1.ListMeta `json:"metadata,omitempty"`
19 
20 	Items []Project `json:"items"`
21 }

The metav1.ObjectMeta type contains the typical metadata properties that you can find in any Kubernetes resource (like for example, the name, namespace, labels and annotations).

Step 2: Define DeepCopy methods

Each type that is being served by the Kubernetes API (in this case, Project and ProjectList) needs to implement the k8s.io/apimachinery/pkg/runtime.Object interface. This interface defines the two methods GetObjectKind() and DeepCopyObject(). The first method is already provided by the embedded metav1.TypeMeta struct; the second you’ll have to implement yourself.

The DeepCopyObject method is intended to generate a deep copy of an object. Since this involves a lot of boilerplate code, these methods are often automatically generated. For the sake of this article, we’ll do it manually. Continue by adding a second file deepcopy.go to the same package:

 1 package v1alpha1
 2 
 3 import "k8s.io/apimachinery/pkg/runtime"
 4 
 5 // DeepCopyInto copies all properties of this object into another object of the
 6 // same type that is provided as a pointer.
 7 func (in *Project) DeepCopyInto(out *Project) {
 8     out.TypeMeta = in.TypeMeta
 9     out.ObjectMeta = in.ObjectMeta
10     out.Spec = ProjectSpec{
11         Replicas: in.Spec.Replicas,
12     }
13 }
14 
15 // DeepCopyObject returns a generically typed copy of an object
16 func (in *Project) DeepCopyObject() runtime.Object {
17     out := Project{}
18     in.DeepCopyInto(&out)
19 
20     return &out
21 }
22 
23 // DeepCopyObject returns a generically typed copy of an object
24 func (in *ProjectList) DeepCopyObject() runtime.Object {
25     out := ProjectList{}
26     out.TypeMeta = in.TypeMeta
27     out.ListMeta = in.ListMeta
28 
29     if in.Items != nil {
30         out.Items = make([]Project, len(in.Items))
31         for i := range in.Items {
32             in.Items[i].DeepCopyInto(&out.Items[i])
33         }
34     }
35 
36     return &out
37 }

Step 3: Register types at the scheme builder

Next, you’ll need to make your new types known to the client library. This will allow the client to (more or less) automatically process your new types when communicating with the API server.

For this, add a new file register.go to your package:

 1 package v1alpha1
 2 
 3 import (
 4     metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
 5     "k8s.io/apimachinery/pkg/runtime"
 6     "k8s.io/apimachinery/pkg/runtime/schema"
 7 )
 8 
 9 const GroupName = "example.martin-helmich.de"
10 const GroupVersion = "v1alpha1"
11 
12 var SchemeGroupVersion = schema.GroupVersion{Group: GroupName, Version: GroupVersion}
13 
14 var (
15     SchemeBuilder = runtime.NewSchemeBuilder(addKnownTypes)
16     AddToScheme   = SchemeBuilder.AddToScheme
17 )
18 
19 func addKnownTypes(scheme *runtime.Scheme) error {
20     scheme.AddKnownTypes(SchemeGroupVersion,
21         &Project{},
22         &ProjectList{},
23     )
24 
25     metav1.AddToGroupVersion(scheme, SchemeGroupVersion)
26     return nil
27 }

As you may notice, this code does not really do anything, yet (except for creating a new runtime.SchemeBuilder instance). The important part is the AddToScheme function (line 16), which is an exported struct member of the runtime.SchemeBuilder type created in line 15. You can call this function later from any part of your client code as soon as the Kubernetes client is initialized to register your type definitions.

Step 4: Build a HTTP client

After defining types and adding a method to register them at the global scheme builder, you can now create a HTTP client that is capable of loading your custom resource.

For this, add the following code to your package’s main.go file (for now):

 1 package main
 2 
 3 import (
 4     "flag"
 5     "log"
 6     "time"
 7 
 8     "k8s.io/apimachinery/pkg/runtime/schema"
 9     "k8s.io/apimachinery/pkg/runtime/serializer"
10 
11     "github.com/martin-helmich/kubernetes-crd-example/api/types/v1alpha1"
12     "k8s.io/client-go/kubernetes/scheme"
13     "k8s.io/client-go/rest"
14     "k8s.io/client-go/tools/clientcmd"
15 )
16 
17 var kubeconfig string
18 
19 func init() {
20     flag.StringVar(&kubeconfig, "kubeconfig", "", "path to Kubernetes config file")
21     flag.Parse()
22 }
23 
24 func main() {
25     var config *rest.Config
26     var err error
27 
28     if kubeconfig == "" {
29         log.Printf("using in-cluster configuration")
30         config, err = rest.InClusterConfig()
31     } else {
32         log.Printf("using configuration from '%s'", kubeconfig)
33         config, err = clientcmd.BuildConfigFromFlags("", kubeconfig)
34     }
35 
36     if err != nil {
37         panic(err)
38     }
39 
40     v1alpha1.AddToScheme(scheme.Scheme)
41 
42     crdConfig := *config
43     crdConfig.ContentConfig.GroupVersion = &schema.GroupVersion{Group: v1alpha1.GroupName, Version: v1alpha1.GroupVersion}
44     crdConfig.APIPath = "/apis"
45     crdConfig.NegotiatedSerializer = serializer.DirectCodecFactory{CodecFactory: scheme.Codecs}
46     crdConfig.UserAgent = rest.DefaultKubernetesUserAgent()
47 
48     exampleRestClient, err := rest.UnversionedRESTClientFor(&crdConfig)
49     if err != nil {
50         panic(err)
51     }
52 }

You can now use the exampleRestClient created in line 48 to query all custom resources within the example.martin-helmich.de/v1alpha1 API group. An example might look like this:

1 result := v1alpha1.ProjectList{}
2 err := exampleRestClient.
3     Get().
4     Resource("projects").
5     Do().
6     Into(&result)

In order to use your API in a more typesafe way, it is usually a good idea to wrap these operations within your own clientset. For this, create a new subpackage clientset/v1alpha1. To start, implement an interface that defines the types of your API group and move the configuration setup from your main method into that clientset’s constructor function (NewForConfig in the example below):

 1 package v1alpha1
 2 
 3 import (
 4     "github.com/martin-helmich/kubernetes-crd-example/api/types/v1alpha1"
 5     "k8s.io/apimachinery/pkg/runtime/schema"
 6     "k8s.io/apimachinery/pkg/runtime/serializer"
 7     "k8s.io/client-go/kubernetes/scheme"
 8     "k8s.io/client-go/rest"
 9 )
10 
11 type ExampleV1Alpha1Interface interface {
12     Projects(namespace string) ProjectInterface 
13 }
14 
15 type ExampleV1Alpha1Client struct {
16     restClient rest.Interface
17 }
18 
19 func NewForConfig(c *rest.Config) (*ExampleV1Alpha1Client, error) {
20     config := *c
21     config.ContentConfig.GroupVersion = &schema.GroupVersion{Group: v1alpha1.GroupName, Version: v1alpha1.GroupVersion}
22     config.APIPath = "/apis"
23     config.NegotiatedSerializer = serializer.DirectCodecFactory{CodecFactory: scheme.Codecs}
24     config.UserAgent = rest.DefaultKubernetesUserAgent()
25 
26     client, err := rest.RESTClientFor(&config)
27     if err != nil {
28         return nil, err
29     }
30 
31     return &ExampleV1Alpha1Client{restClient: client}, nil
32 }
33 
34 func (c *ExampleV1Alpha1Client) Projects(namespace string) ProjectInterface {
35     return &projectClient{
36         restClient: c.restClient,
37         ns: namespace,
38     }
39 }

The code below will not compile yet, as it’s still missing the ProjectInterface and projectClient types. We’ll get to those in a moment.

The ExampleV1Alpha1Interface and its implementation, the ExampleV1Alpha1Client struct are now the central point of entry for accessing your custom resources. You can now easily create a new clientset in your main.go by simply calling clientset, err := v1alpha1.NewForConfig(config).

Next, you’ll need to implement a specific clientset for accessing the Project custom resource (note that the example above already uses the ProjectInterface and projectClient types that we still need to supply). Create a second file projects.go in the same package:

 1 package v1alpha1
 2 
 3 import (
 4     "github.com/martin-helmich/kubernetes-crd-example/api/types/v1alpha1"
 5     metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
 6     "k8s.io/apimachinery/pkg/watch"
 7     "k8s.io/client-go/kubernetes/scheme"
 8     "k8s.io/client-go/rest"
 9 )
10 
11 type ProjectInterface interface {
12     List(opts metav1.ListOptions) (*v1alpha1.ProjectList, error)
13     Get(name string, options metav1.GetOptions) (*v1alpha1.Project, error)
14     Create(*v1alpha1.Project) (*v1alpha1.Project, error)
15     Watch(opts metav1.ListOptions) (watch.Interface, error)
16     // ...
17 }
18 
19 type projectClient struct {
20     restClient rest.Interface
21     ns         string
22 }
23 
24 func (c *projectClient) List(opts metav1.ListOptions) (*v1alpha1.ProjectList, error) {
25     result := v1alpha1.ProjectList{}
26     err := c.restClient.
27         Get().
28         Namespace(c.ns).
29         Resource("projects").
30         VersionedParams(&opts, scheme.ParameterCodec).
31         Do().
32         Into(&result)
33 
34     return &result, err
35 }
36 
37 func (c *projectClient) Get(name string, opts metav1.GetOptions) (*v1alpha1.Project, error) {
38     result := v1alpha1.Project{}
39     err := c.restClient.
40         Get().
41         Namespace(c.ns).
42         Resource("projects").
43         Name(name).
44         VersionedParams(&opts, scheme.ParameterCodec).
45         Do().
46         Into(&result)
47 
48     return &result, err
49 }
50 
51 func (c *projectClient) Create(project *v1alpha1.Project) (*v1alpha1.Project, error) {
52     result := v1alpha1.Project{}
53     err := c.restClient.
54         Post().
55         Namespace(c.ns).
56         Resource("projects").
57         Body(project).
58         Do().
59         Into(&result)
60 
61     return &result, err
62 }
63 
64 func (c *projectClient) Watch(opts metav1.ListOptions) (watch.Interface, error) {
65     opts.Watch = true
66     return c.restClient.
67         Get().
68         Namespace(c.ns).
69         Resource("projects").
70         VersionedParams(&opts, scheme.ParameterCodec).
71         Watch()
72 }

This client is obviously not yet complete and misses methods like Delete, Update and others. However, these can be implemented similar to the already existing methods. Have a look at the existing client sets (for example, the Pod client set) for inspiration.

After creating your client set, using it to list your existing resources becomes quite easy:

 1 import clientV1alpha1 "github.com/martin-helmich/kubernetes-crd-example/clientset/v1alpha1"
 2 // ...
 3 
 4 func main() {
 5     // ...
 6 
 7     clientSet, err := clientV1alpha1.NewForConfig(config)
 8     if err != nil {
 9         panic(err)
10     }
11 
12     projects, err := clientSet.Projects("default").List(metav1.ListOptions{})
13     if err != nil {
14         panic(err)
15     }
16 
17     fmt.Printf("projects found: %+v\n", projects)
18 }

Step 5: Build an informer

When building a Kubernetes Operator, you’ll typically want to be able to react on newly created or updated resources. In theory, you could just periodically call the List() method and check if new resources were added. In practice, this is a sub-optimal solution, especially when you have lots of these resources.

Most operators work by initially loading all relevant instances of a resource by using an initial List() call, and then subscribing to updates using a Watch() call. The initial object list and the updates received from the watch are then used to construct a local cache that allows quick access to any custom resources without having to hit the API server every time.

This pattern is so common that the client-go library offers a helper for this: the Informer from the k8s.io/client-go/tools/cache package. You can construct a new Informer for your custom resource as follows:

 1 package main
 2 
 3 import (
 4     "time"
 5 
 6     "github.com/martin-helmich/kubernetes-crd-example/api/types/v1alpha1"
 7     client_v1alpha1 "github.com/martin-helmich/kubernetes-crd-example/clientset/v1alpha1"
 8     metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
 9     "k8s.io/apimachinery/pkg/runtime"
10     "k8s.io/apimachinery/pkg/util/wait"
11     "k8s.io/apimachinery/pkg/watch"
12     "k8s.io/client-go/tools/cache"
13 )
14 
15 func WatchResources(clientSet client_v1alpha1.ExampleV1Alpha1Interface) cache.Store {
16     projectStore, projectController := cache.NewInformer(
17         &cache.ListWatch{
18             ListFunc: func(lo metav1.ListOptions) (result runtime.Object, err error) {
19                 return clientSet.Projects("some-namespace").List(lo)
20             },
21             WatchFunc: func(lo metav1.ListOptions) (watch.Interface, error) {
22                 return clientSet.Projects("some-namespace").Watch(lo)
23             },
24         },
25         &v1alpha1.Project{},
26         1*time.Minute,
27         cache.ResourceEventHandlerFuncs{},
28     )
29 
30     go projectController.Run(wait.NeverStop)
31     return projectStore
32 }

The NewInformer method returns two objects: The second return value, the controller controls the List() and Watch() calls and fills the first return value, the store with a (more or less) recent cache of the watched resource’s state on the API server (in this case, the project CRD).

You can now use the store to easily access your CRDs, either listing them all or accessing them by name. Keep in mind that the store functions return generic interface{} types, so you’ll have to typecast them back to your CRD type:

1 store := WatchResource(clientSet)
2 
3 project := store.GetByKey("some-namespace/some-project").(*v1alpha1.Project)

Conclusion

Building clients for Custom Resources is something that is (at least, currently) only sparsely documented and can be a bit tricky at times.

A client library for your Custom Resource as shown in this article, along with a respective Informer is a good starting point for building your own Kubernetes operator that reacts on changes made to Custom Resources. Check the Github project for this article for a complete and working version.

Comments