kube

package
v0.16.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 30, 2026 License: Apache-2.0 Imports: 33 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ClusterExists added in v0.12.0

func ClusterExists() (bool, error)

ClusterExists returns true if a Kubernetes cluster is reachable.

It uses a two-stage fast path to avoid the default 32-second API timeout:

  1. Kubeconfig presence check (local, no I/O beyond a stat call). If no kubeconfig file exists at the resolved path, the cluster cannot exist — returns false immediately.

  2. Short-deadline API probe (3 s). Calls /version with a tight deadline. A timeout or network error is treated as "cluster not reachable" (returns false, nil) rather than a hard error, so callers can skip cluster-dependent work without aborting.

func IsCRDReady

func IsCRDReady(obj *unstructured.Unstructured, err error) (bool, error)

IsCRDReady checks if a CustomResourceDefinition is established

func IsDeleted

func IsDeleted(obj *unstructured.Unstructured, err error) (bool, error)

IsDeleted checks if a resource has been deleted (returns true if obj is nil or error is NotFound)

func IsDeploymentReady

func IsDeploymentReady(obj *unstructured.Unstructured, err error) (bool, error)

IsDeploymentReady checks if a Deployment has all desired replicas ready

func IsJobComplete

func IsJobComplete(obj *unstructured.Unstructured, err error) (bool, error)

IsJobComplete checks if a Job has completed successfully

func IsNodeReady

func IsNodeReady(obj *unstructured.Unstructured, err error) (bool, error)

IsNodeReady checks if a Node has Ready condition == True

func IsPVCBound

func IsPVCBound(obj *unstructured.Unstructured, err error) (bool, error)

IsPVCBound checks if a PersistentVolumeClaim is in Bound phase

func IsPhase

func IsPhase(desired Phase) func(obj *unstructured.Unstructured, err error) (bool, error)

IsPhase returns a check function that verifies if the resource is in the desired phase

func IsPodReady

func IsPodReady(obj *unstructured.Unstructured, err error) (bool, error)

IsPodReady checks if a Pod is in Ready condition

func IsPresent

func IsPresent(obj *unstructured.Unstructured, err error) (bool, error)

IsPresent checks if the item exists

func RegisterKind

func RegisterKind(kind ResourceKind, gvr schema.GroupVersionResource)

func RetrieveClusterInfo added in v0.12.0

func RetrieveClusterInfo() (*models.ClusterInfo, error)

func ToGroupVersionResource

func ToGroupVersionResource(kind ResourceKind) (schema.GroupVersionResource, error)

func WithKubeClient

func WithKubeClient(ctx context.Context, kc *Client) context.Context

Types

type CheckFunc

type CheckFunc func(obj *unstructured.Unstructured, err error) (bool, error)

CheckFunc defines a function type for checking resource conditions Notes: when err != nil, obj may be nil. CheckFunc should handle API errors like IsNotFound, IsForbidden.

func IsContainerReady

func IsContainerReady(containerName string) CheckFunc

IsContainerReady returns a CheckFunc that succeeds when the named container reports Ready==true. This is meant to be used for WaitForContainer function.

func IsContainerTerminated

func IsContainerTerminated(containerName string, wantCode int64) CheckFunc

IsContainerTerminated returns a CheckFunc that succeeds when the named container terminated with the specified exit code. If terminated with a different exit code it returns an error. This is meant to be used for WaitForContainer function.

type Client

type Client struct {
	Dyn    dynamic.Interface
	Mapper *restmapper.DeferredDiscoveryRESTMapper
}

Client wraps Kubernetes dynamic client and REST mapper It is intended to be a replacement of invoking kubectl commands directly

func ClientFromContext

func ClientFromContext(ctx context.Context) (*Client, error)

func NewClient

func NewClient() (*Client, error)

NewClient creates a Kubernetes client that automatically detects whether it is running inside a cluster or using a kubeconfig file. It returns a fully prepared dynamic client + discovery mapper.

func (*Client) AnnotateResource added in v0.8.0

func (c *Client) AnnotateResource(ctx context.Context, kind ResourceKind, namespace, name string, annotations map[string]string) error

AnnotateResource adds or updates annotations on a resource. The annotations map is merged with existing annotations.

func (*Client) ApplyManifest

func (c *Client) ApplyManifest(ctx context.Context, manifestPath string) error

ApplyManifest applies resources defined in the given manifest file using Server-Side Apply (SSA). A single PATCH per resource replaces the previous Get → Create/Update two-step, eliminating the 409 Conflict race that occurs when a controller (e.g. the storage provisioner) mutates a resource between the Get and the Update.

SSA rules that matter here:

  • No resourceVersion is sent — the API server handles optimistic concurrency.
  • fieldManager "solo-weaver" declares ownership of every field in the manifest.
  • force:true tells the API server to accept the manifest's values even when they conflict with fields managed by other actors, resolving ownership conflicts in favor of "solo-weaver" and potentially changing existing values.
  • Create-or-update is handled automatically by the API server; no explicit IsNotFound branch is needed.

Manifests must only contain desired-state fields (no status, resourceVersion, uid, managedFields). The block-node storage-config templates already satisfy this requirement.

func (*Client) CRDExists added in v0.7.0

func (c *Client) CRDExists(ctx context.Context, crdName string) (bool, error)

CRDExists checks if a CustomResourceDefinition exists in the cluster. The crdName should be in the format "resource.group.domain" (e.g., "servicemonitors.monitoring.coreos.com").

func (*Client) DeleteManifest

func (c *Client) DeleteManifest(ctx context.Context, manifestPath string) error

DeleteManifest deletes resources defined in the given manifest file

func (*Client) DeletePV added in v0.7.0

func (c *Client) DeletePV(ctx context.Context, name string) error

DeletePV deletes a PersistentVolume by name. Returns nil if the PV doesn't exist.

func (*Client) DeletePVC added in v0.7.0

func (c *Client) DeletePVC(ctx context.Context, namespace, name string) error

DeletePVC deletes a PersistentVolumeClaim by name and namespace. Returns nil if the PVC doesn't exist.

func (*Client) DeleteStatefulSet added in v0.10.0

func (c *Client) DeleteStatefulSet(ctx context.Context, namespace, name string) error

DeleteStatefulSet deletes a StatefulSet by name and namespace using orphan cascading. Orphan cascading removes the StatefulSet controller object but keeps the pods running. This is required when upgrading a StatefulSet that needs volumeClaimTemplates changes, since Kubernetes forbids in-place updates to those fields. Returns nil if the StatefulSet doesn't exist.

func (*Client) GetResourceNestedString added in v0.9.0

func (c *Client) GetResourceNestedString(ctx context.Context, apiVersion, kind, namespace, name string, fields ...string) (string, error)

GetResourceNestedString retrieves a nested string value from a Kubernetes resource. For cluster-scoped resources, pass empty string for namespace. The apiVersion should be in the format "group/version" (e.g., "external-secrets.io/v1beta1"). The fields parameter specifies the path to the nested string (e.g., "spec", "provider", "vault", "server"). Returns empty string if the resource doesn't exist or the field is not found.

func (*Client) GetSecretKeys added in v0.9.0

func (c *Client) GetSecretKeys(ctx context.Context, namespace, name string) ([]string, error)

GetSecretKeys returns the keys present in a Kubernetes Secret's data field. Returns nil and no error if the secret does not exist.

func (*Client) List

func (c *Client) List(ctx context.Context, kind ResourceKind, namespace string, opts WaitOptions) (*unstructured.UnstructuredList, error)

List lists resources of the given kind in the specified namespace with optional filtering. If opts.NamePrefix is set, client-side filtering is applied to return only resources whose names start with the specified prefix.

func (*Client) ResourceExists added in v0.9.0

func (c *Client) ResourceExists(ctx context.Context, apiVersion, kind, namespace, name string) (bool, error)

ResourceExists checks if a resource exists in the cluster. For cluster-scoped resources, pass empty string for namespace. The apiVersion should be in the format "group/version" (e.g., "external-secrets.io/v1beta1").

func (*Client) ScaleDeployment added in v0.8.0

func (c *Client) ScaleDeployment(ctx context.Context, namespace, name string, replicas int32) error

ScaleDeployment scales a Deployment to the specified number of replicas. It uses a JSON Merge Patch (RFC 7386) on spec.replicas for atomic scaling with minimal RBAC requirements and reduced conflict potential.

func (*Client) ScaleStatefulSet added in v0.8.0

func (c *Client) ScaleStatefulSet(ctx context.Context, namespace, name string, replicas int32) error

ScaleStatefulSet scales a StatefulSet to the specified number of replicas. It uses a JSON Merge Patch (RFC 7386) on spec.replicas for atomic scaling with minimal RBAC requirements and reduced conflict potential.

func (*Client) WaitForContainer

func (c *Client) WaitForContainer(ctx context.Context, namespace string, checkFn CheckFunc, timeout time.Duration, opts WaitOptions) error

WaitForContainer waits until the specified container in the given Pod is ready or has terminated successfully within the timeout. It returns an error when the container terminates with a non-zero exit code or on other failures.

func (*Client) WaitForResource

func (c *Client) WaitForResource(
	ctx context.Context,
	kind ResourceKind,
	namespace, name string,
	checkFn CheckFunc,
	timeout time.Duration,
) error

WaitForResource waits until the specified resource of the given kind in the specified namespace satisfies the condition defined by checkFn within the timeout. It returns an error if the timeout is reached or if any fatal API errors occur.

func (*Client) WaitForResources

func (c *Client) WaitForResources(
	ctx context.Context,
	kind ResourceKind,
	namespace string,
	checkFn CheckFunc,
	timeout time.Duration,
	opts WaitOptions,
) error

WaitForResources waits until all resources of the given kind in the specified namespace satisfy the condition defined by checkFn within the timeout. It returns an error if the timeout is reached or if any fatal API errors occur.

func (*Client) WaitForResourcesDeletion added in v0.8.0

func (c *Client) WaitForResourcesDeletion(
	ctx context.Context,
	kind ResourceKind,
	namespace string,
	timeout time.Duration,
	opts WaitOptions,
) error

WaitForResourcesDeletion waits until all resources of the given kind matching the options are deleted from the specified namespace within the timeout. It returns nil when no matching resources exist, or an error if the timeout is reached.

type ClientProvider

type ClientProvider func() (*Client, error)

ClientProvider is a function that provides a kube client NewClient can be used for this provider type

type ClientProviderFromContext

type ClientProviderFromContext func(ctx context.Context) (*Client, error)

ClientProviderFromContext is a function that provides a kube client instance from context. ClientFromContext can be used for this provider type

type KubeConfigManager

type KubeConfigManager struct {
	// contains filtered or unexported fields
}

KubeConfigManager manages kubeconfig file operations with injected dependencies.

func NewKubeConfigManager

func NewKubeConfigManager() (*KubeConfigManager, error)

NewKubeConfigManager creates a new KubeConfigManager with the default dependencies.

func (*KubeConfigManager) Configure

func (m *KubeConfigManager) Configure() error

Configure copies the kubeconfig file to the user's home directory, to /root/.kube, and to the current user's directory. This allows kubectl to be used without requiring root privileges and ensures the config is available for all relevant users.

func (*KubeConfigManager) SetKubeDir

func (m *KubeConfigManager) SetKubeDir(dir string)

SetKubeDir sets a custom kubeconfig directory path. If not set, the default ~/.kube will be used.

type Phase

type Phase string
const (
	PhasePending   Phase = "Pending"
	PhaseRunning   Phase = "Running"
	PhaseSucceeded Phase = "Succeeded"
	PhaseFailed    Phase = "Failed"
	PhaseUnknown   Phase = "Unknown"
)

func RegisterPhase

func RegisterPhase(name string) Phase

RegisterPhase allows registering a new Phase value

func ToPhase

func ToPhase(s string) Phase

ToPhase converts a string to a Phase, normalizing the case

func (Phase) String

func (p Phase) String() string

type ResourceKind

type ResourceKind string
const (
	KindNode        ResourceKind = "Node"
	KindService     ResourceKind = "Service"
	KindNamespace   ResourceKind = "Namespace"
	KindConfigMap   ResourceKind = "ConfigMap"
	KindPod         ResourceKind = "Pod"
	KindDeployment  ResourceKind = "Deployment"
	KindStatefulSet ResourceKind = "StatefulSet"
	KindJob         ResourceKind = "Job"
	KindPVC         ResourceKind = "PersistentVolumeClaim"
	KindPV          ResourceKind = "PersistentVolume"
	KindCRD         ResourceKind = "CustomResourceDefinition"
)

func ToResourceKind

func ToResourceKind(gvr schema.GroupVersionResource) ResourceKind

func (ResourceKind) String

func (k ResourceKind) String() string

type WaitOptions

type WaitOptions struct {
	// NamePrefix restricts the list of returned objects to those whose names start with the given prefix.
	// +optional
	NamePrefix string `json:"namePrefix,omitempty"`
	// A selector to restrict the list of returned objects by their labels.
	// Defaults to everything.
	// +optional
	LabelSelector string `json:"labelSelector,omitempty"`
	// A selector to restrict the list of returned objects by their fields.
	// Defaults to everything.
	// +optional
	FieldSelector string `json:"fieldSelector,omitempty"`
}

func (WaitOptions) AsListOptions

func (w WaitOptions) AsListOptions() metav1.ListOptions

func (WaitOptions) String

func (w WaitOptions) String() string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL