kubernetes

package
v0.2.10 Latest Latest
Warning

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

Go to latest
Published: Aug 2, 2026 License: MIT Imports: 59 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// Using a nil UUID (all zeros) as the default when SpaceID is not provided
	// This is a valid UUID format that won't cause parsing errors
	DefaultSpaceID       = "00000000-0000-0000-0000-000000000000"
	DefaultUnitSlug      = "default"
	DefaultInventoryName = "inventory"
	DefaultInventoryID   = "00000000-0000-0000-0000-000000000000-default"
	DefaultNamespace     = "default"
	FieldManager         = "confighub-bridge-worker"
	DefaultTimeout       = LargeWaitTimeout
	MinimalTimeout       = 10 * time.Millisecond
	PollInterval         = 2 * time.Second
	InventoryPrefix      = "inventory"
)
View Source
const (
	// InventoryConfigMapName is the standard name for the inventory ConfigMap
	InventoryConfigMapName = "inventory"
	// YAMLSeparator is the standard YAML document separator
	YAMLSeparator = "---"
	// InventoryIDLabel is the label key for inventory ID
	InventoryIDLabel = "cli-utils.sigs.k8s.io/inventory-id"
	// FunctionAnnotation is the annotation key for function
	FunctionAnnotation = "config.k8s.io/function"
	// InventoryDataKey is the key for inventory data in ConfigMap
	InventoryDataKey = "inventory"
)
View Source
const LargeWaitTimeout = 87600 * time.Hour

LargeWaitTimeout is effectively infinite (~10 years) - disabled per #3220 The Bridge should report what Kubernetes reports, not have its own timeout-based failure.

Variables

View Source
var ErrOperationInterrupted = errors.New("operation interrupted")

ErrOperationInterrupted is returned when an operation is cancelled or overridden. Status is already sent via sendOverriddenStatus/sendCancelledStatus, so no "Failed" status needed.

View Source
var K8sApplierFactory = defaultK8sApplierFactory

K8sApplierFactory is a variable that can be replaced in tests

View Source
var KubernetesClientFactory = setupKubernetesClient

KubernetesClientFactory creates a controller-runtime client bound to the given context. Override in tests to inject a fake client.

View Source
var KubernetesConfigFactory = setupKubernetesConfig

KubernetesConfigFactory creates a Kubernetes rest.Config for the given context. Override in tests to inject a fake config.

Functions

func BuildOriginalNamespaceMap added in v0.1.25

func BuildOriginalNamespaceMap(data []byte) map[string]string

BuildOriginalNamespaceMap parses the original unit data and returns a map of "Group/Kind/Name" -> namespace for resources that have an explicit namespace set. Used by OCI bridges to determine which resources should retain their namespace in LiveData — resources not in this map have their namespace cleared.

func CleanBaseDataForDrift added in v0.1.25

func CleanBaseDataForDrift(baseData []byte) ([]byte, error)

CleanBaseDataForDrift prepares "base data" (the last-applied revision YAML) for drift comparison by stripping comments, internal annotations, and normalizing resource quantities — the same cleanup rules applied to LiveData. This ensures textual differences that are not real drift (e.g. comments, controller-injected annotations, "2000m" vs "2") do not trigger false positives.

func CombineInventoryWithResources

func CombineInventoryWithResources(inventoryCM *InventoryConfigMap, resources []byte) ([]byte, error)

CombineInventoryWithResources combines the inventory ConfigMap with resource YAML The inventory ConfigMap is placed as the first document

func CreateInventoryFromLiveData

func CreateInventoryFromLiveData(ctx context.Context, liveData []byte, inv inventory.Info) (*InMemInventoryClient, *InventoryConfigMap, []byte, error)

CreateInventoryFromLiveData creates an InMemInventoryClient initialized with LiveData data This is a convenience wrapper for backward compatibility

func CreateRetryBackoff

func CreateRetryBackoff(params KubernetesWorkerParams) *backoff.ExponentialBackOff

CreateRetryBackoff creates a standard exponential backoff policy for retrying operations It derives retry parameters from the WaitTimeout to ensure proper scaling: - For short timeouts (< 2m): quick retries starting at 5s - For medium timeouts (2m-10m): standard retries starting at 10s - For long timeouts (> 10m): slower retries starting at 30s

func DiscoverAllResourceTypes

func DiscoverAllResourceTypes(cfg *rest.Config) (map[string]ResourceTypeInfo, error)

DiscoverAllResourceTypes fetches all available resource types (including CRDs) from the cluster Returns a map of resource type string (e.g. group/version/Kind) to ResourceTypeInfo

func EnsureConfigHubContext

func EnsureConfigHubContext(obj *unstructured.Unstructured, unitSlug, spaceID string, revisionNum int64)

EnsureConfigHubContext sets ConfigHub context annotations (UnitSlug, SpaceID, RevisionNum) on a parsed Kubernetes object. Used by the K8s bridge which already has parsed objects. See also k8skit.EnsureConfigHubContextOnData for a text-based variant that preserves YAML comments and key ordering.

func GetCustomResourceDefinitions

func GetCustomResourceDefinitions(k8sclient KubernetesClient) ([]*unstructured.Unstructured, error)

GetCustomResourceDefinitions fetches only Custom Resource Definitions from the cluster

func GetDisableTargetCreation added in v0.1.27

func GetDisableTargetCreation() bool

func GetLiveObjects

func GetLiveObjects(
	ctx context.Context,
	k8sClient KubernetesClient,
	objects []*unstructured.Unstructured,
	doCleanup bool,
	skipNotFound bool,
) ([]*unstructured.Unstructured, error)

GetLiveObjects fetches live versions of expected objects from the cluster. When skipNotFound is true, resources that return a NotFound error are silently skipped (e.g., not yet created during ArgoCD sync). All other errors (permission denied, network timeouts, RBAC failures) are always returned immediately.

func GetObjectRefsFromInventory

func GetObjectRefsFromInventory(inventoryCM *InventoryConfigMap) (object.ObjMetadataSet, error)

GetObjectRefsFromInventory extracts object references from an inventory ConfigMap

func GetResourcesWithConfig

func GetResourcesWithConfig(k8sclient KubernetesClient, config *ImportConfig, cfg *rest.Config) ([]*unstructured.Unstructured, error)

GetResourcesWithConfig handles resource import with a clean configuration structure

func MarshalInventoryConfigMap added in v0.1.25

func MarshalInventoryConfigMap(inventoryCM *InventoryConfigMap) ([]byte, error)

MarshalInventoryConfigMap serializes an InventoryConfigMap to YAML bytes.

func ObjectsToYAML

func ObjectsToYAML(objects []*unstructured.Unstructured) (string, error)

func OriginalNamespaceKey added in v0.1.25

func OriginalNamespaceKey(obj *unstructured.Unstructured) string

OriginalNamespaceKey returns the map key used by BuildOriginalNamespaceMap.

func ParseGroupVersionKind

func ParseGroupVersionKind(s string) (schema.GroupVersionKind, error)

TODO: move to k8skit

func ParseObjects

func ParseObjects(data []byte) ([]*unstructured.Unstructured, error)

ParseObjects parses YAML objects from payload data

func ResolveNamespace added in v0.1.25

func ResolveNamespace(payload api.BridgeWorkerPayload) string

ResolveNamespace determines the namespace to enforce on resources as their metadata.namespace, when enforcement is desired. Precedence:

  1. TargetOptions["Namespace"] — explicit user override via BridgeOptions
  2. Pod namespace (in-cluster) or kubeconfig context.namespace (out-of-cluster)
  3. "" — no namespace enforcement

func SaveInventoryToLiveData

func SaveInventoryToLiveData(invClient *InMemInventoryClient, inventoryCM *InventoryConfigMap, inventoryInfo inventory.Info, resources []byte) ([]byte, error)

SaveInventoryToLiveData updates the LiveData with the current inventory state This is a convenience wrapper for backward compatibility

func SetConfigProvider

func SetConfigProvider(provider ConfigProvider)

SetConfigProvider allows tests to override the config provider

func SetupMockSendStatus

func SetupMockSendStatus(t *testing.T, mockCtx *MockBridgeWorkerContext, status api.ActionStatusType, result api.ActionResultType, message string)

SetupMockSendStatus sets up a mock expectation for SendStatus with exact message match.

func SetupMockSendStatusContains

func SetupMockSendStatusContains(t *testing.T, mockCtx *MockBridgeWorkerContext, status api.ActionStatusType, result api.ActionResultType, messageContains string)

SetupMockSendStatusContains sets up a mock expectation for SendStatus with partial message match.

func UpdateInventoryConfigMap

func UpdateInventoryConfigMap(inventoryCM *InventoryConfigMap, objRefs object.ObjMetadataSet) error

UpdateInventoryConfigMap updates the inventory ConfigMap with new object metadata

func ValidateResourceTypeFormat

func ValidateResourceTypeFormat(resourceType string) bool

ValidateResourceTypeFormat checks if a resource type string is properly formatted Returns true if the format matches the expected GVK pattern Valid formats: "v1/Kind" (core API) or "group/version/Kind" (non-core API)

Types

type ApplierComponents

type ApplierComponents struct {
	KubernetesClient       KubernetesClient
	DynamicClient          dynamic.Interface
	DiscoveryClient        discovery.CachedDiscoveryInterface
	RestConfig             *rest.Config
	RestMapper             meta.RESTMapper
	Applier                cliUtilsApplier
	Destroyer              cliUtilsDestroyer
	InventoryClient        inventory.Client
	InventoryInfo          inventory.Info
	ServerSideOptions      common.ServerSideOptions
	ReconcileTimeout       time.Duration
	PruneTimeout           time.Duration
	PrunePropagationPolicy metav1.DeletionPropagation
	InventoryPolicy        inventory.Policy
}

ApplierComponents holds all components needed for apply operations

type ApplierConfig

type ApplierConfig struct {
	KubeContext       string
	EnforcedNamespace string // If non-empty, every namespaced resource's metadata.namespace must equal this value
	LiveData          []byte // LiveData containing inventory and resources (legacy)
	BridgeState       []byte // BridgeState containing inventory ConfigMap YAML
	SpaceID           string // SpaceID for inventory identification
	UnitSlug          string // UnitSlug for inventory identification
	RevisionNum       int64  // RevisionNum for the revision being applied
	WaitTimeout       string // WaitTimeout duration string for resource readiness
	DryRun            bool   // DryRun uses server-side dry run (validates without persisting)
	// ProgressingTimeout bounds how long a resource may remain kstatus=InProgress
	// with no augmented-status transition before the statuspoller flags it Stuck.
	// Zero means use the statuspoller's default (150s).
	ProgressingTimeout time.Duration
}

ApplierConfig contains configuration for creating an applier

func CreateApplierConfig added in v0.1.41

func CreateApplierConfig(payload api.BridgeWorkerPayload) (ApplierConfig, error)

CreateApplierConfig creates an ApplierConfig from the payload. Exported so renderer bridges can build an applier config and apply auxiliary resources (e.g. the Flux CR that the Flux renderer SSA-applies with spec.suspend=true).

type ApplierName

type ApplierName string
const (
	CLIUtilsSSA ApplierName = "CLIUtilsSSA"
)

type ApplyResult

type ApplyResult struct {
	ResourceSet      ResourceSet
	LiveObjects      []*unstructured.Unstructured
	LiveData         []byte // Updated LiveData including inventory
	LiveState        []byte
	ResourceStatuses api.ResourceStatusMap // Per-resource sync and readiness status
	Error            error
}

ApplyResult contains the result of an apply operation

type CLIUtilsApplier

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

CLIUtilsApplier implements K8sApplier using kubernetes-sigs/cli-utils.

Lifecycle: a fresh CLIUtilsApplier is constructed per bridge handler invocation (KubernetesBridgeWorker.GetOrCreateApplier returns a new instance for every Apply / WaitForApply / Destroy / WaitForDestroy / Refresh call). The applier therefore holds no state that crosses calls; no protocol exists between Apply and WaitForApply on the same instance. Each method does its own work end to end and returns the result through ApplyResult / WaitResult / DestroyResult.

All fields are populated at construction and never mutated afterwards, except liveData: Apply may rewrite it after the LiveDataBuilder produces an updated serialization, and the rewritten bytes are returned in the same ApplyResult.

Per-call computed values (ResourceSet, ResourceStatusMap) are kept on the stack and threaded through return values rather than stashed on the receiver. The wctx is also per-call: WaitForApply receives it as a parameter and uses wctx.SendStatus directly, so no stale per-instance emitter can outlive its request.

func (*CLIUtilsApplier) Apply

Apply implements K8sApplier.Apply following the CLI-Utils algorithm

func (*CLIUtilsApplier) Destroy

Destroy implements K8sApplier.Destroy following the CLI-Utils algorithm

func (*CLIUtilsApplier) Refresh

Refresh implements K8sApplier.Refresh Returns uncleaned live objects - caller will cleanup for LiveData, keep uncleaned for LiveState

func (*CLIUtilsApplier) WaitForApply

func (a *CLIUtilsApplier) WaitForApply(wctx api.BridgeWorkerContext, objects []*unstructured.Unstructured, timeout time.Duration) WaitResult

WaitForApply implements K8sApplier.WaitForApply.

The applier is constructed fresh per call (see CLIUtilsApplier doc), so WaitForApply does not assume any state was carried over from the Apply that preceded it on the wire. The bridge worker's Apply handler returns before WaitForApply is dispatched, so by the time we get here Apply is either already on the cluster or never will be — there is nothing to wait for at the in-process level.

Streaming: the wait loop publishes Progressing ActionResults via wctx.SendStatus as the rollup state changes or on heartbeats. The internal Apply-driven brief wait passes nil for the emitter and runs silently.

func (*CLIUtilsApplier) WaitForDestroy

func (a *CLIUtilsApplier) WaitForDestroy(wctx api.BridgeWorkerContext, objects []*unstructured.Unstructured, timeout time.Duration) WaitResult

WaitForDestroy implements K8sApplier.WaitForDestroy.

As with WaitForApply, the applier is fresh per call (see CLIUtilsApplier doc), so WaitForDestroy does not assume any state was carried over from the Destroy that preceded it on the wire. The handler simply polls until the named objects are gone or the timeout fires.

type CachedResource

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

CachedResource represents a cached Kubernetes resource

type ConfigProvider

type ConfigProvider interface {
	GetConfig() (*rest.Config, error)
}

ConfigProvider interface allows for testing by controlling config retrieval

type DefaultConfigProvider

type DefaultConfigProvider struct{}

DefaultConfigProvider uses InClusterConfig for production

func (DefaultConfigProvider) GetConfig

func (d DefaultConfigProvider) GetConfig() (*rest.Config, error)

type DestroyResult

type DestroyResult struct {
	ResourceSet ResourceSet
	LiveData    []byte // Updated LiveData including inventory after destroy
	Error       error
}

DestroyResult contains the result of a destroy operation

type EventProcessor

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

EventProcessor handles events from apply/destroy operations. It tracks three types of resource modifications: - appliedObjects: Resources that were created or updated during apply - prunedObjects: Resources removed during apply because they're no longer in desired state - deletedObjects: Resources explicitly removed during destroy operations

type FetchStrategy

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

FetchStrategy determines how to fetch resources

type FreshDiscoveryClient

type FreshDiscoveryClient struct {
	*discovery.DiscoveryClient
}

FreshDiscoveryClient is a wrapper around DiscoveryClient that implements CachedDiscoveryInterface but always returns fresh data (no caching)

func (*FreshDiscoveryClient) Fresh

func (f *FreshDiscoveryClient) Fresh() bool

Fresh implements CachedDiscoveryInterface - always returns true since we don't cache

func (*FreshDiscoveryClient) Invalidate

func (f *FreshDiscoveryClient) Invalidate()

Invalidate implements CachedDiscoveryInterface - no-op since we don't cache

type ImportConfig

type ImportConfig struct {
	IncludeSystem  bool
	IncludeCustom  bool
	IncludeCluster bool
	IncludeOwned   bool
	Namespaces     []string
	Filters        []goclientnew.ImportFilter
}

ImportConfig holds the configuration options for resource import

func NewImportConfigFromRequest

func NewImportConfigFromRequest(request *goclientnew.ImportRequest) *ImportConfig

NewImportConfigFromRequest creates an ImportConfig from an ImportRequest

type InMemInventory

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

InMemInventory represents an in-memory inventory

func (*InMemInventory) GetObjectRefs

func (i *InMemInventory) GetObjectRefs() object.ObjMetadataSet

GetObjectRefs returns the list of object references tracked in the inventory

func (*InMemInventory) GetObjectStatuses

func (i *InMemInventory) GetObjectStatuses() object.ObjectStatusSet

GetObjectStatuses returns the list of statuses for each object reference

func (*InMemInventory) Info

func (i *InMemInventory) Info() inventory.Info

Info returns the inventory info

func (*InMemInventory) SetObjectRefs

func (i *InMemInventory) SetObjectRefs(refs object.ObjMetadataSet)

SetObjectRefs updates the local cache of object references

func (*InMemInventory) SetObjectStatuses

func (i *InMemInventory) SetObjectStatuses(statuses object.ObjectStatusSet)

SetObjectStatuses updates the local cache of object statuses

type InMemInventoryClient

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

InMemInventoryClient is an inventory client that stores everything in memory

func NewInMemInventoryClient

func NewInMemInventoryClient() *InMemInventoryClient

NewInMemInventoryClient creates a new in-memory inventory client

func (*InMemInventoryClient) CreateFromLiveData

func (c *InMemInventoryClient) CreateFromLiveData(ctx context.Context, liveData []byte, inv inventory.Info) (*InventoryConfigMap, []byte, error)

CreateFromLiveData creates an InMemInventoryClient initialized with LiveData data

func (*InMemInventoryClient) CreateOrUpdate

CreateOrUpdate creates or updates an inventory object in memory

func (*InMemInventoryClient) Delete

Delete removes an inventory object from memory

func (*InMemInventoryClient) Get

Get retrieves an inventory object from memory

func (*InMemInventoryClient) List

List returns all inventory objects from memory

func (*InMemInventoryClient) NewInventory

func (c *InMemInventoryClient) NewInventory(info inventory.Info) (inventory.Inventory, error)

NewInventory returns an empty initialized inventory object

func (*InMemInventoryClient) PopulateFromObjects

func (c *InMemInventoryClient) PopulateFromObjects(ctx context.Context, inv inventory.Info, objects []*unstructured.Unstructured) error

PopulateFromObjects populates the inventory with object metadata from unstructured objects. This is used for backward compatibility when inventory is empty but objects need to be tracked (e.g., for units created before inventory tracking was added).

func (*InMemInventoryClient) SaveToLiveData

func (c *InMemInventoryClient) SaveToLiveData(inventoryCM *InventoryConfigMap, inventoryInfo inventory.Info, resources []byte) ([]byte, error)

SaveToLiveData updates the LiveData with the current inventory state

type InventoryConfigMap

type InventoryConfigMap struct {
	*unstructured.Unstructured
}

InventoryConfigMap represents the structure of the inventory ConfigMap that tracks applied resources for pruning and lifecycle management

func NewInventoryConfigMap

func NewInventoryConfigMap(inv inventory.Info) *InventoryConfigMap

NewInventoryConfigMap creates a new inventory ConfigMap for the given inventory info

func NewInventoryConfigMapWithOptions

func NewInventoryConfigMapWithOptions(inv inventory.Info, opts InventoryOptions) *InventoryConfigMap

NewInventoryConfigMapWithOptions creates a new inventory ConfigMap with optional metadata

func SplitInventoryFromLiveData

func SplitInventoryFromLiveData(liveData []byte) (*InventoryConfigMap, []byte, error)

SplitInventoryFromLiveData splits the LiveData YAML into inventory ConfigMap and remaining resources The inventory ConfigMap is expected to be the first document in the YAML

func (*InventoryConfigMap) GetInventoryID

func (i *InventoryConfigMap) GetInventoryID() string

GetInventoryID retrieves the inventory ID from the ConfigMap

func (*InventoryConfigMap) IsValid

func (i *InventoryConfigMap) IsValid() bool

IsValid checks if the InventoryConfigMap is valid

type InventoryMetadata

type InventoryMetadata struct {
	SpaceID       string
	UnitSlug      string
	InventoryName string
	InventoryID   string
}

InventoryMetadata contains extracted inventory metadata

type InventoryOptions

type InventoryOptions struct {
	Name     string
	SpaceID  string
	UnitSlug string
}

InventoryOptions contains optional metadata for inventory ConfigMap

type K8sApplier

type K8sApplier interface {
	// Apply applies the given objects to the cluster
	Apply(wctx api.BridgeWorkerContext, objects []*unstructured.Unstructured) ApplyResult

	// WaitForApply waits for applied resources to be ready. Progress is
	// streamed through wctx.SendStatus; implementations that don't stream
	// (e.g. cluster-internal waits) ignore wctx beyond Context().
	WaitForApply(wctx api.BridgeWorkerContext, objects []*unstructured.Unstructured, timeout time.Duration) WaitResult

	// Refresh retrieves the current live state of objects
	Refresh(wctx api.BridgeWorkerContext, objects []*unstructured.Unstructured) ([]*unstructured.Unstructured, error)

	// Destroy deletes the given objects from the cluster
	Destroy(wctx api.BridgeWorkerContext, objects []*unstructured.Unstructured) DestroyResult

	// WaitForDestroy waits for resources to be terminated and returns the final state
	WaitForDestroy(wctx api.BridgeWorkerContext, objects []*unstructured.Unstructured, timeout time.Duration) WaitResult
}

K8sApplier defines the interface for Kubernetes resource operations Note: Import is not part of this interface because it's a higher-level operation that reads live objects from the cluster based on discovery/filtering logic. Import belongs to the BridgeWorker interface as it operates at the orchestration level, while K8sApplier focuses on direct resource manipulation (apply/destroy/refresh).

func NewCLIUtilsApplier

func NewCLIUtilsApplier(config ApplierConfig) (K8sApplier, error)

NewCLIUtilsApplier creates a new K8sApplier instance.

SpaceID and UnitSlug are hard preconditions: the inventory ConfigMap's identity is derived from them, so missing either would either collide with other units or produce a malformed id (e.g. a bare "-"). The bridge worker should never invoke the applier without both set; we fail loudly here rather than fabricate an id from KubeContext (which is worker-local and frequently empty in-cluster).

func NewK8sApplier

func NewK8sApplier(name ApplierName, config ApplierConfig) (K8sApplier, error)

type KubernetesBridgeWorker

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

func NewKubernetesBridgeWorker

func NewKubernetesBridgeWorker() *KubernetesBridgeWorker

NewKubernetesBridgeWorker creates a new KubernetesBridgeWorker with CLI Utils SSA as default

func (*KubernetesBridgeWorker) Apply

func (*KubernetesBridgeWorker) BuildBridgeState added in v0.1.25

func (w *KubernetesBridgeWorker) BuildBridgeState(payload api.BridgeWorkerPayload, appliedObjects []*unstructured.Unstructured) []byte

BuildBridgeState generates the CLIUtils inventory ConfigMap YAML for the given applied objects (e.g., ArgoCD Application CRs, Flux Kustomization CRs). The result is suitable for storing in ActionResult.BridgeState.

func (*KubernetesBridgeWorker) Destroy

func (*KubernetesBridgeWorker) Finalize

Finalize implements api.BridgeWorker.Finalize This method is called when the worker is being shutdown or cleaned up

func (*KubernetesBridgeWorker) GetApplierType

func (w *KubernetesBridgeWorker) GetApplierType() ApplierName

GetApplierType returns the applier type used by this bridge worker.

func (*KubernetesBridgeWorker) GetOrCreateApplier

func (w *KubernetesBridgeWorker) GetOrCreateApplier(payload api.BridgeWorkerPayload) (K8sApplier, error)

GetOrCreateApplier returns the applier instance, creating it if needed

func (*KubernetesBridgeWorker) GetResourceProvider

func (w *KubernetesBridgeWorker) GetResourceProvider() *k8skit.K8sResourceProviderType

GetResourceProvider returns the resource provider used by this bridge worker.

func (*KubernetesBridgeWorker) ID

func (*KubernetesBridgeWorker) Import

func (w *KubernetesBridgeWorker) Import(wctx api.BridgeWorkerContext, payload api.BridgeWorkerPayload) (retErr error)

func (*KubernetesBridgeWorker) Info

func (*KubernetesBridgeWorker) InfoForToolchainAndProvider

func (w *KubernetesBridgeWorker) InfoForToolchainAndProvider(opts api.InfoOptions, toolchain workerapi.ToolchainType, provider api.ProviderType) api.BridgeWorkerInfo

This supports ToolchainTypes and ProviderTypes that generate and apply Kubernetes resources.

func (*KubernetesBridgeWorker) Refresh

func (*KubernetesBridgeWorker) SetApplierType

func (w *KubernetesBridgeWorker) SetApplierType(t ApplierName)

SetApplierType sets the applier type used by this bridge worker.

func (*KubernetesBridgeWorker) WatchForApply

func (*KubernetesBridgeWorker) WatchForDestroy

func (w *KubernetesBridgeWorker) WatchForDestroy(wctx api.BridgeWorkerContext, payload api.BridgeWorkerPayload) error

type KubernetesClient

type KubernetesClient interface {
	Get(ctx context.Context, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error
	Create(ctx context.Context, obj client.Object, opts ...client.CreateOption) error
	Update(ctx context.Context, obj client.Object, opts ...client.UpdateOption) error
	Patch(ctx context.Context, obj client.Object, patch client.Patch, opts ...client.PatchOption) error
	Delete(ctx context.Context, obj client.Object, opts ...client.DeleteOption) error
	DeleteAllOf(ctx context.Context, obj client.Object, opts ...client.DeleteAllOfOption) error
	IsObjectNamespaced(obj runtime.Object) (bool, error)
	// Add other methods as needed
	List(ctx context.Context, list client.ObjectList, opts ...client.ListOption) error
}

type KubernetesWorkerParams

type KubernetesWorkerParams struct {
	KubeContext string `json:",omitempty"`
	WaitTimeout string `json:",omitempty"` // Duration string like "5m0s", "10h5m"

	// Retry configuration
	RetryInitialInterval string  `json:",omitempty"` // Initial retry interval (e.g., "10s")
	RetryMultiplier      float64 `json:",omitempty"` // Backoff multiplier (e.g., 2.0)
	RetryMaxInterval     string  `json:",omitempty"` // Max retry interval (e.g., "5m")
	RetryMaxElapsedTime  string  `json:",omitempty"` // Max total time for retries (e.g., "30m")
}

func ParseTargetParams

func ParseTargetParams(payload api.BridgeWorkerPayload) (KubernetesWorkerParams, string, error)

ParseTargetParams extracts and parses target parameters. KubeContext is resolved from BridgeHandle first (the new model), falling back to the deprecated KubeContext field in TargetParams JSON for backward compatibility.

func (KubernetesWorkerParams) ToMap

func (p KubernetesWorkerParams) ToMap() map[string]interface{}

type ListOptionsBuilder

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

ListOptionsBuilder helps construct Kubernetes list options consistently

func NewListOptionsBuilder

func NewListOptionsBuilder() *ListOptionsBuilder

NewListOptionsBuilder creates a new builder

func (*ListOptionsBuilder) Build

func (b *ListOptionsBuilder) Build() []client.ListOption

Build constructs the final list options

func (*ListOptionsBuilder) WithFilters

WithFilters adds filters to the builder

func (*ListOptionsBuilder) WithNamespace

func (b *ListOptionsBuilder) WithNamespace(namespace string) *ListOptionsBuilder

WithNamespace sets the target namespace

func (*ListOptionsBuilder) WithSystemFiltering

func (b *ListOptionsBuilder) WithSystemFiltering(includeSystem, isNamespaced bool) *ListOptionsBuilder

WithSystemFiltering configures system resource filtering

type LiveDataBuilder

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

LiveDataBuilder optimally builds LiveData from tracked events

func NewLiveDataBuilder

func NewLiveDataBuilder(
	inventory inventory.Client,
	dynamicClient dynamic.Interface,
	restMapper meta.RESTMapper,
	spaceID string,
	unitSlug string,
) *LiveDataBuilder

NewLiveDataBuilder creates a new LiveDataBuilder

func (*LiveDataBuilder) BuildLiveData

func (b *LiveDataBuilder) BuildLiveData(
	ctx context.Context,
	invInfo inventory.Info,
	processor *EventProcessor,
	previousLiveData []byte,
) (liveData []byte, resourceSet ResourceSet, err error)

BuildLiveData builds optimal LiveData from tracked events

type MockBridgeWorkerContext

type MockBridgeWorkerContext struct {
	mock.Mock
}

MockBridgeWorkerContext implements api.BridgeWorkerContext for testing.

func SetupMockContext

func SetupMockContext(t *testing.T) *MockBridgeWorkerContext

SetupMockContext creates a new MockBridgeWorkerContext with default context.

func (*MockBridgeWorkerContext) Context

func (*MockBridgeWorkerContext) GetServerURL

func (m *MockBridgeWorkerContext) GetServerURL() string

func (*MockBridgeWorkerContext) GetWorkerID

func (m *MockBridgeWorkerContext) GetWorkerID() string

func (*MockBridgeWorkerContext) SendStatus

func (m *MockBridgeWorkerContext) SendStatus(result *api.ActionResult) error

type MockK8sApplier

type MockK8sApplier struct {
	mock.Mock
}

MockK8sApplier is a mock implementation of the K8sApplier interface.

func (*MockK8sApplier) Apply

func (*MockK8sApplier) BuildLiveState

func (m *MockK8sApplier) BuildLiveState(ctx context.Context) ([]*unstructured.Unstructured, error)

func (*MockK8sApplier) Destroy

func (*MockK8sApplier) Refresh

func (*MockK8sApplier) WaitForApply

func (m *MockK8sApplier) WaitForApply(wctx api.BridgeWorkerContext, objects []*unstructured.Unstructured, timeout time.Duration) WaitResult

func (*MockK8sApplier) WaitForDestroy

func (m *MockK8sApplier) WaitForDestroy(wctx api.BridgeWorkerContext, objects []*unstructured.Unstructured, timeout time.Duration) WaitResult

type MockK8sClient

type MockK8sClient struct {
	mock.Mock
}

MockK8sClient is a mock implementation of the KubernetesClient interface.

func (*MockK8sClient) Create

func (m *MockK8sClient) Create(ctx context.Context, obj client.Object, opts ...client.CreateOption) error

func (*MockK8sClient) Delete

func (m *MockK8sClient) Delete(ctx context.Context, obj client.Object, opts ...client.DeleteOption) error

func (*MockK8sClient) DeleteAllOf

func (m *MockK8sClient) DeleteAllOf(ctx context.Context, obj client.Object, opts ...client.DeleteAllOfOption) error

func (*MockK8sClient) Get

func (*MockK8sClient) IsObjectNamespaced

func (m *MockK8sClient) IsObjectNamespaced(obj runtime.Object) (bool, error)

func (*MockK8sClient) List

func (m *MockK8sClient) List(ctx context.Context, list client.ObjectList, opts ...client.ListOption) error

func (*MockK8sClient) Patch

func (m *MockK8sClient) Patch(ctx context.Context, obj client.Object, patch client.Patch, opts ...client.PatchOption) error

func (*MockK8sClient) Update

func (m *MockK8sClient) Update(ctx context.Context, obj client.Object, opts ...client.UpdateOption) error

type ResourceCache

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

ResourceCache provides LRU caching for unchanged resources

func NewResourceCache

func NewResourceCache(maxSize int, maxAge time.Duration) *ResourceCache

NewResourceCache creates a new resource cache

func (*ResourceCache) Get

Get retrieves a cached resource

func (*ResourceCache) IsValid

func (c *ResourceCache) IsValid(key string) bool

IsValid checks if a cached resource is still valid

func (*ResourceCache) Put

func (c *ResourceCache) Put(key string, obj *unstructured.Unstructured)

Put stores a resource in cache

func (*ResourceCache) Remove

func (c *ResourceCache) Remove(key string)

Remove deletes a resource from cache

type ResourceDiscovery

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

ResourceDiscovery encapsulates the logic for discovering and filtering Kubernetes resources

func NewResourceDiscovery

func NewResourceDiscovery(client KubernetesClient, config *ImportConfig, cfg *rest.Config) *ResourceDiscovery

NewResourceDiscovery creates a new ResourceDiscovery instance

func (*ResourceDiscovery) Discover

func (rd *ResourceDiscovery) Discover() ([]*unstructured.Unstructured, error)

Discover performs resource discovery based on the configured parameters

type ResourceSet

type ResourceSet interface {
	// Entries returns a slice that can be used to get the count of changes
	GetEntries() []ResourceSetEntry
}

ResourceSet represents a generic resource set interface This allows different applier implementations to provide their own ResourceSet types

type ResourceSetEntry

type ResourceSetEntry interface {
	// Minimal interface for change set entries
	String() string
}

ResourceSetEntry represents a single change in the resource set

type ResourceTypeInfo

type ResourceTypeInfo struct {
	GVK        schema.GroupVersionKind
	Namespaced bool
}

ResourceTypeInfo holds information about a discovered resource type including its GVK and whether it's namespaced

type SimpleInventoryInfo

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

SimpleInventoryInfo implements the inventory.Info interface

func (*SimpleInventoryInfo) GetID

func (s *SimpleInventoryInfo) GetID() inventory.ID

func (*SimpleInventoryInfo) GetName

func (s *SimpleInventoryInfo) GetName() string

func (*SimpleInventoryInfo) GetNamespace

func (s *SimpleInventoryInfo) GetNamespace() string

type SimpleRESTClientGetter

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

SimpleRESTClientGetter implements genericclioptions.RESTClientGetter using our existing REST config

func (*SimpleRESTClientGetter) ToDiscoveryClient

func (*SimpleRESTClientGetter) ToRESTConfig

func (r *SimpleRESTClientGetter) ToRESTConfig() (*rest.Config, error)

func (*SimpleRESTClientGetter) ToRESTMapper

func (r *SimpleRESTClientGetter) ToRESTMapper() (meta.RESTMapper, error)

func (*SimpleRESTClientGetter) ToRawKubeConfigLoader

func (r *SimpleRESTClientGetter) ToRawKubeConfigLoader() clientcmd.ClientConfig

type SimpleResourceSet

type SimpleResourceSet struct {
	Entries []SimpleResourceSetEntry
}

SimpleResourceSet is a basic implementation of ResourceSet

func NewSimpleResourceSet

func NewSimpleResourceSet() *SimpleResourceSet

NewSimpleResourceSet creates a new SimpleResourceSet

func (*SimpleResourceSet) Add

Add adds an entry to the SimpleResourceSet

func (*SimpleResourceSet) GetEntries

func (s *SimpleResourceSet) GetEntries() []ResourceSetEntry

type SimpleResourceSetEntry

type SimpleResourceSetEntry struct {
	Name      string
	Namespace string
	Kind      string
	Action    string
}

SimpleResourceSetEntry is a basic implementation of ResourceSetEntry

func (SimpleResourceSetEntry) String

func (s SimpleResourceSetEntry) String() string

type WaitResult

type WaitResult struct {
	LiveObjects      []*unstructured.Unstructured
	ResourceSet      ResourceSet
	ResourceStatuses api.ResourceStatusMap // Per-resource sync and readiness status
	Error            error
}

WaitResult contains the result of a wait operation

Directories

Path Synopsis
Package cleanup performs the heuristic object cleanup the Kubernetes bridge applies to live cluster state before storing it as a Unit's configuration data (during Refresh and import): stripping fields not owned by any applier, removing status / managedFields / internal metadata, dropping cluster-internal annotations and labels, and normalizing resource quantities.
Package cleanup performs the heuristic object cleanup the Kubernetes bridge applies to live cluster state before storing it as a Unit's configuration data (during Refresh and import): stripping fields not owned by any applier, removing status / managedFields / internal metadata, dropping cluster-internal annotations and labels, and normalizing resource quantities.
Package mfclass classifies Kubernetes server-side-apply field managers into meaningful categories — appliers (kubectl, ConfigHub, ArgoCD, Flux, Sveltos, Helm, …), asynchronous controllers, admission controllers, and default fields — and provides field-set utilities built on structured-merge-diff for reasoning about which fields each manager owns.
Package mfclass classifies Kubernetes server-side-apply field managers into meaningful categories — appliers (kubectl, ConfigHub, ArgoCD, Flux, Sveltos, Helm, …), asynchronous controllers, admission controllers, and default fields — and provides field-set utilities built on structured-merge-diff for reasoning about which fields each manager owns.
Package statuspoller augments sigs.k8s.io/cli-utils/kstatus with a Stuck state driven by per-kind classifiers.
Package statuspoller augments sigs.k8s.io/cli-utils/kstatus with a Stuck state driven by per-kind classifiers.

Jump to

Keyboard shortcuts

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