controller-runtimesigs.k8s.io/controller-runtime/pkg/client Index | Examples | Files | Directories

package client

import "sigs.k8s.io/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.

It is a common pattern in Kubernetes to read from a cache and write to the API server. This pattern is covered by the creating the Client with a Cache.

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{"somelabel": "someval"})

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

Constants

const UnsafeDisableDeepCopy = UnsafeDisableDeepCopyOption(true)

UnsafeDisableDeepCopy indicates not to deep copy objects during list objects.

Variables

var DryRunAll = dryRunAll{}

DryRunAll sets the "dry run" option to "all", executing all validation, etc without persisting the change to storage.

var ForceOwnership = forceOwnership{}

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

Functions

func IgnoreAlreadyExists

func IgnoreAlreadyExists(err error) error

IgnoreAlreadyExists returns nil on AlreadyExists errors. All other values that are not AlreadyExists errors or nil are returned unmodified.

func IgnoreNotFound

func IgnoreNotFound(err error) error

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

Types

type CacheOptions

type CacheOptions struct {
	// Reader is a cache-backed reader that will be used to read objects from the cache.
	// +required
	Reader Reader
	// DisableFor is a list of objects that should never be read from the cache.
	// Objects configured here always result in a live lookup.
	DisableFor []Object
	// Unstructured is a flag that indicates whether the cache-backed client should
	// read unstructured objects or lists from the cache.
	// If false, unstructured objects will always result in a live lookup.
	Unstructured bool
}

CacheOptions are options for creating a cache-backed client.

type Client

type Client interface {
	Reader
	Writer
	StatusClient
	SubResourceClientConstructor

	// Scheme returns the scheme this client is using.
	Scheme() *runtime.Scheme
	// RESTMapper returns the rest this client is using.
	RESTMapper() meta.RESTMapper
	// GroupVersionKindFor returns the GroupVersionKind for the given object.
	GroupVersionKindFor(obj runtime.Object) (schema.GroupVersionKind, error)
	// IsObjectNamespaced returns true if the GroupVersionKind of the object is namespaced.
	IsObjectNamespaced(obj runtime.Object) (bool, error)
}

Client knows how to perform CRUD operations on Kubernetes objects.

Example (Apply)

This example shows how to use the client with unstructured objects to create/patch objects using Server Side Apply, "k8s.io/apimachinery/pkg/runtime".DefaultUnstructuredConverter.ToUnstructured is used to convert an object into map[string]any representation, which is then set as an "Object" field in *unstructured.Unstructured struct, which implements client.Object.

Code:play 

package main

import (
	"context"

	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
	"k8s.io/apimachinery/pkg/runtime"

	corev1ac "k8s.io/client-go/applyconfigurations/core/v1"

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

var c client.Client

func main() {
	// Using a typed object.
	configMap := corev1ac.ConfigMap("name", "namespace").WithData(map[string]string{"key": "value"})
	// c is a created client.
	u := &unstructured.Unstructured{}
	u.Object, _ = runtime.DefaultUnstructuredConverter.ToUnstructured(configMap)
	_ = c.Patch(context.Background(), u, client.Apply, client.ForceOwnership, client.FieldOwner("field-owner"))
}
Example (Create)

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

Code:play 

package main

import (
	"context"

	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
	"k8s.io/apimachinery/pkg/runtime/schema"

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

var c client.Client

func main() {
	// Using a typed object.
	pod := &corev1.Pod{
		ObjectMeta: metav1.ObjectMeta{
			Namespace: "namespace",
			Name:      "name",
		},
		Spec: corev1.PodSpec{
			Containers: []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{}{
		"metadata": 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)
}
Example (Delete)

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

Code:play 

package main

import (
	"context"

	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
	"k8s.io/apimachinery/pkg/runtime/schema"

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

var c client.Client

func main() {
	// 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.SetName("name")
	u.SetNamespace("namespace")
	u.SetGroupVersionKind(schema.GroupVersionKind{
		Group:   "apps",
		Kind:    "Deployment",
		Version: "v1",
	})
	_ = c.Delete(context.Background(), u)
}
Example (DeleteAllOf)

This example shows how to use the client with typed and unstructured objects to delete collections of objects.

Code:play 

package main

import (
	"context"

	corev1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
	"k8s.io/apimachinery/pkg/runtime/schema"

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

var c client.Client

func main() {
	// Using a typed object.
	// c is a created client.
	_ = c.DeleteAllOf(context.Background(), &corev1.Pod{}, client.InNamespace("foo"), client.MatchingLabels{"app": "foo"})

	// Using an unstructured Object
	u := &unstructured.Unstructured{}
	u.SetGroupVersionKind(schema.GroupVersionKind{
		Group:   "apps",
		Kind:    "Deployment",
		Version: "v1",
	})
	_ = c.DeleteAllOf(context.Background(), u, client.InNamespace("foo"), client.MatchingLabels{"app": "foo"})
}
Example (Get)

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

Code:play 

package main

import (
	"context"

	corev1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
	"k8s.io/apimachinery/pkg/runtime/schema"

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

var c client.Client

func main() {
	// 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)
}
Example (List)

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

Code:play 

package main

import (
	"context"

	corev1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
	"k8s.io/apimachinery/pkg/runtime/schema"

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

var c client.Client

func main() {
	// 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)
}
Example (Patch)

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

Code:play 

package main

import (
	"context"

	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"
)

var c client.Client

func main() {
	patch := []byte(`{"metadata":{"annotations":{"version": "v2"}}}`)
	_ = c.Patch(context.Background(), &corev1.Pod{
		ObjectMeta: metav1.ObjectMeta{
			Namespace: "namespace",
			Name:      "name",
		},
	}, client.RawPatch(types.StrategicMergePatchType, patch))
}
Example (PatchStatus)

This example shows how to use the client with typed and unstructured objects to patch objects' status.

Code:play 

package main

import (
	"context"
	"fmt"
	"time"

	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
	"k8s.io/apimachinery/pkg/runtime/schema"
	"k8s.io/apimachinery/pkg/types"

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

var c client.Client

func main() {
	u := &unstructured.Unstructured{}
	u.Object = map[string]interface{}{
		"metadata": map[string]interface{}{
			"name":      "foo",
			"namespace": "namespace",
		},
	}
	u.SetGroupVersionKind(schema.GroupVersionKind{
		Group:   "batch",
		Version: "v1beta1",
		Kind:    "CronJob",
	})
	patch := []byte(fmt.Sprintf(`{"status":{"lastScheduleTime":"%s"}}`, time.Now().Format(time.RFC3339)))
	_ = c.Status().Patch(context.Background(), u, client.RawPatch(types.MergePatchType, patch))
}
Example (Update)

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

Code:play 

package main

import (
	"context"

	corev1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
	"k8s.io/apimachinery/pkg/runtime/schema"

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

var c client.Client

func main() {
	// Using a typed object.
	pod := &corev1.Pod{}
	// c is a created client.
	_ = c.Get(context.Background(), client.ObjectKey{
		Namespace: "namespace",
		Name:      "name",
	}, pod)
	controllerutil.AddFinalizer(pod, "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)
	controllerutil.AddFinalizer(u, "new-finalizer")
	_ = c.Update(context.Background(), u)
}

func New

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

New returns a new Client using the provided config and Options.

By default, the client surfaces warnings returned by the server. To suppress warnings, set config.WarningHandlerWithContext = rest.NoWarnings{}. To define custom behavior, implement the rest.WarningHandlerWithContext interface. See sigs.k8s.io/controller-runtime/pkg/log.KubeAPIWarningLogger for an example.

The client's read behavior is determined by Options.Cache. If either Options.Cache or Options.Cache.Reader is nil, the client reads directly from the API server. If both Options.Cache and Options.Cache.Reader are non-nil, the client reads from a local cache. However, specific resources can still be configured to bypass the cache based on Options.Cache.Unstructured and Options.Cache.DisableFor. Write operations are always performed directly on the API server.

The client 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 unstructured types, the group, version, and kind will be extracted from the corresponding fields on the object.

Example

Code:play 

package main

import (
	"context"
	"fmt"
	"os"

	corev1 "k8s.io/api/core/v1"

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

func main() {
	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)
	}
}
Example (Suppress_warnings)

Code:play 

package main

import (
	"context"
	"fmt"
	"os"

	corev1 "k8s.io/api/core/v1"
	"k8s.io/client-go/rest"

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

func main() {
	cfg := config.GetConfigOrDie()
	// Use a rest.WarningHandlerWithContext that discards warning messages.
	cfg.WarningHandlerWithContext = rest.NoWarnings{}

	cl, err := client.New(cfg, 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)
	}
}

func NewDryRunClient

func NewDryRunClient(c Client) Client

NewDryRunClient wraps an existing client and enforces DryRun mode on all mutating api calls.

func NewNamespacedClient

func NewNamespacedClient(c Client, ns string) Client

NewNamespacedClient wraps an existing client enforcing the namespace value. All functions using this client will have the same namespace declared here.

func WithFieldOwner

func WithFieldOwner(c Client, fieldOwner string) Client

WithFieldOwner wraps a Client and adds the fieldOwner as the field manager to all write requests from this client. If additional FieldOwner options are specified on methods of this client, the value specified here will be overridden.

func WithFieldValidation

func WithFieldValidation(c Client, validation FieldValidation) Client

WithFieldValidation wraps a Client and configures field validation, by default, for all write requests from this client. Users can override field validation for individual write requests.

type Continue

type Continue string

Continue sets a continuation token to retrieve chunks of results when using limit. Continue does not implement DeleteAllOfOption interface because the server does not support setting it for deletecollection operations.

func (Continue) ApplyToList

func (c Continue) ApplyToList(opts *ListOptions)

ApplyToList applies this configuration to the given an List options.

type CreateOption

type CreateOption interface {
	// ApplyToCreate applies this configuration to the given create options.
	ApplyToCreate(*CreateOptions)
}

CreateOption is some configuration that modifies options for a create request.

type CreateOptions

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

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

	// fieldValidation instructs the server on how to handle
	// objects in the request (POST/PUT/PATCH) containing unknown
	// or duplicate fields. Valid values are:
	// - Ignore: This will ignore any unknown fields that are silently
	// dropped from the object, and will ignore all but the last duplicate
	// field that the decoder encounters. This is the default behavior
	// prior to v1.23.
	// - Warn: This will send a warning via the standard warning response
	// header for each unknown field that is dropped from the object, and
	// for each duplicate field that is encountered. The request will
	// still succeed if there are no other errors, and will only persist
	// the last of any duplicate fields. This is the default in v1.23+
	// - Strict: This will fail the request with a BadRequest error if
	// any unknown fields would be dropped from the object, or if any
	// duplicate fields are present. The error returned from the server
	// will contain all unknown and duplicate fields encountered.
	FieldValidation 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

func (o *CreateOptions) ApplyOptions(opts []CreateOption) *CreateOptions

ApplyOptions applies the given create options on these options, and then returns itself (for convenient chaining).

func (*CreateOptions) ApplyToCreate

func (o *CreateOptions) ApplyToCreate(co *CreateOptions)

ApplyToCreate implements CreateOption.

func (*CreateOptions) AsCreateOptions

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

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

type DeleteAllOfOption

type DeleteAllOfOption interface {
	// ApplyToDeleteAllOf applies this configuration to the given deletecollection options.
	ApplyToDeleteAllOf(*DeleteAllOfOptions)
}

DeleteAllOfOption is some configuration that modifies options for a delete request.

type DeleteAllOfOptions

type DeleteAllOfOptions struct {
	ListOptions
	DeleteOptions
}

DeleteAllOfOptions contains options for deletecollection (deleteallof) requests. It's just list and delete options smooshed together.

func (*DeleteAllOfOptions) ApplyOptions

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

ApplyOptions applies the given deleteallof options on these options, and then returns itself (for convenient chaining).

func (*DeleteAllOfOptions) ApplyToDeleteAllOf

func (o *DeleteAllOfOptions) ApplyToDeleteAllOf(do *DeleteAllOfOptions)

ApplyToDeleteAllOf implements DeleteAllOfOption.

type DeleteOption

type DeleteOption interface {
	// ApplyToDelete applies this configuration to the given delete options.
	ApplyToDelete(*DeleteOptions)
}

DeleteOption is some configuration that modifies options for a delete request.

type DeleteOptions

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

	// 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
}

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

func (*DeleteOptions) ApplyOptions

func (o *DeleteOptions) ApplyOptions(opts []DeleteOption) *DeleteOptions

ApplyOptions applies the given delete options on these options, and then returns itself (for convenient chaining).

func (*DeleteOptions) ApplyToDelete

func (o *DeleteOptions) ApplyToDelete(do *DeleteOptions)

ApplyToDelete implements DeleteOption.

func (*DeleteOptions) AsDeleteOptions

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

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

type FieldIndexer

type FieldIndexer interface {
	// IndexField 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(ctx context.Context, obj 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.

Example (SecretNameNode)

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

Code:play 

package main

import (
	"context"

	corev1 "k8s.io/api/core/v1"

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

var (
	c           client.Client
	someIndexer client.FieldIndexer
)

func main() {
	// someIndexer is a FieldIndexer over a Cache
	_ = someIndexer.IndexField(context.TODO(), &corev1.Pod{}, "spec.volumes.secret.secretName", func(o client.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
	})

	_ = someIndexer.IndexField(context.TODO(), &corev1.Pod{}, "spec.NodeName", func(o client.Object) []string {
		nodeName := o.(*corev1.Pod).Spec.NodeName
		if nodeName != "" {
			return []string{nodeName}
		}
		return nil
	})

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

type FieldOwner

type FieldOwner string

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

func (FieldOwner) ApplyToCreate

func (f FieldOwner) ApplyToCreate(opts *CreateOptions)

ApplyToCreate applies this configuration to the given create options.

func (FieldOwner) ApplyToPatch

func (f FieldOwner) ApplyToPatch(opts *PatchOptions)

ApplyToPatch applies this configuration to the given patch options.

func (FieldOwner) ApplyToSubResourceCreate

func (f FieldOwner) ApplyToSubResourceCreate(opts *SubResourceCreateOptions)

ApplyToSubResourceCreate applies this configuration to the given create options.

func (FieldOwner) ApplyToSubResourcePatch

func (f FieldOwner) ApplyToSubResourcePatch(opts *SubResourcePatchOptions)

ApplyToSubResourcePatch applies this configuration to the given patch options.

func (FieldOwner) ApplyToSubResourceUpdate

func (f FieldOwner) ApplyToSubResourceUpdate(opts *SubResourceUpdateOptions)

ApplyToSubResourceUpdate applies this configuration to the given update options.

func (FieldOwner) ApplyToUpdate

func (f FieldOwner) ApplyToUpdate(opts *UpdateOptions)

ApplyToUpdate applies this configuration to the given update options.

type FieldValidation

type FieldValidation string

FieldValidation configures field validation for the given requests.

func (FieldValidation) ApplyToCreate

func (f FieldValidation) ApplyToCreate(opts *CreateOptions)

ApplyToCreate applies this configuration to the given create options.

func (FieldValidation) ApplyToPatch

func (f FieldValidation) ApplyToPatch(opts *PatchOptions)

ApplyToPatch applies this configuration to the given patch options.

func (FieldValidation) ApplyToSubResourceCreate

func (f FieldValidation) ApplyToSubResourceCreate(opts *SubResourceCreateOptions)

ApplyToSubResourceCreate applies this configuration to the given create options.

func (FieldValidation) ApplyToSubResourcePatch

func (f FieldValidation) ApplyToSubResourcePatch(opts *SubResourcePatchOptions)

ApplyToSubResourcePatch applies this configuration to the given patch options.

func (FieldValidation) ApplyToSubResourceUpdate

func (f FieldValidation) ApplyToSubResourceUpdate(opts *SubResourceUpdateOptions)

ApplyToSubResourceUpdate applies this configuration to the given update options.

func (FieldValidation) ApplyToUpdate

func (f FieldValidation) ApplyToUpdate(opts *UpdateOptions)

ApplyToUpdate applies this configuration to the given update options.

type GetOption

type GetOption interface {
	// ApplyToGet applies this configuration to the given get options.
	ApplyToGet(*GetOptions)
}

GetOption is some configuration that modifies options for a get request.

type GetOptions

type GetOptions struct {
	// Raw represents raw GetOptions, as passed to the API server.  Note
	// that these may not be respected by all implementations of interface.
	Raw *metav1.GetOptions
}

GetOptions contains options for get operation. Now it only has a Raw field, with support for specific resourceVersion.

func (*GetOptions) ApplyOptions

func (o *GetOptions) ApplyOptions(opts []GetOption) *GetOptions

ApplyOptions applies the given get options on these options, and then returns itself (for convenient chaining).

func (*GetOptions) ApplyToGet

func (o *GetOptions) ApplyToGet(lo *GetOptions)

ApplyToGet implements GetOption for GetOptions.

func (*GetOptions) AsGetOptions

func (o *GetOptions) AsGetOptions() *metav1.GetOptions

AsGetOptions returns these options as a flattened metav1.GetOptions. This may mutate the Raw field.

type GracePeriodSeconds

type GracePeriodSeconds int64

GracePeriodSeconds sets the grace period for the deletion to the given number of seconds.

func (GracePeriodSeconds) ApplyToDelete

func (s GracePeriodSeconds) ApplyToDelete(opts *DeleteOptions)

ApplyToDelete applies this configuration to the given delete options.

func (GracePeriodSeconds) ApplyToDeleteAllOf

func (s GracePeriodSeconds) ApplyToDeleteAllOf(opts *DeleteAllOfOptions)

ApplyToDeleteAllOf applies this configuration to the given an List options.

type HasLabels

type HasLabels []string

HasLabels filters the list/delete operation checking if the set of labels exists without checking their values.

func (HasLabels) ApplyToDeleteAllOf

func (m HasLabels) ApplyToDeleteAllOf(opts *DeleteAllOfOptions)

ApplyToDeleteAllOf applies this configuration to the given an List options.

func (HasLabels) ApplyToList

func (m HasLabels) ApplyToList(opts *ListOptions)

ApplyToList applies this configuration to the given list options.

type InNamespace

type InNamespace string

InNamespace restricts the list/delete operation to the given namespace.

func (InNamespace) ApplyToDeleteAllOf

func (n InNamespace) ApplyToDeleteAllOf(opts *DeleteAllOfOptions)

ApplyToDeleteAllOf applies this configuration to the given an List options.

func (InNamespace) ApplyToList

func (n InNamespace) ApplyToList(opts *ListOptions)

ApplyToList applies this configuration to the given list options.

func (InNamespace) AsSelector

func (n InNamespace) AsSelector() fields.Selector

AsSelector returns a selector that matches objects in the given namespace.

type IndexerFunc

type IndexerFunc func(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 Limit

type Limit int64

Limit specifies the maximum number of results to return from the server. Limit does not implement DeleteAllOfOption interface because the server does not support setting it for deletecollection operations.

func (Limit) ApplyToList

func (l Limit) ApplyToList(opts *ListOptions)

ApplyToList applies this configuration to the given an list options.

type ListOption

type ListOption interface {
	// ApplyToList applies this configuration to the given list options.
	ApplyToList(*ListOptions)
}

ListOption is some configuration that modifies options for a list request.

type ListOptions

type ListOptions struct {
	// LabelSelector filters results by label. Use labels.Parse() 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
	// exact match 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

	// Limit specifies the maximum number of results to return from the server. The server may
	// not support this field on all resource types, but if it does and more results remain it
	// will set the continue field on the returned list object. This field is not supported if watch
	// is true in the Raw ListOptions.
	Limit int64
	// Continue is a token returned by the server that lets a client retrieve chunks of results
	// from the server by specifying limit. The server may reject requests for continuation tokens
	// it does not recognize and will return a 410 error if the token can no longer be used because
	// it has expired. This field is not supported if watch is true in the Raw ListOptions.
	Continue string

	// UnsafeDisableDeepCopy indicates not to deep copy objects during list objects.
	// Be very careful with this, when enabled you must DeepCopy any object before mutating it,
	// otherwise you will mutate the object in the cache.
	// +optional
	UnsafeDisableDeepCopy *bool

	// 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, FieldSelector, Limit and Continue 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

func (o *ListOptions) ApplyOptions(opts []ListOption) *ListOptions

ApplyOptions applies the given list options on these options, and then returns itself (for convenient chaining).

func (*ListOptions) ApplyToList

func (o *ListOptions) ApplyToList(lo *ListOptions)

ApplyToList implements ListOption for ListOptions.

func (*ListOptions) AsListOptions

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

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

type MatchingFields

type MatchingFields fields.Set

MatchingFields filters the list/delete operation on the given field Set (or index in the case of cached lists).

func (MatchingFields) ApplyToDeleteAllOf

func (m MatchingFields) ApplyToDeleteAllOf(opts *DeleteAllOfOptions)

ApplyToDeleteAllOf applies this configuration to the given an List options.

func (MatchingFields) ApplyToList

func (m MatchingFields) ApplyToList(opts *ListOptions)

ApplyToList applies this configuration to the given list options.

type MatchingFieldsSelector

type MatchingFieldsSelector struct {
	fields.Selector
}

MatchingFieldsSelector filters the list/delete operation on the given field selector (or index in the case of cached lists). A struct is used because fields.Selector is an interface, which cannot be aliased.

func (MatchingFieldsSelector) ApplyToDeleteAllOf

func (m MatchingFieldsSelector) ApplyToDeleteAllOf(opts *DeleteAllOfOptions)

ApplyToDeleteAllOf applies this configuration to the given an List options.

func (MatchingFieldsSelector) ApplyToList

func (m MatchingFieldsSelector) ApplyToList(opts *ListOptions)

ApplyToList applies this configuration to the given list options.

type MatchingLabels

type MatchingLabels map[string]string

MatchingLabels filters the list/delete operation on the given set of labels.

func (MatchingLabels) ApplyToDeleteAllOf

func (m MatchingLabels) ApplyToDeleteAllOf(opts *DeleteAllOfOptions)

ApplyToDeleteAllOf applies this configuration to the given an List options.

func (MatchingLabels) ApplyToList

func (m MatchingLabels) ApplyToList(opts *ListOptions)

ApplyToList applies this configuration to the given list options.

type MatchingLabelsSelector

type MatchingLabelsSelector struct {
	labels.Selector
}

MatchingLabelsSelector filters the list/delete operation on the given label selector (or index in the case of cached lists). A struct is used because labels.Selector is an interface, which cannot be aliased.

func (MatchingLabelsSelector) ApplyToDeleteAllOf

func (m MatchingLabelsSelector) ApplyToDeleteAllOf(opts *DeleteAllOfOptions)

ApplyToDeleteAllOf applies this configuration to the given an List options.

func (MatchingLabelsSelector) ApplyToList

func (m MatchingLabelsSelector) ApplyToList(opts *ListOptions)

ApplyToList applies this configuration to the given list options.

type MergeFromOption

type MergeFromOption interface {
	// ApplyToMergeFrom applies this configuration to the given patch options.
	ApplyToMergeFrom(*MergeFromOptions)
}

MergeFromOption is some configuration that modifies options for a merge-from patch data.

type MergeFromOptions

type MergeFromOptions struct {
	// OptimisticLock, when true, includes `metadata.resourceVersion` into the final
	// patch data. If the `resourceVersion` field doesn't match what's stored,
	// the operation results in a conflict and clients will need to try again.
	OptimisticLock bool
}

MergeFromOptions contains options to generate a merge-from patch data.

type MergeFromWithOptimisticLock

type MergeFromWithOptimisticLock struct{}

MergeFromWithOptimisticLock can be used if clients want to make sure a patch is being applied to the latest resource version of an object.

The behavior is similar to what an Update would do, without the need to send the whole object. Usually this method is useful if you might have multiple clients acting on the same object and the same API version, but with different versions of the Go structs.

For example, an "older" copy of a Widget that has fields A and B, and a "newer" copy with A, B, and C. Sending an update using the older struct definition results in C being dropped, whereas using a patch does not.

func (MergeFromWithOptimisticLock) ApplyToMergeFrom

func (m MergeFromWithOptimisticLock) ApplyToMergeFrom(in *MergeFromOptions)

ApplyToMergeFrom applies this configuration to the given patch options.

type NewClientFunc

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

NewClientFunc allows a user to define how to create a client.

type Object

type Object interface {
	metav1.Object
	runtime.Object
}

Object is a Kubernetes object, allows functions to work indistinctly with any resource that implements both Object interfaces.

Semantically, these are objects which are both serializable (runtime.Object) and identifiable (metav1.Object) -- think any object which you could write as YAML or JSON, and then `kubectl create`.

Code-wise, this means that any object which embeds both ObjectMeta (which provides metav1.Object) and TypeMeta (which provides half of runtime.Object) and has a `DeepCopyObject` implementation (the other half of runtime.Object) will implement this by default.

For example, nearly all the built-in types are Objects, as well as all KubeBuilder-generated CRDs (unless you do something real funky to them).

By and large, most things that implement runtime.Object also implement Object -- it's very rare to have *just* a runtime.Object implementation (the cases tend to be funky built-in types like Webhook payloads that don't have a `metadata` field).

Notice that XYZList types are distinct: they implement ObjectList instead.

type ObjectKey

type ObjectKey = types.NamespacedName

ObjectKey identifies a Kubernetes Object.

func ObjectKeyFromObject

func ObjectKeyFromObject(obj Object) ObjectKey

ObjectKeyFromObject returns the ObjectKey given a runtime.Object.

type ObjectList

type ObjectList interface {
	metav1.ListInterface
	runtime.Object
}

ObjectList is a Kubernetes object list, allows functions to work indistinctly with any resource that implements both runtime.Object and metav1.ListInterface interfaces.

Semantically, this is any object which may be serialized (ObjectMeta), and is a kubernetes list wrapper (has items, pagination fields, etc) -- think the wrapper used in a response from a `kubectl list --output yaml` call.

Code-wise, this means that any object which embedds both ListMeta (which provides metav1.ListInterface) and TypeMeta (which provides half of runtime.Object) and has a `DeepCopyObject` implementation (the other half of runtime.Object) will implement this by default.

For example, nearly all the built-in XYZList types are ObjectLists, as well as the XYZList types for all KubeBuilder-generated CRDs (unless you do something real funky to them).

By and large, most things that are XYZList and implement runtime.Object also implement ObjectList -- it's very rare to have *just* a runtime.Object implementation (the cases tend to be funky built-in types like Webhook payloads that don't have a `metadata` field).

This is similar to Object, which is almost always implemented by the items in the list themselves.

type Options

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

	// 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

	// Cache, if provided, is used to read objects from the cache.
	Cache *CacheOptions

	// DryRun instructs the client to only perform dry run requests.
	DryRun *bool
}

Options are creation options for a Client.

type Patch

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

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

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

	// Merge uses the raw object as a merge patch, without modifications.
	// Use MergeFrom if you wish to compute a diff instead.
	Merge Patch = mergePatch{}
)

func MergeFrom

func MergeFrom(obj Object) Patch

MergeFrom creates a Patch that patches using the merge-patch strategy with the given object as base. The difference between MergeFrom and StrategicMergeFrom lays in the handling of modified list fields. When using MergeFrom, existing lists will be completely replaced by new lists. When using StrategicMergeFrom, the list field's `patchStrategy` is respected if specified in the API type, e.g. the existing list is not replaced completely but rather merged with the new one using the list's `patchMergeKey`. See https://kubernetes.io/docs/tasks/manage-kubernetes-objects/update-api-object-kubectl-patch/ for more details on the difference between merge-patch and strategic-merge-patch.

func MergeFromWithOptions

func MergeFromWithOptions(obj Object, opts ...MergeFromOption) Patch

MergeFromWithOptions creates a Patch that patches using the merge-patch strategy with the given object as base. See MergeFrom for more details.

func RawPatch

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

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

func StrategicMergeFrom

func StrategicMergeFrom(obj Object, opts ...MergeFromOption) Patch

StrategicMergeFrom creates a Patch that patches using the strategic-merge-patch strategy with the given object as base. The difference between MergeFrom and StrategicMergeFrom lays in the handling of modified list fields. When using MergeFrom, existing lists will be completely replaced by new lists. When using StrategicMergeFrom, the list field's `patchStrategy` is respected if specified in the API type, e.g. the existing list is not replaced completely but rather merged with the new one using the list's `patchMergeKey`. See https://kubernetes.io/docs/tasks/manage-kubernetes-objects/update-api-object-kubectl-patch/ for more details on the difference between merge-patch and strategic-merge-patch. Please note, that CRDs don't support strategic-merge-patch, see https://kubernetes.io/docs/concepts/extend-kubernetes/api-extension/custom-resources/#advanced-features-and-flexibility

type PatchOption

type PatchOption interface {
	// ApplyToPatch applies this configuration to the given patch options.
	ApplyToPatch(*PatchOptions)
}

PatchOption is some configuration that modifies options for a patch request.

type PatchOptions

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

	// fieldValidation instructs the server on how to handle
	// objects in the request (POST/PUT/PATCH) containing unknown
	// or duplicate fields. Valid values are:
	// - Ignore: This will ignore any unknown fields that are silently
	// dropped from the object, and will ignore all but the last duplicate
	// field that the decoder encounters. This is the default behavior
	// prior to v1.23.
	// - Warn: This will send a warning via the standard warning response
	// header for each unknown field that is dropped from the object, and
	// for each duplicate field that is encountered. The request will
	// still succeed if there are no other errors, and will only persist
	// the last of any duplicate fields. This is the default in v1.23+
	// - Strict: This will fail the request with a BadRequest error if
	// any unknown fields would be dropped from the object, or if any
	// duplicate fields are present. The error returned from the server
	// will contain all unknown and duplicate fields encountered.
	FieldValidation string

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

PatchOptions contains options for patch requests.

func (*PatchOptions) ApplyOptions

func (o *PatchOptions) ApplyOptions(opts []PatchOption) *PatchOptions

ApplyOptions applies the given patch options on these options, and then returns itself (for convenient chaining).

func (*PatchOptions) ApplyToPatch

func (o *PatchOptions) ApplyToPatch(po *PatchOptions)

ApplyToPatch implements PatchOptions.

func (*PatchOptions) AsPatchOptions

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

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

type Preconditions

type Preconditions metav1.Preconditions

Preconditions must be fulfilled before an operation (update, delete, etc.) is carried out.

func (Preconditions) ApplyToDelete

func (p Preconditions) ApplyToDelete(opts *DeleteOptions)

ApplyToDelete applies this configuration to the given delete options.

func (Preconditions) ApplyToDeleteAllOf

func (p Preconditions) ApplyToDeleteAllOf(opts *DeleteAllOfOptions)

ApplyToDeleteAllOf applies this configuration to the given an List options.

type PropagationPolicy

type PropagationPolicy metav1.DeletionPropagation

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.

func (PropagationPolicy) ApplyToDelete

func (p PropagationPolicy) ApplyToDelete(opts *DeleteOptions)

ApplyToDelete applies the given delete options on these options. It will propagate to the dependents of the object to let the garbage collector handle it.

func (PropagationPolicy) ApplyToDeleteAllOf

func (p PropagationPolicy) ApplyToDeleteAllOf(opts *DeleteAllOfOptions)

ApplyToDeleteAllOf applies this configuration to the given an List options.

type Reader

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 Object, opts ...GetOption) 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 ObjectList, opts ...ListOption) error
}

Reader knows how to read and list Kubernetes objects.

type StatusClient

type StatusClient interface {
	Status() SubResourceWriter
}

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

type StatusWriter

type StatusWriter = SubResourceWriter

StatusWriter is kept for backward compatibility.

type SubResourceClient

type SubResourceClient interface {
	SubResourceReader
	SubResourceWriter
}

SubResourceClient knows how to perform CRU operations on Kubernetes objects.

type SubResourceClientConstructor

type SubResourceClientConstructor interface {
	// SubResourceClientConstructor returns a subresource client for the named subResource. Known
	// upstream subResources usages are:
	// - ServiceAccount token creation:
	//     sa := &corev1.ServiceAccount{ObjectMeta: metav1.ObjectMeta{Namespace: "foo", Name: "bar"}}
	//     token := &authenticationv1.TokenRequest{}
	//     c.SubResource("token").Create(ctx, sa, token)
	//
	// - Pod eviction creation:
	//     pod := &corev1.Pod{ObjectMeta: metav1.ObjectMeta{Namespace: "foo", Name: "bar"}}
	//     c.SubResource("eviction").Create(ctx, pod, &policyv1.Eviction{})
	//
	// - Pod binding creation:
	//     pod := &corev1.Pod{ObjectMeta: metav1.ObjectMeta{Namespace: "foo", Name: "bar"}}
	//     binding := &corev1.Binding{Target: corev1.ObjectReference{Name: "my-node"}}
	//     c.SubResource("binding").Create(ctx, pod, binding)
	//
	// - CertificateSigningRequest approval:
	//     csr := &certificatesv1.CertificateSigningRequest{
	//	     ObjectMeta: metav1.ObjectMeta{Namespace: "foo", Name: "bar"},
	//       Status: certificatesv1.CertificateSigningRequestStatus{
	//         Conditions: []certificatesv1.[]CertificateSigningRequestCondition{{
	//           Type: certificatesv1.CertificateApproved,
	//           Status: corev1.ConditionTrue,
	//         }},
	//       },
	//     }
	//     c.SubResource("approval").Update(ctx, csr)
	//
	// - Scale retrieval:
	//     dep := &appsv1.Deployment{ObjectMeta: metav1.ObjectMeta{Namespace: "foo", Name: "bar"}}
	//     scale := &autoscalingv1.Scale{}
	//     c.SubResource("scale").Get(ctx, dep, scale)
	//
	// - Scale update:
	//     dep := &appsv1.Deployment{ObjectMeta: metav1.ObjectMeta{Namespace: "foo", Name: "bar"}}
	//     scale := &autoscalingv1.Scale{Spec: autoscalingv1.ScaleSpec{Replicas: 2}}
	//     c.SubResource("scale").Update(ctx, dep, client.WithSubResourceBody(scale))
	SubResource(subResource string) SubResourceClient
}

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

type SubResourceCreateOption

type SubResourceCreateOption interface {
	// ApplyToSubResourceCreate applies this configuration to the given create options.
	ApplyToSubResourceCreate(*SubResourceCreateOptions)
}

SubResourceCreateOption is some configuration that modifies options for a create request.

type SubResourceCreateOptions

type SubResourceCreateOptions struct {
	CreateOptions
}

SubResourceCreateOptions are all the possible configurations for a subresource create request.

func (*SubResourceCreateOptions) ApplyOptions

ApplyOptions applies the given options.

func (*SubResourceCreateOptions) ApplyToSubResourceCreate

func (co *SubResourceCreateOptions) ApplyToSubResourceCreate(o *SubResourceCreateOptions)

ApplyToSubResourceCreate applies the the configuration on the given create options.

type SubResourceGetOption

type SubResourceGetOption interface {
	ApplyToSubResourceGet(*SubResourceGetOptions)
}

SubResourceGetOption modifies options for a SubResource Get request.

type SubResourceGetOptions

type SubResourceGetOptions struct {
	Raw *metav1.GetOptions
}

SubResourceGetOptions holds all the possible configuration for a subresource Get request.

func (*SubResourceGetOptions) ApplyOptions

ApplyOptions applues the given options.

func (*SubResourceGetOptions) ApplyToSubResourceGet

func (getOpt *SubResourceGetOptions) ApplyToSubResourceGet(o *SubResourceGetOptions)

ApplyToSubResourceGet updates the configuaration to the given get options.

func (*SubResourceGetOptions) AsGetOptions

func (getOpt *SubResourceGetOptions) AsGetOptions() *metav1.GetOptions

AsGetOptions returns the configured options as *metav1.GetOptions.

type SubResourcePatchOption

type SubResourcePatchOption interface {
	// ApplyToSubResourcePatch applies the configuration on the given patch options.
	ApplyToSubResourcePatch(*SubResourcePatchOptions)
}

SubResourcePatchOption configures a subresource patch request.

type SubResourcePatchOptions

type SubResourcePatchOptions struct {
	PatchOptions
	SubResourceBody Object
}

SubResourcePatchOptions holds all possible configurations for a subresource patch request.

func (*SubResourcePatchOptions) ApplyOptions

ApplyOptions applies the given options.

func (*SubResourcePatchOptions) ApplyToSubResourcePatch

func (po *SubResourcePatchOptions) ApplyToSubResourcePatch(o *SubResourcePatchOptions)

ApplyToSubResourcePatch applies the configuration on the given patch options.

type SubResourceReader

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

SubResourceReader knows how to read SubResources

type SubResourceUpdateAndPatchOption

type SubResourceUpdateAndPatchOption interface {
	SubResourceUpdateOption
	SubResourcePatchOption
}

SubResourceUpdateAndPatchOption is an option that can be used for either a subresource update or patch request.

func WithSubResourceBody

func WithSubResourceBody(body Object) SubResourceUpdateAndPatchOption

WithSubResourceBody returns an option that uses the given body for a subresource Update or Patch operation.

type SubResourceUpdateOption

type SubResourceUpdateOption interface {
	// ApplyToSubResourceUpdate applies this configuration to the given update options.
	ApplyToSubResourceUpdate(*SubResourceUpdateOptions)
}

SubResourceUpdateOption is some configuration that modifies options for a update request.

type SubResourceUpdateOptions

type SubResourceUpdateOptions struct {
	UpdateOptions
	SubResourceBody Object
}

SubResourceUpdateOptions holds all the possible configuration for a subresource update request.

func (*SubResourceUpdateOptions) ApplyOptions

ApplyOptions applies the given options.

func (*SubResourceUpdateOptions) ApplyToSubResourceUpdate

func (uo *SubResourceUpdateOptions) ApplyToSubResourceUpdate(o *SubResourceUpdateOptions)

ApplyToSubResourceUpdate updates the configuration on the given create options

type SubResourceWriter

type SubResourceWriter interface {
	// Create saves the subResource object in the Kubernetes cluster. obj must be a
	// struct pointer so that obj can be updated with the content returned by the Server.
	Create(ctx context.Context, obj Object, subResource Object, opts ...SubResourceCreateOption) error

	// 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 Object, opts ...SubResourceUpdateOption) 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 Object, patch Patch, opts ...SubResourcePatchOption) error
}

SubResourceWriter knows how to update subresource of a Kubernetes object.

type UnsafeDisableDeepCopyOption

type UnsafeDisableDeepCopyOption bool

UnsafeDisableDeepCopyOption indicates not to deep copy objects during list objects. Be very careful with this, when enabled you must DeepCopy any object before mutating it, otherwise you will mutate the object in the cache.

func (UnsafeDisableDeepCopyOption) ApplyToList

func (d UnsafeDisableDeepCopyOption) ApplyToList(opts *ListOptions)

ApplyToList applies this configuration to the given an List options.

type UpdateOption

type UpdateOption interface {
	// ApplyToUpdate applies this configuration to the given update options.
	ApplyToUpdate(*UpdateOptions)
}

UpdateOption is some configuration that modifies options for a update request.

type UpdateOptions

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

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

	// fieldValidation instructs the server on how to handle
	// objects in the request (POST/PUT/PATCH) containing unknown
	// or duplicate fields. Valid values are:
	// - Ignore: This will ignore any unknown fields that are silently
	// dropped from the object, and will ignore all but the last duplicate
	// field that the decoder encounters. This is the default behavior
	// prior to v1.23.
	// - Warn: This will send a warning via the standard warning response
	// header for each unknown field that is dropped from the object, and
	// for each duplicate field that is encountered. The request will
	// still succeed if there are no other errors, and will only persist
	// the last of any duplicate fields. This is the default in v1.23+
	// - Strict: This will fail the request with a BadRequest error if
	// any unknown fields would be dropped from the object, or if any
	// duplicate fields are present. The error returned from the server
	// will contain all unknown and duplicate fields encountered.
	FieldValidation 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

func (o *UpdateOptions) ApplyOptions(opts []UpdateOption) *UpdateOptions

ApplyOptions applies the given update options on these options, and then returns itself (for convenient chaining).

func (*UpdateOptions) ApplyToUpdate

func (o *UpdateOptions) ApplyToUpdate(uo *UpdateOptions)

ApplyToUpdate implements UpdateOption.

func (*UpdateOptions) AsUpdateOptions

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

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

type WithWatch

type WithWatch interface {
	Client
	Watch(ctx context.Context, obj ObjectList, opts ...ListOption) (watch.Interface, error)
}

WithWatch supports Watch on top of the CRUD operations supported by the normal Client. Its intended use-case are CLI apps that need to wait for events.

func NewWithWatch

func NewWithWatch(config *rest.Config, options Options) (WithWatch, error)

NewWithWatch returns a new WithWatch.

type Writer

type Writer interface {
	// Create saves the object obj in the Kubernetes cluster. obj must be a
	// struct pointer so that obj can be updated with the content returned by the Server.
	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. obj must be a
	// struct pointer so that obj can be updated with the content returned by the Server.
	Update(ctx context.Context, obj Object, opts ...UpdateOption) 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 Object, patch Patch, opts ...PatchOption) error

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

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

Source Files

client.go client_rest_resources.go codec.go doc.go dryrun.go fieldowner.go fieldvalidation.go interfaces.go metadata_client.go namespaced_client.go object.go options.go patch.go typed_client.go unstructured_client.go watch.go

Directories

PathSynopsis
pkg/client/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.
pkg/client/configPackage config contains libraries for initializing REST configs for talking to the Kubernetes API
pkg/client/fakePackage fake provides a fake client for testing.
pkg/client/interceptor
Version
v0.21.0 (latest)
Published
May 20, 2025
Platform
linux/amd64
Imports
27 packages
Last checked
24 minutes ago

Tools for package owners.