or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

builder.mdclient-cache.mdcore-framework.mdevent-handling.mdindex.mdsupporting-services.mdtesting.mdutilities.mdwebhooks.md
tile.json

client-cache.mddocs/

Client and Cache

The client and cache subsystem provides efficient read and write operations against Kubernetes resources with intelligent caching, field indexing, and split-reader patterns for high-performance controllers.

Overview

Controller-runtime provides a sophisticated client abstraction that combines:

  • Client - High-level CRUD operations for Kubernetes objects
  • Cache - In-memory cache with informers for efficient resource watching
  • Field Indexing - Custom indices for fast lookups by arbitrary fields
  • Split Reader - Cached reads with direct API writes for consistency

Client Package

Import Path: sigs.k8s.io/controller-runtime/pkg/client

Client Interface

package client

import (
    "context"
    "net/http"

    "k8s.io/apimachinery/pkg/api/meta"
    "k8s.io/apimachinery/pkg/runtime"
    "k8s.io/apimachinery/pkg/runtime/schema"
    "k8s.io/apimachinery/pkg/types"
    "k8s.io/apimachinery/pkg/watch"
    "k8s.io/client-go/rest"
)

// Client knows how to perform CRUD operations on Kubernetes objects
type Client interface {
    Reader
    Writer
    StatusClient
    SubResourceClientConstructor

    // Scheme returns the scheme this client is using
    Scheme() *runtime.Scheme

    // RESTMapper returns the rest mapper
    RESTMapper() meta.RESTMapper

    // GroupVersionKindFor returns the GroupVersionKind for the given object
    GroupVersionKindFor(obj runtime.Object) (schema.GroupVersionKind, error)

    // IsObjectNamespaced returns true if the GroupVersionKind is namespaced
    IsObjectNamespaced(obj runtime.Object) (bool, error)
}

Reader Interface

// Reader knows how to read and list Kubernetes objects
type Reader interface {
    // Get retrieves an obj for the given object key
    Get(ctx context.Context, key ObjectKey, obj Object, opts ...GetOption) error

    // List retrieves list of objects
    List(ctx context.Context, list ObjectList, opts ...ListOption) error
}

Writer Interface

// Writer knows how to create, delete, update and patch Kubernetes objects
type Writer interface {
    // Create saves the object obj in the Kubernetes cluster
    Create(ctx context.Context, obj Object, opts ...CreateOption) error

    // Delete deletes the given obj from Kubernetes cluster
    Delete(ctx context.Context, obj Object, opts ...DeleteOption) error

    // Update updates the given obj in the Kubernetes cluster
    Update(ctx context.Context, obj Object, opts ...UpdateOption) error

    // Patch patches the given obj in the Kubernetes cluster
    Patch(ctx context.Context, obj Object, patch Patch, opts ...PatchOption) error

    // Apply applies the given obj using server-side apply
    Apply(ctx context.Context, obj runtime.ApplyConfiguration, opts ...ApplyOption) error

    // DeleteAllOf deletes all objects of the given type matching the given options
    DeleteAllOf(ctx context.Context, obj Object, opts ...DeleteAllOfOption) error
}

StatusClient Interface

// StatusClient knows how to create a client which can update status subresource
type StatusClient interface {
    Status() SubResourceWriter
}

SubResourceWriter Interface

// SubResourceWriter knows how to update and patch the Status subresource
type SubResourceWriter interface {
    // Update updates the fields corresponding to the status subresource
    Update(ctx context.Context, obj Object, opts ...SubResourceUpdateOption) error

    // Patch patches the given object's subresource
    Patch(ctx context.Context, obj Object, patch Patch, opts ...SubResourcePatchOption) error
}

SubResourceClient Interface

// SubResourceClient knows how to perform operations on a single SubResource
type SubResourceClient interface {
    // Get retrieves the subresource for the given object
    Get(ctx context.Context, obj Object, subResource Object, opts ...SubResourceGetOption) error

    // Create creates the subresource for the given object
    Create(ctx context.Context, obj Object, subResource Object, opts ...SubResourceCreateOption) error

    // Update updates the subresource
    Update(ctx context.Context, obj Object, opts ...SubResourceUpdateOption) error

    // Patch patches the subresource
    Patch(ctx context.Context, obj Object, patch Patch, opts ...SubResourcePatchOption) error
}
// SubResourceClientConstructor knows how to create a SubResourceClient
type SubResourceClientConstructor interface {
    SubResource(subResource string) SubResourceClient
}

Creating a Client

// New creates a new Client for the given config
func New(config *rest.Config, options Options) (c Client, err error)

// NewWithWatch returns a new Client with watch capability
func NewWithWatch(config *rest.Config, options Options) (WithWatch, error)

Client Options

type Options struct {
    // HTTPClient is the HTTP client to use for requests
    HTTPClient *http.Client

    // Scheme is the scheme to use for mapping objects to GroupVersionKinds
    Scheme *runtime.Scheme

    // Mapper is the RESTMapper to use for mapping GroupVersionKinds to Resources
    Mapper meta.RESTMapper

    // Cache is the cache configuration
    Cache *CacheOptions

    // DryRun sets the client to perform dry-run requests
    DryRun *bool
}
type CacheOptions struct {
    // Reader is the cache reader to use
    Reader Reader

    // DisableFor lists the types for which caching should be disabled
    DisableFor []Object

    // Unstructured determines whether to cache unstructured objects
    Unstructured bool
}

Client Variants

// NewDryRunClient wraps an existing client to perform dry-run requests
func NewDryRunClient(c Client) Client

// NewNamespacedClient wraps an existing client to scope operations to a specific namespace
func NewNamespacedClient(c Client, ns string) Client

// WithFieldOwner wraps a client to use a specific field owner for server-side apply
func WithFieldOwner(c Client, fieldOwner string) Client

// WithFieldValidation wraps a client to use a specific field validation level
func WithFieldValidation(c Client, validation FieldValidation) Client

WithWatch Interface

// WithWatch supports both watching and reading Kubernetes objects
type WithWatch interface {
    Client
    Watch(ctx context.Context, obj ObjectList, opts ...ListOption) (watch.Interface, error)
}

Object Types

// Object is a Kubernetes object
type Object interface {
    metav1.Object
    runtime.Object
}

// ObjectList is a Kubernetes object list
type ObjectList interface {
    metav1.ListInterface
    runtime.Object
}

// ObjectKey identifies a Kubernetes Object
type ObjectKey = types.NamespacedName
// ObjectKeyFromObject creates an ObjectKey from an Object
func ObjectKeyFromObject(obj Object) ObjectKey

Field Indexing

// FieldIndexer knows how to index over a particular "field"
type FieldIndexer interface {
    // IndexField adds an index with the given field name
    IndexField(ctx context.Context, obj Object, field string, extractValue IndexerFunc) error
}

// IndexerFunc knows how to take an object and turn it into a series of non-namespaced keys
type IndexerFunc func(Object) []string

Patch Types

// Patch is a patch that can be applied to a Kubernetes object
type Patch interface {
    Type() types.PatchType
    Data(obj Object) ([]byte, error)
}

Predefined patches:

var (
    // Apply represents server-side apply patch
    Apply Patch

    // Merge represents merge patch
    Merge Patch
)

// MergeFrom creates a merge patch from an object
func MergeFrom(obj Object) Patch

// MergeFromWithOptions creates a merge patch with options
func MergeFromWithOptions(obj Object, opts ...MergeFromOption) Patch

// StrategicMergeFrom creates a strategic merge patch from an object
func StrategicMergeFrom(obj Object, opts ...MergeFromOption) Patch

// RawPatch creates a patch from raw bytes
func RawPatch(patchType types.PatchType, data []byte) Patch

// ApplyConfigurationFromUnstructured creates an ApplyConfiguration from an unstructured object
func ApplyConfigurationFromUnstructured(u *unstructured.Unstructured) runtime.ApplyConfiguration

Patch Options

type MergeFromOptions struct {
    OptimisticLock bool
}

type MergeFromWithOptimisticLock struct{}

func (MergeFromWithOptimisticLock) ApplyToMergeFrom(in *MergeFromOptions)

Common Options

List options:

type InNamespace string
type MatchingLabels map[string]string
type MatchingLabelsSelector struct {
    Selector labels.Selector
}
type MatchingFields fields.Set
type MatchingFieldsSelector struct {
    Selector fields.Selector
}
type HasLabels []string
type Limit int64
type Continue string

Update options:

type FieldOwner string
type FieldValidation string

var (
    // DryRunAll performs a dry run of the operation
    DryRunAll dryRunAll

    // ForceOwnership forces field ownership in server-side apply
    ForceOwnership forceOwnership
)

Delete options:

type GracePeriodSeconds int64

type Preconditions struct {
    UID             *types.UID
    ResourceVersion *string
}

type PropagationPolicy metav1.DeletionPropagation

func (PropagationPolicy) ApplyToDelete(*DeleteOptions)
func (PropagationPolicy) ApplyToDeleteAllOf(*DeleteAllOfOptions)

Options Types

type CreateOptions struct {
    DryRun          []string
    FieldManager    string
    FieldValidation string
    Raw             *metav1.CreateOptions
}

func (o *CreateOptions) ApplyOptions(opts []CreateOption) *CreateOptions
func (o *CreateOptions) ApplyToCreate(co *CreateOptions)
func (o *CreateOptions) AsCreateOptions() *metav1.CreateOptions

type DeleteOptions struct {
    GracePeriodSeconds *int64
    Preconditions      *Preconditions
    PropagationPolicy  *metav1.DeletionPropagation
    Raw                *metav1.DeleteOptions
    DryRun             []string
}

func (o *DeleteOptions) ApplyOptions(opts []DeleteOption) *DeleteOptions
func (o *DeleteOptions) ApplyToDelete(do *DeleteOptions)
func (o *DeleteOptions) AsDeleteOptions() *metav1.DeleteOptions

type DeleteAllOfOptions struct {
    ListOptions
    DeleteOptions
}

func (o *DeleteAllOfOptions) ApplyOptions(opts []DeleteAllOfOption) *DeleteAllOfOptions
func (o *DeleteAllOfOptions) ApplyToDeleteAllOf(do *DeleteAllOfOptions)

type UpdateOptions struct {
    DryRun          []string
    FieldManager    string
    FieldValidation string
    Raw             *metav1.UpdateOptions
}

func (o *UpdateOptions) ApplyOptions(opts []UpdateOption) *UpdateOptions
func (o *UpdateOptions) ApplyToUpdate(uo *UpdateOptions)
func (o *UpdateOptions) AsUpdateOptions() *metav1.UpdateOptions

type ListOptions struct {
    LabelSelector labels.Selector
    FieldSelector fields.Selector
    Namespace     string
    Limit         int64
    Continue      string
    Raw           *metav1.ListOptions
    UnsafeDisableDeepCopy bool
}

func (o *ListOptions) ApplyOptions(opts []ListOption) *ListOptions
func (o *ListOptions) ApplyToList(lo *ListOptions)
func (o *ListOptions) AsListOptions() *metav1.ListOptions

type PatchOptions struct {
    DryRun          []string
    Force           *bool
    FieldManager    string
    FieldValidation string
    Raw             *metav1.PatchOptions
}

func (o *PatchOptions) ApplyOptions(opts []PatchOption) *PatchOptions
func (o *PatchOptions) ApplyToPatch(po *PatchOptions)
func (o *PatchOptions) AsPatchOptions() *metav1.PatchOptions

SubResource Options

type SubResourceCreateOptions struct {
    CreateOptions
    SubResourceBody Object
}

func (o *SubResourceCreateOptions) ApplyOptions(opts []SubResourceCreateOption) *SubResourceCreateOptions
func (o *SubResourceCreateOptions) ApplyToSubResourceCreate(sco *SubResourceCreateOptions)

type SubResourceGetOptions struct {
    Raw *metav1.GetOptions
}

func (o *SubResourceGetOptions) ApplyOptions(opts []SubResourceGetOption) *SubResourceGetOptions
func (o *SubResourceGetOptions) ApplyToSubResourceGet(sgo *SubResourceGetOptions)
func (o *SubResourceGetOptions) AsGetOptions() *metav1.GetOptions

type SubResourcePatchOptions struct {
    PatchOptions
    SubResourceBody Object
}

func (o *SubResourcePatchOptions) ApplyOptions(opts []SubResourcePatchOption) *SubResourcePatchOptions
func (o *SubResourcePatchOptions) ApplyToSubResourcePatch(spo *SubResourcePatchOptions)

type SubResourceUpdateOptions struct {
    UpdateOptions
    SubResourceBody Object
}

func (o *SubResourceUpdateOptions) ApplyOptions(opts []SubResourceUpdateOption) *SubResourceUpdateOptions
func (o *SubResourceUpdateOptions) ApplyToSubResourceUpdate(suo *SubResourceUpdateOptions)

// WithSubResourceBody returns an option that uses the given body for a subresource Update or Patch
func WithSubResourceBody(body Object) SubResourceUpdateAndPatchOption

type SubResourceUpdateAndPatchOption interface {
    ApplyToSubResourceUpdate(*SubResourceUpdateOptions)
    ApplyToSubResourcePatch(*SubResourcePatchOptions)
}

StatusWriter and SubResource Interfaces

// StatusWriter is kept for backward compatibility
type StatusWriter = SubResourceWriter

type SubResourceReader interface {
    Get(ctx context.Context, obj Object, subResource Object, opts ...SubResourceGetOption) error
}

Error Handling

// IgnoreNotFound returns nil if the error is a NotFound error
func IgnoreNotFound(err error) error

// IgnoreAlreadyExists returns nil if the error is an AlreadyExists error
func IgnoreAlreadyExists(err error) error

Unsafe Options

// UnsafeDisableDeepCopy indicates not to deep copy objects during list operations
const UnsafeDisableDeepCopy UnsafeDisableDeepCopyOption = true

type UnsafeDisableDeepCopyOption bool

Client Usage Example

package example

import (
    "context"
    "fmt"

    corev1 "k8s.io/api/core/v1"
    metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    "k8s.io/apimachinery/pkg/types"
    "sigs.k8s.io/controller-runtime/pkg/client"
)

func ClientExample(c client.Client) error {
    ctx := context.Background()

    // Get a single object
    var pod corev1.Pod
    err := c.Get(ctx, types.NamespacedName{
        Namespace: "default",
        Name:      "my-pod",
    }, &pod)
    if err != nil {
        return client.IgnoreNotFound(err)
    }

    // List objects
    var podList corev1.PodList
    err = c.List(ctx, &podList,
        client.InNamespace("default"),
        client.MatchingLabels{"app": "my-app"},
    )
    if err != nil {
        return err
    }

    // Create an object
    newPod := &corev1.Pod{
        ObjectMeta: metav1.ObjectMeta{
            Name:      "new-pod",
            Namespace: "default",
        },
        Spec: corev1.PodSpec{
            Containers: []corev1.Container{
                {
                    Name:  "nginx",
                    Image: "nginx:latest",
                },
            },
        },
    }
    if err := c.Create(ctx, newPod); err != nil {
        return err
    }

    // Update an object
    pod.Labels = map[string]string{"updated": "true"}
    if err := c.Update(ctx, &pod); err != nil {
        return err
    }

    // Patch an object
    patch := client.MergeFrom(pod.DeepCopy())
    pod.Annotations = map[string]string{"patched": "true"}
    if err := c.Patch(ctx, &pod, patch); err != nil {
        return err
    }

    // Update status subresource
    pod.Status.Phase = corev1.PodRunning
    if err := c.Status().Update(ctx, &pod); err != nil {
        return err
    }

    // Delete an object
    if err := c.Delete(ctx, &pod); err != nil {
        return err
    }

    return nil
}

Cache Package

Import Path: sigs.k8s.io/controller-runtime/pkg/cache

Cache Interface

package cache

import (
    "context"
    "net/http"
    "time"

    "k8s.io/apimachinery/pkg/api/meta"
    "k8s.io/apimachinery/pkg/fields"
    "k8s.io/apimachinery/pkg/labels"
    "k8s.io/apimachinery/pkg/runtime"
    "k8s.io/apimachinery/pkg/runtime/schema"
    "k8s.io/client-go/rest"
    toolscache "k8s.io/client-go/tools/cache"
    "sigs.k8s.io/controller-runtime/pkg/client"
)

// Cache knows how to load Kubernetes objects, fetch informers to request to receive events
type Cache interface {
    // Reader reads objects from the cache
    client.Reader

    // Informers knows how to create or fetch informers
    Informers
}

Informers Interface

// Informers knows how to create or fetch informers for different group-version-kinds
type Informers interface {
    // GetInformer fetches or constructs an informer for the given object
    GetInformer(ctx context.Context, obj client.Object, opts ...InformerGetOption) (Informer, error)

    // GetInformerForKind fetches or constructs an informer for the given GVK
    GetInformerForKind(ctx context.Context, gvk schema.GroupVersionKind, opts ...InformerGetOption) (Informer, error)

    // RemoveInformer removes an informer entry
    RemoveInformer(ctx context.Context, obj client.Object) error

    // Start starts running all the informers
    Start(ctx context.Context) error

    // WaitForCacheSync waits for all started informers to sync
    WaitForCacheSync(ctx context.Context) bool

    // FieldIndexer adds a field index to the cache
    client.FieldIndexer
}

Informer Interface

// Informer allows you to interact with the underlying informer
type Informer interface {
    // AddEventHandler adds an event handler
    AddEventHandler(handler toolscache.ResourceEventHandler) (toolscache.ResourceEventHandlerRegistration, error)

    // AddEventHandlerWithResyncPeriod adds an event handler with a specific resync period
    AddEventHandlerWithResyncPeriod(handler toolscache.ResourceEventHandler, resyncPeriod time.Duration) (toolscache.ResourceEventHandlerRegistration, error)

    // AddEventHandlerWithOptions adds an event handler with options
    AddEventHandlerWithOptions(handler toolscache.ResourceEventHandler, options toolscache.HandlerOptions) (toolscache.ResourceEventHandlerRegistration, error)

    // RemoveEventHandler removes an event handler
    RemoveEventHandler(handle toolscache.ResourceEventHandlerRegistration) error

    // AddIndexers adds indexers to this informer
    AddIndexers(indexers toolscache.Indexers) error

    // HasSynced returns true if the informer's store has been synced
    HasSynced() bool

    // IsStopped returns true if the informer has been stopped
    IsStopped() bool
}

Creating a Cache

// New creates a new Cache for the given config and options
func New(cfg *rest.Config, opts Options) (Cache, error)

Cache Options

type Options struct {
    // HTTPClient is the HTTP client to use for requests
    HTTPClient *http.Client

    // Scheme is the scheme to use for caching objects
    Scheme *runtime.Scheme

    // Mapper is the RESTMapper to use
    Mapper meta.RESTMapper

    // SyncPeriod determines the minimum frequency at which watched resources are reconciled
    SyncPeriod *time.Duration

    // ReaderFailOnMissingInformer makes the cache reader return an error if an informer is not found
    ReaderFailOnMissingInformer bool

    // DefaultNamespaces maps namespaces to cache configs
    DefaultNamespaces map[string]Config

    // DefaultLabelSelector is the default label selector for all objects
    DefaultLabelSelector labels.Selector

    // DefaultFieldSelector is the default field selector for all objects
    DefaultFieldSelector fields.Selector

    // DefaultTransform is the default transform function for all objects
    DefaultTransform toolscache.TransformFunc

    // DefaultWatchErrorHandler is the default watch error handler
    DefaultWatchErrorHandler toolscache.WatchErrorHandlerWithContext

    // DefaultUnsafeDisableDeepCopy indicates to disable deep-copying by default
    DefaultUnsafeDisableDeepCopy *bool

    // DefaultEnableWatchBookmarks indicates to enable watch bookmarks by default
    DefaultEnableWatchBookmarks *bool

    // ByObject allows configuring cache behavior per-object
    ByObject map[client.Object]ByObject

    // NewInformer allows customizing how informers are created
    NewInformer func(toolscache.ListerWatcher, runtime.Object, time.Duration, toolscache.Indexers) toolscache.SharedIndexInformer
}

Per-Object Configuration

// ByObject offers fine-grained control over the cache's ListWatch by object
type ByObject struct {
    // Namespaces maps namespace names to cache configs for that namespace
    Namespaces map[string]Config

    // Label is a label selector to restrict the cache to objects matching this selector
    Label labels.Selector

    // Field is a field selector to restrict the cache to objects matching this selector
    Field fields.Selector

    // Transform is a transformation function for objects before caching
    Transform toolscache.TransformFunc

    // UnsafeDisableDeepCopy indicates whether to disable deep-copying for this type
    UnsafeDisableDeepCopy *bool

    // EnableWatchBookmarks indicates whether to enable watch bookmarks for this type
    EnableWatchBookmarks *bool

    // SyncPeriod determines the minimum frequency at which this resource is reconciled
    SyncPeriod *time.Duration
}
// Config describes all potential options for a given watch
type Config struct {
    LabelSelector             labels.Selector
    FieldSelector             fields.Selector
    Transform                 toolscache.TransformFunc
    UnsafeDisableDeepCopy     *bool
    EnableWatchBookmarks      *bool
    SyncPeriod                *time.Duration
}

Namespace Constants

// AllNamespaces should be used as the map key to specify cache settings for all namespaces
const AllNamespaces = metav1.NamespaceAll

Informer Get Options

type InformerGetOption func(*InformerGetOptions)

type InformerGetOptions internal.GetOptions

// BlockUntilSynced blocks until the informer has synced
func BlockUntilSynced(shouldBlock bool) InformerGetOption

Transform Functions

// TransformStripManagedFields strips the managed fields of an object before caching
func TransformStripManagedFields() toolscache.TransformFunc

Cache Errors

// ErrCacheNotStarted is returned when trying to read from a cache that wasn't started
type ErrCacheNotStarted struct{}

func (*ErrCacheNotStarted) Error() string
// ErrResourceNotCached indicates that the resource type is not cached
type ErrResourceNotCached struct {
    GVK schema.GroupVersionKind
}

func (r ErrResourceNotCached) Error() string

NewCacheFunc

// NewCacheFunc is a function for creating a new cache from options and config
type NewCacheFunc func(config *rest.Config, opts Options) (Cache, error)

Cache Usage Example

package example

import (
    "context"
    "fmt"
    "time"

    corev1 "k8s.io/api/core/v1"
    "k8s.io/apimachinery/pkg/labels"
    toolscache "k8s.io/client-go/tools/cache"
    "sigs.k8s.io/controller-runtime/pkg/cache"
    "sigs.k8s.io/controller-runtime/pkg/client"
    "sigs.k8s.io/controller-runtime/pkg/client/config"
)

func CacheExample() error {
    // Get rest config
    cfg, err := config.GetConfig()
    if err != nil {
        return err
    }

    // Create cache with custom options
    c, err := cache.New(cfg, cache.Options{
        // Only watch default namespace
        DefaultNamespaces: map[string]cache.Config{
            "default": {},
        },
        // Only cache pods with specific label
        ByObject: map[client.Object]cache.ByObject{
            &corev1.Pod{}: {
                Label: labels.SelectorFromSet(labels.Set{"app": "my-app"}),
            },
        },
        // Strip managed fields to reduce memory usage
        DefaultTransform: cache.TransformStripManagedFields(),
    })
    if err != nil {
        return err
    }

    // Start the cache
    ctx, cancel := context.WithCancel(context.Background())
    defer cancel()

    go func() {
        if err := c.Start(ctx); err != nil {
            fmt.Printf("Error starting cache: %v\n", err)
        }
    }()

    // Wait for cache to sync
    if !c.WaitForCacheSync(ctx) {
        return fmt.Errorf("failed to sync cache")
    }

    // Get an informer
    informer, err := c.GetInformer(ctx, &corev1.Pod{})
    if err != nil {
        return err
    }

    // Add event handler
    _, err = informer.AddEventHandler(toolscache.ResourceEventHandlerFuncs{
        AddFunc: func(obj interface{}) {
            pod := obj.(*corev1.Pod)
            fmt.Printf("Pod added: %s/%s\n", pod.Namespace, pod.Name)
        },
        UpdateFunc: func(oldObj, newObj interface{}) {
            pod := newObj.(*corev1.Pod)
            fmt.Printf("Pod updated: %s/%s\n", pod.Namespace, pod.Name)
        },
        DeleteFunc: func(obj interface{}) {
            pod := obj.(*corev1.Pod)
            fmt.Printf("Pod deleted: %s/%s\n", pod.Namespace, pod.Name)
        },
    })
    if err != nil {
        return err
    }

    // Add field indexer for custom lookups
    if err := c.IndexField(ctx, &corev1.Pod{}, "spec.nodeName", func(obj client.Object) []string {
        pod := obj.(*corev1.Pod)
        return []string{pod.Spec.NodeName}
    }); err != nil {
        return err
    }

    // List pods using the cache
    var podList corev1.PodList
    if err := c.List(ctx, &podList, client.InNamespace("default")); err != nil {
        return err
    }

    fmt.Printf("Found %d pods in cache\n", len(podList.Items))

    return nil
}

Client Sub-packages

APIUtil Package

Import Path: sigs.k8s.io/controller-runtime/pkg/client/apiutil

Utilities for working with APIs and schemes.

package apiutil

import (
    "net/http"

    "k8s.io/apimachinery/pkg/api/meta"
    "k8s.io/apimachinery/pkg/runtime"
    "k8s.io/apimachinery/pkg/runtime/schema"
    "k8s.io/apimachinery/pkg/runtime/serializer"
    "k8s.io/client-go/rest"
)

// GVKForObject returns the GroupVersionKind for the given object
func GVKForObject(obj runtime.Object, scheme *runtime.Scheme) (schema.GroupVersionKind, error)

// IsGVKNamespaced returns true if the GVK is namespaced
func IsGVKNamespaced(gvk schema.GroupVersionKind, restmapper meta.RESTMapper) (bool, error)

// IsObjectNamespaced returns true if the object is namespaced
func IsObjectNamespaced(obj runtime.Object, scheme *runtime.Scheme, restmapper meta.RESTMapper) (bool, error)

// NewDynamicRESTMapper creates a dynamic RESTMapper
func NewDynamicRESTMapper(cfg *rest.Config, httpClient *http.Client) (meta.RESTMapper, error)

// RESTClientForGVK creates a REST client for the given GVK
func RESTClientForGVK(
    gvk schema.GroupVersionKind,
    forceDisableProtoBuf bool,
    isUnstructured bool,
    baseConfig *rest.Config,
    codecs serializer.CodecFactory,
    httpClient *http.Client,
) (rest.Interface, error)

// AddToProtobufScheme adds the protobuf scheme to the given scheme builder
func AddToProtobufScheme(addToScheme func(*runtime.Scheme) error) error
// ErrResourceDiscoveryFailed is returned when resource discovery fails
type ErrResourceDiscoveryFailed map[schema.GroupVersion]error

func (e *ErrResourceDiscoveryFailed) Error() string
func (e *ErrResourceDiscoveryFailed) Unwrap() []error

Config Package

Import Path: sigs.k8s.io/controller-runtime/pkg/client/config

Utilities for loading Kubernetes client configuration.

package config

import (
    "flag"

    "k8s.io/client-go/rest"
)

const KubeconfigFlagName = "kubeconfig"

// GetConfig returns the default Kubernetes client config
func GetConfig() (*rest.Config, error)

// GetConfigOrDie returns the config or panics
func GetConfigOrDie() *rest.Config

// GetConfigWithContext returns the config for a specific context
func GetConfigWithContext(context string) (*rest.Config, error)

// RegisterFlags registers kubeconfig flags
func RegisterFlags(fs *flag.FlagSet)

Fake Package

Import Path: sigs.k8s.io/controller-runtime/pkg/client/fake

Fake client for unit testing.

package fake

import (
    "k8s.io/apimachinery/pkg/api/meta"
    "k8s.io/apimachinery/pkg/runtime"
    "k8s.io/client-go/testing"
    "sigs.k8s.io/controller-runtime/pkg/client"
    "sigs.k8s.io/controller-runtime/pkg/client/interceptor"
)

// NewFakeClient creates a new fake client
func NewFakeClient(initObjs ...runtime.Object) client.WithWatch

// AddIndex adds an index to the fake client
func AddIndex(c client.Client, obj runtime.Object, field string, extractValue client.IndexerFunc) error
// ClientBuilder builds fake clients
type ClientBuilder struct {
    // Has unexported fields
}

// NewClientBuilder creates a new ClientBuilder
func NewClientBuilder() *ClientBuilder

func (f *ClientBuilder) Build() client.WithWatch
func (f *ClientBuilder) WithObjects(initObjs ...client.Object) *ClientBuilder
func (f *ClientBuilder) WithLists(initLists ...client.ObjectList) *ClientBuilder
func (f *ClientBuilder) WithRuntimeObjects(initRuntimeObjs ...runtime.Object) *ClientBuilder
func (f *ClientBuilder) WithScheme(scheme *runtime.Scheme) *ClientBuilder
func (f *ClientBuilder) WithRESTMapper(restMapper meta.RESTMapper) *ClientBuilder
func (f *ClientBuilder) WithStatusSubresource(o ...client.Object) *ClientBuilder
func (f *ClientBuilder) WithIndex(obj runtime.Object, field string, extractValue client.IndexerFunc) *ClientBuilder
func (f *ClientBuilder) WithObjectTracker(ot testing.ObjectTracker) *ClientBuilder
func (f *ClientBuilder) WithInterceptorFuncs(interceptorFuncs interceptor.Funcs) *ClientBuilder
func (f *ClientBuilder) WithReturnManagedFields() *ClientBuilder

Interceptor Package

Import Path: sigs.k8s.io/controller-runtime/pkg/client/interceptor

Client interceptors for customizing client behavior.

package interceptor

import (
    "context"

    "k8s.io/apimachinery/pkg/runtime"
    "k8s.io/apimachinery/pkg/watch"
    "sigs.k8s.io/controller-runtime/pkg/client"
)

// NewClient creates a new client with interceptors
func NewClient(interceptedClient client.WithWatch, funcs Funcs) client.WithWatch
// Funcs contains functions that are called instead of the underlying client's methods
type Funcs struct {
    Get               func(ctx context.Context, client client.WithWatch, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error
    List              func(ctx context.Context, client client.WithWatch, list client.ObjectList, opts ...client.ListOption) error
    Create            func(ctx context.Context, client client.WithWatch, obj client.Object, opts ...client.CreateOption) error
    Delete            func(ctx context.Context, client client.WithWatch, obj client.Object, opts ...client.DeleteOption) error
    DeleteAllOf       func(ctx context.Context, client client.WithWatch, obj client.Object, opts ...client.DeleteAllOfOption) error
    Update            func(ctx context.Context, client client.WithWatch, obj client.Object, opts ...client.UpdateOption) error
    Patch             func(ctx context.Context, client client.WithWatch, obj client.Object, patch client.Patch, opts ...client.PatchOption) error
    Apply             func(ctx context.Context, client client.WithWatch, obj runtime.ApplyConfiguration, opts ...client.ApplyOption) error
    Watch             func(ctx context.Context, client client.WithWatch, obj client.ObjectList, opts ...client.ListOption) (watch.Interface, error)
    SubResource       func(client client.WithWatch, subResource string) client.SubResourceClient
    SubResourceGet    func(ctx context.Context, client client.Client, subResourceName string, obj client.Object, subResource client.Object, opts ...client.SubResourceGetOption) error
    SubResourceCreate func(ctx context.Context, client client.Client, subResourceName string, obj client.Object, subResource client.Object, opts ...client.SubResourceCreateOption) error
    SubResourceUpdate func(ctx context.Context, client client.Client, subResourceName string, obj client.Object, opts ...client.SubResourceUpdateOption) error
    SubResourcePatch  func(ctx context.Context, client client.Client, subResourceName string, obj client.Object, patch client.Patch, opts ...client.SubResourcePatchOption) error
}