controller-runtime: github.com/kubernetes-sigs/controller-runtime/pkg/client Index | Examples | Files | Directories

package client

import "github.com/kubernetes-sigs/controller-runtime/pkg/client"

Package client contains functionality for interacting with Kubernetes API servers.

Clients

Clients are split into two interfaces -- Readers and Writers. Readers get and list, while writers create, update, and delete.

The New function can be used to create a new client that talks directly to the API server.

A common pattern in Kubernetes to read from a cache and write to the API server. This pattern is covered by the DelegatingClient type, which can be used to have a client whose Reader is different from the Writer.

Options

Many client operations in Kubernetes support options. These options are represented as variadic arguments at the end of a given method call. For instance, to use a label selector on list, you can call

err := someReader.List(context.Background(), &podList, client.MatchingLabels(someLabelMap))

Indexing

Indexes may be added to caches using a FieldIndexer. This allows you to easily and efficiently look up objects with certain properties. You can then make use of the index by specifying a field selector on calls to List on the Reader corresponding to the given Cache.

For instance, a Secret controller might have an index on the `.spec.volumes.secret.secretName` field in Pod objects, so that it could easily look up all pods that reference a given secret.

Index

Examples

Package Files

client.go client_cache.go doc.go interfaces.go options.go patch.go split.go typed_client.go unstructured_client.go

Variables

var (
    // Apply uses server-side apply to patch the given object.
    Apply = applyPatch{}
)

func IgnoreNotFound Uses

func IgnoreNotFound(err error) error

IgnoreNotFound returns nil on NotFound errors. All other values that are not NotFound errors or nil are returned unmodified.

type Client Uses

type Client interface {
    Reader
    Writer
    StatusClient
}

Client knows how to perform CRUD operations on Kubernetes objects.

This example shows how to use the client with typed and unstrucurted objects to create objects.

Code:

// Using a typed object.
pod := &corev1.Pod{
    ObjectMeta: metav1.ObjectMeta{
        Namespace: "namespace",
        Name:      "name",
    },
    Spec: corev1.PodSpec{
        Containers: []corev1.Container{
            corev1.Container{
                Image: "nginx",
                Name:  "nginx",
            },
        },
    },
}
// c is a created client.
_ = c.Create(context.Background(), pod)

// Using a unstructured object.
u := &unstructured.Unstructured{}
u.Object = map[string]interface{}{
    "name":      "name",
    "namespace": "namespace",
    "spec": map[string]interface{}{
        "replicas": 2,
        "selector": map[string]interface{}{
            "matchLabels": map[string]interface{}{
                "foo": "bar",
            },
        },
        "template": map[string]interface{}{
            "labels": map[string]interface{}{
                "foo": "bar",
            },
            "spec": map[string]interface{}{
                "containers": []map[string]interface{}{
                    {
                        "name":  "nginx",
                        "image": "nginx",
                    },
                },
            },
        },
    },
}
u.SetGroupVersionKind(schema.GroupVersionKind{
    Group:   "apps",
    Kind:    "Deployment",
    Version: "v1",
})
_ = c.Create(context.Background(), u)

This example shows how to use the client with typed and unstrucurted objects to delete objects.

Code:

// Using a typed object.
pod := &corev1.Pod{
    ObjectMeta: metav1.ObjectMeta{
        Namespace: "namespace",
        Name:      "name",
    },
}
// c is a created client.
_ = c.Delete(context.Background(), pod)

// Using a unstructured object.
u := &unstructured.Unstructured{}
u.Object = map[string]interface{}{
    "name":      "name",
    "namespace": "namespace",
}
u.SetGroupVersionKind(schema.GroupVersionKind{
    Group:   "apps",
    Kind:    "Deployment",
    Version: "v1",
})
_ = c.Delete(context.Background(), u)

This example shows how to use the client with typed and unstructured objects to retrieve a objects.

Code:

// Using a typed object.
pod := &corev1.Pod{}
// c is a created client.
_ = c.Get(context.Background(), client.ObjectKey{
    Namespace: "namespace",
    Name:      "name",
}, pod)

// Using a unstructured object.
u := &unstructured.Unstructured{}
u.SetGroupVersionKind(schema.GroupVersionKind{
    Group:   "apps",
    Kind:    "Deployment",
    Version: "v1",
})
_ = c.Get(context.Background(), client.ObjectKey{
    Namespace: "namespace",
    Name:      "name",
}, u)

This example shows how to use the client with typed and unstrucurted objects to list objects.

Code:

// Using a typed object.
pod := &corev1.PodList{}
// c is a created client.
_ = c.List(context.Background(), pod)

// Using a unstructured object.
u := &unstructured.UnstructuredList{}
u.SetGroupVersionKind(schema.GroupVersionKind{
    Group:   "apps",
    Kind:    "DeploymentList",
    Version: "v1",
})
_ = c.List(context.Background(), u)

This example shows how to use the client with typed and unstrucurted objects to update objects.

Code:

// Using a typed object.
pod := &corev1.Pod{}
// c is a created client.
_ = c.Get(context.Background(), client.ObjectKey{
    Namespace: "namespace",
    Name:      "name",
}, pod)
pod.SetFinalizers(append(pod.GetFinalizers(), "new-finalizer"))
_ = c.Update(context.Background(), pod)

// Using a unstructured object.
u := &unstructured.Unstructured{}
u.SetGroupVersionKind(schema.GroupVersionKind{
    Group:   "apps",
    Kind:    "Deployment",
    Version: "v1",
})
_ = c.Get(context.Background(), client.ObjectKey{
    Namespace: "namespace",
    Name:      "name",
}, u)
u.SetFinalizers(append(u.GetFinalizers(), "new-finalizer"))
_ = c.Update(context.Background(), u)

func New Uses

func New(config *rest.Config, options Options) (Client, error)

New returns a new Client using the provided config and Options. The returned client reads *and* writes directly from the server (it doesn't use object caches). It understands how to work with normal types (both custom resources and aggregated/built-in resources), as well as unstructured types.

In the case of normal types, the scheme will be used to look up the corresponding group, version, and kind for the given type. In the case of unstrctured types, the group, version, and kind will be extracted from the corresponding fields on the object.

Code:

cl, err := client.New(config.GetConfigOrDie(), client.Options{})
if err != nil {
    fmt.Println("failed to create client")
    os.Exit(1)
}

podList := &corev1.PodList{}

err = cl.List(context.Background(), podList, client.InNamespace("default"))
if err != nil {
    fmt.Printf("failed to list pods in namespace default: %v\n", err)
    os.Exit(1)
}

type CreateOptionFunc Uses

type CreateOptionFunc func(*CreateOptions)

CreateOptionFunc is a function that mutates a CreateOptions struct. It implements the functional options pattern. See https://github.com/tmrts/go-patterns/blob/master/idiom/functional-options.md.

var CreateDryRunAll CreateOptionFunc = func(opts *CreateOptions) {
    opts.DryRun = []string{metav1.DryRunAll}
}

CreateDryRunAll is a functional option that sets the DryRun field of a CreateOptions struct to metav1.DryRunAll.

type CreateOptions Uses

type CreateOptions struct {
    // When present, indicates that modifications should not be
    // persisted. An invalid or unrecognized dryRun directive will
    // result in an error response and no further processing of the
    // request. Valid values are:
    // - All: all dry run stages will be processed
    DryRun []string

    // Raw represents raw CreateOptions, as passed to the API server.
    Raw *metav1.CreateOptions
}

CreateOptions contains options for create requests. It's generally a subset of metav1.CreateOptions.

func (*CreateOptions) ApplyOptions Uses

func (o *CreateOptions) ApplyOptions(optFuncs []CreateOptionFunc) *CreateOptions

ApplyOptions executes the given CreateOptionFuncs and returns the mutated CreateOptions.

func (*CreateOptions) AsCreateOptions Uses

func (o *CreateOptions) AsCreateOptions() *metav1.CreateOptions

AsCreateOptions returns these options as a metav1.CreateOptions. This may mutate the Raw field.

type DelegatingClient Uses

type DelegatingClient struct {
    Reader
    Writer
    StatusClient
}

DelegatingClient forms a Client by composing separate reader, writer and statusclient interfaces. This way, you can have an Client that reads from a cache and writes to the API server.

type DelegatingReader Uses

type DelegatingReader struct {
    CacheReader  Reader
    ClientReader Reader
}

DelegatingReader forms a Reader that will cause Get and List requests for unstructured types to use the ClientReader while requests for any other type of object with use the CacheReader. This avoids accidentally caching the entire cluster in the common case of loading arbitrary unstructured objects (e.g. from OwnerReferences).

func (*DelegatingReader) Get Uses

func (d *DelegatingReader) Get(ctx context.Context, key ObjectKey, obj runtime.Object) error

Get retrieves an obj for a given object key from the Kubernetes Cluster.

func (*DelegatingReader) List Uses

func (d *DelegatingReader) List(ctx context.Context, list runtime.Object, opts ...ListOptionFunc) error

List retrieves list of objects for a given namespace and list options.

type DeleteOptionFunc Uses

type DeleteOptionFunc func(*DeleteOptions)

DeleteOptionFunc is a function that mutates a DeleteOptions struct. It implements the functional options pattern. See https://github.com/tmrts/go-patterns/blob/master/idiom/functional-options.md.

func GracePeriodSeconds Uses

func GracePeriodSeconds(gp int64) DeleteOptionFunc

GracePeriodSeconds is a functional option that sets the GracePeriodSeconds field of a DeleteOptions struct.

func Preconditions Uses

func Preconditions(p *metav1.Preconditions) DeleteOptionFunc

Preconditions is a functional option that sets the Preconditions field of a DeleteOptions struct.

func PropagationPolicy Uses

func PropagationPolicy(p metav1.DeletionPropagation) DeleteOptionFunc

PropagationPolicy is a functional option that sets the PropagationPolicy field of a DeleteOptions struct.

type DeleteOptions Uses

type DeleteOptions struct {
    // GracePeriodSeconds is the duration in seconds before the object should be
    // deleted. Value must be non-negative integer. The value zero indicates
    // delete immediately. If this value is nil, the default grace period for the
    // specified type will be used.
    GracePeriodSeconds *int64

    // Preconditions must be fulfilled before a deletion is carried out. If not
    // possible, a 409 Conflict status will be returned.
    Preconditions *metav1.Preconditions

    // PropagationPolicy determined whether and how garbage collection will be
    // performed. Either this field or OrphanDependents may be set, but not both.
    // The default policy is decided by the existing finalizer set in the
    // metadata.finalizers and the resource-specific default policy.
    // Acceptable values are: 'Orphan' - orphan the dependents; 'Background' -
    // allow the garbage collector to delete the dependents in the background;
    // 'Foreground' - a cascading policy that deletes all dependents in the
    // foreground.
    PropagationPolicy *metav1.DeletionPropagation

    // Raw represents raw DeleteOptions, as passed to the API server.
    Raw *metav1.DeleteOptions
}

DeleteOptions contains options for delete requests. It's generally a subset of metav1.DeleteOptions.

func (*DeleteOptions) ApplyOptions Uses

func (o *DeleteOptions) ApplyOptions(optFuncs []DeleteOptionFunc) *DeleteOptions

ApplyOptions executes the given DeleteOptionFuncs and returns the mutated DeleteOptions.

func (*DeleteOptions) AsDeleteOptions Uses

func (o *DeleteOptions) AsDeleteOptions() *metav1.DeleteOptions

AsDeleteOptions returns these options as a metav1.DeleteOptions. This may mutate the Raw field.

type FieldIndexer Uses

type FieldIndexer interface {
    // IndexFields adds an index with the given field name on the given object type
    // by using the given function to extract the value for that field.  If you want
    // compatibility with the Kubernetes API server, only return one key, and only use
    // fields that the API server supports.  Otherwise, you can return multiple keys,
    // and "equality" in the field selector means that at least one key matches the value.
    // The FieldIndexer will automatically take care of indexing over namespace
    // and supporting efficient all-namespace queries.
    IndexField(obj runtime.Object, field string, extractValue IndexerFunc) error
}

FieldIndexer knows how to index over a particular "field" such that it can later be used by a field selector.

This example shows how to set up and consume a field selector over a pod's volumes' secretName field.

Code:

// someIndexer is a FieldIndexer over a Cache
_ = someIndexer.IndexField(&corev1.Pod{}, "spec.volumes.secret.secretName", func(o runtime.Object) []string {
    var res []string
    for _, vol := range o.(*corev1.Pod).Spec.Volumes {
        if vol.Secret == nil {
            continue
        }
        // just return the raw field value -- the indexer will take care of dealing with namespaces for us
        res = append(res, vol.Secret.SecretName)
    }
    return res
})

// elsewhere (e.g. in your reconciler)
mySecretName := "someSecret" // derived from the reconcile.Request, for instance
var podsWithSecrets corev1.PodList
_ = c.List(context.Background(), &podsWithSecrets, client.MatchingField("spec.volumes.secret.secretName", mySecretName))

type IndexerFunc Uses

type IndexerFunc func(runtime.Object) []string

IndexerFunc knows how to take an object and turn it into a series of non-namespaced keys. Namespaced objects are automatically given namespaced and non-spaced variants, so keys do not need to include namespace.

type ListOptionFunc Uses

type ListOptionFunc func(*ListOptions)

ListOptionFunc is a function that mutates a ListOptions struct. It implements the functional options pattern. See https://github.com/tmrts/go-patterns/blob/master/idiom/functional-options.md.

func InNamespace Uses

func InNamespace(ns string) ListOptionFunc

InNamespace is a functional option that sets the Namespace field of a ListOptions struct.

func MatchingField Uses

func MatchingField(name, val string) ListOptionFunc

MatchingField is a functional option that sets the FieldSelector field of a ListOptions struct.

func MatchingLabels Uses

func MatchingLabels(lbls map[string]string) ListOptionFunc

MatchingLabels is a functional option that sets the LabelSelector field of a ListOptions struct.

func UseListOptions Uses

func UseListOptions(newOpts *ListOptions) ListOptionFunc

UseListOptions is a functional option that replaces the fields of a ListOptions struct with those of a different ListOptions struct.

Example: cl.List(ctx, list, client.UseListOptions(lo.InNamespace(ns).MatchingLabels(labels)))

type ListOptions Uses

type ListOptions struct {
    // LabelSelector filters results by label.  Use SetLabelSelector to
    // set from raw string form.
    LabelSelector labels.Selector
    // FieldSelector filters results by a particular field.  In order
    // to use this with cache-based implementations, restrict usage to
    // a single field-value pair that's been added to the indexers.
    FieldSelector fields.Selector

    // Namespace represents the namespace to list for, or empty for
    // non-namespaced objects, or to list across all namespaces.
    Namespace string

    // Raw represents raw ListOptions, as passed to the API server.  Note
    // that these may not be respected by all implementations of interface,
    // and the LabelSelector and FieldSelector fields are ignored.
    Raw *metav1.ListOptions
}

ListOptions contains options for limiting or filtering results. It's generally a subset of metav1.ListOptions, with support for pre-parsed selectors (since generally, selectors will be executed against the cache).

func (*ListOptions) ApplyOptions Uses

func (o *ListOptions) ApplyOptions(optFuncs []ListOptionFunc) *ListOptions

ApplyOptions executes the given ListOptionFuncs and returns the mutated ListOptions.

func (*ListOptions) AsListOptions Uses

func (o *ListOptions) AsListOptions() *metav1.ListOptions

AsListOptions returns these options as a flattened metav1.ListOptions. This may mutate the Raw field.

func (*ListOptions) InNamespace Uses

func (o *ListOptions) InNamespace(ns string) *ListOptions

InNamespace is a convenience function that sets the namespace, and then returns the options. It mutates the list options.

func (*ListOptions) MatchingField Uses

func (o *ListOptions) MatchingField(name, val string) *ListOptions

MatchingField is a convenience function that sets the field selector to match the given field, and then returns the options. It mutates the list options.

func (*ListOptions) MatchingLabels Uses

func (o *ListOptions) MatchingLabels(lbls map[string]string) *ListOptions

MatchingLabels is a convenience function that sets the label selector to match the given labels, and then returns the options. It mutates the list options.

func (*ListOptions) SetFieldSelector Uses

func (o *ListOptions) SetFieldSelector(selRaw string) error

SetFieldSelector sets this the label selector of these options from a string form of the selector.

func (*ListOptions) SetLabelSelector Uses

func (o *ListOptions) SetLabelSelector(selRaw string) error

SetLabelSelector sets this the label selector of these options from a string form of the selector.

type ObjectKey Uses

type ObjectKey = types.NamespacedName

ObjectKey identifies a Kubernetes Object.

func ObjectKeyFromObject Uses

func ObjectKeyFromObject(obj runtime.Object) (ObjectKey, error)

ObjectKeyFromObject returns the ObjectKey given a runtime.Object

type Options Uses

type Options struct {
    // Scheme, if provided, will be used to map go structs to GroupVersionKinds
    Scheme *runtime.Scheme

    // Mapper, if provided, will be used to map GroupVersionKinds to Resources
    Mapper meta.RESTMapper
}

Options are creation options for a Client

type Patch Uses

type Patch interface {
    // Type is the PatchType of the patch.
    Type() types.PatchType
    // Data is the raw data representing the patch.
    Data(obj runtime.Object) ([]byte, error)
}

Patch is a patch that can be applied to a Kubernetes object.

func ConstantPatch Uses

func ConstantPatch(patchType types.PatchType, data []byte) Patch

ConstantPatch constructs a new Patch with the given PatchType and data.

func MergeFrom Uses

func MergeFrom(obj runtime.Object) Patch

MergeFrom creates a Patch that patches using the merge-patch strategy with the given object as base.

type PatchOptionFunc Uses

type PatchOptionFunc func(*PatchOptions)

PatchOptionFunc is a function that mutates a PatchOptions struct. It implements the functional options pattern. See https://github.com/tmrts/go-patterns/blob/master/idiom/functional-options.md.

var ForceOwnership PatchOptionFunc = func(opts *PatchOptions) {
    definitelyTrue := true
    opts.Force = &definitelyTrue
}

ForceOwnership sets the Force option, indicating that in case of conflicts with server-side apply, the client should acquire ownership of the conflicting field. Most controllers should use this.

var PatchDryRunAll PatchOptionFunc = func(opts *PatchOptions) {
    opts.DryRun = []string{metav1.DryRunAll}
}

PatchDryRunAll is a functional option that sets the DryRun field of a PatchOptions struct to metav1.DryRunAll.

func FieldOwner Uses

func FieldOwner(name string) PatchOptionFunc

FieldOwner set the field manager name for the given server-side apply patch.

type PatchOptions Uses

type PatchOptions struct {
    // When present, indicates that modifications should not be
    // persisted. An invalid or unrecognized dryRun directive will
    // result in an error response and no further processing of the
    // request. Valid values are:
    // - All: all dry run stages will be processed
    DryRun []string

    // Force is going to "force" Apply requests. It means user will
    // re-acquire conflicting fields owned by other people. Force
    // flag must be unset for non-apply patch requests.
    // +optional
    Force *bool

    // FieldManager is the name of the user or component submitting
    // this request.  It must be set with server-side apply.
    FieldManager string

    // Raw represents raw PatchOptions, as passed to the API server.
    Raw *metav1.PatchOptions
}

PatchOptions contains options for patch requests.

func (*PatchOptions) ApplyOptions Uses

func (o *PatchOptions) ApplyOptions(optFuncs []PatchOptionFunc) *PatchOptions

ApplyOptions executes the given PatchOptionFuncs, mutating these PatchOptions. It returns the mutated PatchOptions for convenience.

func (*PatchOptions) AsPatchOptions Uses

func (o *PatchOptions) AsPatchOptions() *metav1.PatchOptions

AsPatchOptions returns these options as a metav1.PatchOptions. This may mutate the Raw field.

type Reader Uses

type Reader interface {
    // Get retrieves an obj for the given object key from the Kubernetes Cluster.
    // obj must be a struct pointer so that obj can be updated with the response
    // returned by the Server.
    Get(ctx context.Context, key ObjectKey, obj runtime.Object) error

    // List retrieves list of objects for a given namespace and list options. On a
    // successful call, Items field in the list will be populated with the
    // result returned from the server.
    List(ctx context.Context, list runtime.Object, opts ...ListOptionFunc) error
}

Reader knows how to read and list Kubernetes objects.

type StatusClient Uses

type StatusClient interface {
    Status() StatusWriter
}

StatusClient knows how to create a client which can update status subresource for kubernetes objects.

type StatusWriter Uses

type StatusWriter interface {
    // Update updates the fields corresponding to the status subresource for the
    // given obj. obj must be a struct pointer so that obj can be updated
    // with the content returned by the Server.
    Update(ctx context.Context, obj runtime.Object, opts ...UpdateOptionFunc) error

    // Patch patches the given object's subresource. obj must be a struct
    // pointer so that obj can be updated with the content returned by the
    // Server.
    Patch(ctx context.Context, obj runtime.Object, patch Patch, opts ...PatchOptionFunc) error
}

StatusWriter knows how to update status subresource of a Kubernetes object.

type UpdateOptionFunc Uses

type UpdateOptionFunc func(*UpdateOptions)

UpdateOptionFunc is a function that mutates a UpdateOptions struct. It implements the functional options pattern. See https://github.com/tmrts/go-patterns/blob/master/idiom/functional-options.md.

var UpdateDryRunAll UpdateOptionFunc = func(opts *UpdateOptions) {
    opts.DryRun = []string{metav1.DryRunAll}
}

UpdateDryRunAll is a functional option that sets the DryRun field of a UpdateOptions struct to metav1.DryRunAll.

type UpdateOptions Uses

type UpdateOptions struct {
    // When present, indicates that modifications should not be
    // persisted. An invalid or unrecognized dryRun directive will
    // result in an error response and no further processing of the
    // request. Valid values are:
    // - All: all dry run stages will be processed
    DryRun []string

    // Raw represents raw UpdateOptions, as passed to the API server.
    Raw *metav1.UpdateOptions
}

UpdateOptions contains options for create requests. It's generally a subset of metav1.UpdateOptions.

func (*UpdateOptions) ApplyOptions Uses

func (o *UpdateOptions) ApplyOptions(optFuncs []UpdateOptionFunc) *UpdateOptions

ApplyOptions executes the given UpdateOptionFuncs and returns the mutated UpdateOptions.

func (*UpdateOptions) AsUpdateOptions Uses

func (o *UpdateOptions) AsUpdateOptions() *metav1.UpdateOptions

AsUpdateOptions returns these options as a metav1.UpdateOptions. This may mutate the Raw field.

type Writer Uses

type Writer interface {
    // Create saves the object obj in the Kubernetes cluster.
    Create(ctx context.Context, obj runtime.Object, opts ...CreateOptionFunc) error

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

    // Update updates the given obj in the Kubernetes cluster. obj must be a
    // struct pointer so that obj can be updated with the content returned by the Server.
    Update(ctx context.Context, obj runtime.Object, opts ...UpdateOptionFunc) error

    // Patch patches the given obj in the Kubernetes cluster. obj must be a
    // struct pointer so that obj can be updated with the content returned by the Server.
    Patch(ctx context.Context, obj runtime.Object, patch Patch, opts ...PatchOptionFunc) error
}

Writer knows how to create, delete, and update Kubernetes objects.

Directories

PathSynopsis
apiutilPackage apiutil contains utilities for working with raw Kubernetes API machinery, such as creating RESTMappers and raw REST clients, and extracting the GVK of an object.
configPackage config contains libraries for initializing REST configs for talking to the Kubernetes API
fakePackage fake provides a fake client for testing.

Package client imports 21 packages (graph). Updated 2019-05-17. Refresh now. Tools for package owners.