provider

package
v0.1.1-alpha.3 Latest Latest
Warning

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

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

Documentation

Overview

Package provider defines the infrastructure provider interfaces.

This is the Anti-Corruption Layer between the platform and KubeVirt. All provider methods return domain types, not K8s types.

Import Path (ADR-0016): kv-shepherd.io/shepherd/internal/provider

Index

Constants

View Source
const (
	AuthInteractionRedirect    = runtimecontract.AuthInteractionRedirect
	AuthInteractionCredentials = runtimecontract.AuthInteractionCredentials
)
View Source
const (
	DirectoryConflictSameExternalIdentity = directorycontract.DirectoryConflictSameExternalIdentity
	DirectoryConflictUsernameConflict     = directorycontract.DirectoryConflictUsernameConflict
	DirectoryConflictEmailConflict        = directorycontract.DirectoryConflictEmailConflict
	DirectoryConflictAmbiguousExisting    = directorycontract.DirectoryConflictAmbiguousExisting
)
View Source
const (
	DirectoryActionCreate  = directorycontract.DirectoryActionCreate
	DirectoryActionUpdate  = directorycontract.DirectoryActionUpdate
	DirectoryActionBlocked = directorycontract.DirectoryActionBlocked
)
View Source
const AuthProviderProtectedFieldMask = configcodec.AuthProviderProtectedFieldMask
View Source
const (
	DirectoryEnrichmentModeEnrichExistingOnly = directorycontract.DirectoryEnrichmentModeEnrichExistingOnly
)
View Source
const (
	DirectoryJoinKeyUsername = directorycontract.DirectoryJoinKeyUsername
)
View Source
const (
	DirectoryPreviewMatchByExternalID = directorycontract.DirectoryPreviewMatchByExternalID
)
View Source
const (
	// FieldOwner identifies kubevirt-shepherd as the field manager for SSA.
	// Per ADR-0011: platform is Source of Truth; Force=true overwrites manual edits.
	FieldOwner = "kubevirt-shepherd"
)

Variables

View Source
var (
	ErrAuthProviderConfigCodecKeyMissing = configcodec.ErrAuthProviderConfigCodecKeyMissing
	ErrAuthProviderConfigCiphertext      = configcodec.ErrAuthProviderConfigCiphertext
	ErrAuthProviderConfigDecrypt         = configcodec.ErrAuthProviderConfigDecrypt
)

Functions

func CloneDirectoryAttributes

func CloneDirectoryAttributes(value map[string]interface{}) map[string]interface{}

CloneDirectoryAttributes clones an opaque JSON-like attribute map.

func DefaultRootDataVolumeName

func DefaultRootDataVolumeName(vmName string) string

DefaultRootDataVolumeName returns the platform-managed root DataVolume name for a VM when using the default naming profile.

func HasAllCapabilities

func HasAllCapabilities(clusterFeatures, required []string) bool

HasAllCapabilities is a package-level helper for filtering clusters by feature set. Operates on raw []string from DB (Cluster.enabled_features), avoiding ClusterCapabilities allocation. Used by ListCompatibleClusters API handler (ADR-0014 Layer 3 / P2-A).

func NewAuthCredentialError

func NewAuthCredentialError(code, message string) error

NewAuthCredentialError constructs a structured credential-login error.

func NewAuthStartError

func NewAuthStartError(code, message string) error

NewAuthStartError constructs a structured login-start error.

func NewDirectorySyncRequestError

func NewDirectorySyncRequestError(message string) error

NewDirectorySyncRequestError constructs a request-validation error.

func RegisterAuthProviderAdminAdapter

func RegisterAuthProviderAdminAdapter(adapter AuthProviderAdminAdapter) error

RegisterAuthProviderAdminAdapter registers an adapter globally.

func RenderVMLiveUpdatePatch

func RenderVMLiveUpdatePatch(namespace string, current *domain.VM, target VMLiveUpdateTargets) (*domain.VMMutation, error)

RenderVMLiveUpdatePatch builds an exact KubeVirt VM patch for a live VM resource update.

func RenderVMResourceUpdatePatch

func RenderVMResourceUpdatePatch(namespace string, current *domain.VM, target VMLiveUpdateTargets) (*domain.VMMutation, error)

RenderVMResourceUpdatePatch renders a VM resource patch using the safest supported path for the current VM state.

Running VMs use the strict live-update path. Stopped VMs can accept broader CPU/memory reconfiguration while disk remains expansion-only.

func RenderVMSpecToYAML

func RenderVMSpecToYAML(namespace string, spec *VMRenderInput) (string, error)

RenderVMSpecToYAML converts a VMRenderInput into a KubeVirt VirtualMachine YAML string.

This is the "YAML porter" implementation required by ADR-0011. The rendered YAML is consumed by DynamicSSAClient.ApplyYAML().

Resource granularity: CPU and Memory must be in 0.5-step increments.

  • CPU: 0.5, 1.0, 1.5, 2.0, ... (in cores)
  • Memory: 0.5, 1.0, 1.5, 2.0, ... (in Gi)

SpecOverrides (ADR-0018 Hybrid Model) are applied as deep-merge patches into the rendered YAML after template execution. Override paths are validated to start with "spec." prefix to prevent overwriting metadata or apiVersion.

Transition: When ADR-0007 user-managed templates are implemented, callers should use the template rendering pipeline instead and set spec.RenderedYAML directly.

func ResolveVMLiveCPUHotplugSupport

func ResolveVMLiveCPUHotplugSupport(current *domain.VM) (currentTotalCores, perSocketIncrement int, err error)

ResolveVMLiveCPUHotplugSupport validates that the current VM topology can be expanded via socket hotplug and returns the current total vCPU count together with the per-socket increment size.

Types

type ApprovalDecision

type ApprovalDecision = approvalcontract.ApprovalDecision

ApprovalDecision represents an approval decision.

type ApprovalExecutionOptions

type ApprovalExecutionOptions = approvalcontract.ApprovalExecutionOptions

ApprovalExecutionOptions are canonical core-owned fields needed to execute an approved work order after a provider reaches a final decision.

type ApprovalProvider

type ApprovalProvider = approvalcontract.ApprovalProvider

ApprovalProvider defines the approval workflow interface.

type ApprovalRequest

type ApprovalRequest = approvalcontract.ApprovalRequest

ApprovalRequest represents a canonical approval submission.

type ApprovalResponse

type ApprovalResponse = approvalcontract.ApprovalResponse

ApprovalResponse represents an approval submission response.

type AuthCallbackRequest

type AuthCallbackRequest = runtimecontract.AuthCallbackRequest

AuthCallbackRequest is the opaque callback envelope forwarded to providers.

type AuthCredentialCapability

type AuthCredentialCapability = runtimecontract.AuthCredentialCapability

AuthCredentialCapability is an optional auth-provider runtime extension for direct credential submission flows.

type AuthCredentialError

type AuthCredentialError = runtimecontract.AuthCredentialError

AuthCredentialError indicates a provider-owned credential-login failure.

type AuthCredentialRequest

type AuthCredentialRequest = runtimecontract.AuthCredentialRequest

AuthCredentialRequest is the opaque credential envelope forwarded to providers.

type AuthInteractionType

type AuthInteractionType = runtimecontract.AuthInteractionType

type AuthLoginMode

type AuthLoginMode = runtimecontract.AuthLoginMode

AuthLoginMode describes one provider-owned login entrypoint.

type AuthProfileAttributes

type AuthProfileAttributes = runtimecontract.AuthProfileAttributes

AuthProfileAttributes stores display-only external profile metadata.

type AuthProviderAdminAdapter

type AuthProviderAdminAdapter = admincontract.AuthProviderAdminAdapter

AuthProviderAdminAdapter defines the plugin contract for auth provider management endpoints.

func ResolveAuthProviderAdminAdapter

func ResolveAuthProviderAdminAdapter(authType string) AuthProviderAdminAdapter

ResolveAuthProviderAdminAdapter resolves an adapter from global registry.

type AuthProviderAdminAdapterDescriber

type AuthProviderAdminAdapterDescriber = admincontract.AuthProviderAdminAdapterDescriber

AuthProviderAdminAdapterDescriber is an optional adapter extension for metadata exposure.

type AuthProviderConfigCodec

type AuthProviderConfigCodec = configcodec.AuthProviderConfigCodec

func NewAuthProviderConfigCodec

func NewAuthProviderConfigCodec(encryptionKey []byte) *AuthProviderConfigCodec

type AuthProviderSampleField

type AuthProviderSampleField = admincontract.AuthProviderSampleField

AuthProviderSampleField is the normalized sample-field contract exposed by plugins.

type AuthProviderTypeDescriptor

type AuthProviderTypeDescriptor = admincontract.AuthProviderTypeDescriptor

AuthProviderTypeDescriptor describes a provider type exposed to admin UI/API.

func ListAuthProviderAdminAdapterTypes

func ListAuthProviderAdminAdapterTypes() []AuthProviderTypeDescriptor

ListAuthProviderAdminAdapterTypes returns all registered provider type descriptors.

type AuthResult

type AuthResult = runtimecontract.AuthResult

AuthResult is the canonical runtime auth result consumed by core.

type AuthRuntimeCapability

type AuthRuntimeCapability = runtimecontract.AuthRuntimeCapability

AuthRuntimeCapability is an optional auth-provider runtime extension.

type AuthRuntimeDescriber

type AuthRuntimeDescriber = runtimecontract.AuthRuntimeDescriber

AuthRuntimeDescriber exposes public runtime metadata when supported.

type AuthRuntimeDescriptor

type AuthRuntimeDescriptor = runtimecontract.AuthRuntimeDescriptor

AuthRuntimeDescriptor exposes public runtime metadata for login UX.

type AuthStartError

type AuthStartError = runtimecontract.AuthStartError

AuthStartError indicates a provider-owned login-start validation failure.

type AuthStartRequest

type AuthStartRequest = runtimecontract.AuthStartRequest

AuthStartRequest carries core-owned login parameters into the provider.

type AuthStartResponse

type AuthStartResponse = runtimecontract.AuthStartResponse

AuthStartResponse carries the provider-owned redirect URL back to core.

type AuthorizationClient

type AuthorizationClient interface {
	CreateSelfSubjectAccessReview(
		ctx context.Context,
		review *authorizationv1.SelfSubjectAccessReview,
		opts k8smetav1.CreateOptions,
	) (*authorizationv1.SelfSubjectAccessReview, error)
}

AuthorizationClient abstracts access reviews needed for CDI clone RBAC preflight.

type CapabilityDetector

type CapabilityDetector struct{}

CapabilityDetector detects cluster capabilities during health checks (ADR-0014).

Detection strategy (2 sources merged):

  1. GA features: inferred from KubeVirtVersion via static table — no K8s API call
  2. Explicit featureGates: read from kubevirt CR via KubeVirtCRClient.GetFeatureGates()

Called once per health check cycle per cluster (piggybacks on existing connection). Results are persisted to Cluster.enabled_features by lifecycle.go (P1-C).

func NewCapabilityDetector

func NewCapabilityDetector() *CapabilityDetector

NewCapabilityDetector creates a new CapabilityDetector (stateless, safe to share).

func (*CapabilityDetector) Detect

Detect fetches live capability data from the cluster.

Strategy (2 sources, merged):

  1. GA features: inferred from Status.ObservedKubeVirtVersion via static table (no VM API calls).
  2. Explicit featureGates: read from KubeVirt CR spec.configuration.developerConfiguration.featureGates.
  3. Node allocatable hugepages resources: read from Nodes().List() and mapped to feature keys like hugepages-2Mi / hugepages-1Gi.

Both are fetched from a single KubeVirt CR GET (the adapter layer caches the CR object via sync.Once, so GetVersion() and GetFeatureGates() share one GET).

Graceful degradation:

  • If the CR GET fails (RBAC / unreachable), both version and gates degrade gracefully.
  • Version falls back to "" → GA table returns nil.
  • Gates fall back to nil → GA-only detection.
  • Operator note: grant 'get kubevirts' on the 'kubevirt' namespace for full detection.

Cost: exactly 1 KubeVirt CR GET per health check cycle per cluster (sync.Once in kubecli_adapter.go ensures the second call reuses the cached CR).

type CloneProvider

type CloneProvider = infracontract.CloneProvider

type ClusterCapabilities

type ClusterCapabilities struct {
	KubeVirtVersion string    `json:"kubevirt_version"`
	EnabledFeatures []string  `json:"enabled_features"` // merged, lowercase-normalized keys
	DetectedAt      time.Time `json:"detected_at"`
}

ClusterCapabilities represents detected capabilities for a cluster (ADR-0014).

Stored as JSON in Cluster.enabled_features ([]string). EnabledFeatures is the merged result of:

  1. GA features guaranteed available at KubeVirtVersion (static table, no API call needed)
  2. Explicit feature gates in kubevirt CR spec.configuration.developerConfiguration.featureGates

This is the canonical structure for capability queries — prefer over raw []string from DB.

func (*ClusterCapabilities) HasAllFeatures

func (c *ClusterCapabilities) HasAllFeatures(required []string) bool

HasAllFeatures returns true when ALL required features are present. Used by ListCompatibleClusters (ADR-0014 Layer 3).

func (*ClusterCapabilities) HasFeature

func (c *ClusterCapabilities) HasFeature(name string) bool

HasFeature returns true if the cluster has the specified feature enabled. Case-insensitive match against EnabledFeatures.

type ClusterClientFactory

type ClusterClientFactory func(clusterName string) (KubeVirtClusterClient, error)

ClusterClientFactory creates KubeVirtClusterClient for a given cluster name.

func NewClusterClientFactoryFromKubeconfigLoader

func NewClusterClientFactoryFromKubeconfigLoader(loader KubeconfigLoader) ClusterClientFactory

NewClusterClientFactoryFromKubeconfigLoader builds a provider client factory backed by kubeconfig bytes loaded from persistence.

type ClusterHealth

type ClusterHealth struct {
	ClusterName     string        `json:"cluster_name"`
	Status          ClusterStatus `json:"status"`
	KubeVirtVersion string        `json:"kubevirt_version,omitempty"`
	EnabledFeatures []string      `json:"enabled_features,omitempty"` // ADR-0014: merged GA + explicit featureGates
	StorageClasses  []string      `json:"storage_classes,omitempty"`  // ADR-0015: auto-detected cluster StorageClasses
	// StorageClassesDetected distinguishes a successful empty detection result from
	// a degraded health check where StorageClass listing was skipped or failed.
	StorageClassesDetected bool      `json:"storage_classes_detected,omitempty"`
	LastChecked            time.Time `json:"last_checked"`
	Error                  string    `json:"error,omitempty"`
}

ClusterHealth contains health check results.

type ClusterHealthChecker

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

ClusterHealthChecker performs periodic health checks on registered clusters.

func NewClusterHealthChecker

func NewClusterHealthChecker(clientFactory ClusterClientFactory, interval time.Duration) *ClusterHealthChecker

NewClusterHealthChecker creates a new ClusterHealthChecker.

func (*ClusterHealthChecker) CheckCluster

func (c *ClusterHealthChecker) CheckCluster(ctx context.Context, clusterName string) *ClusterHealth

CheckCluster performs a single health check for a cluster.

Connectivity probe: calls client.KubeVirt().GetVersion() which does a GET on the cluster-scoped KubeVirt CR singleton. This is namespace-independent and always exists on correctly-installed KubeVirt clusters — unlike the former VM list probe which required VMs to exist in the "default" namespace.

Capability detection: runs CapabilityDetector.Detect() after connectivity is confirmed. Detection failure is non-fatal (RBAC may restrict featureGates access).

func (*ClusterHealthChecker) GetHealth

func (c *ClusterHealthChecker) GetHealth(clusterName string) *ClusterHealth

GetHealth returns the cached health status for a cluster.

func (*ClusterHealthChecker) Start

func (c *ClusterHealthChecker) Start(ctx context.Context, clusterNames []string)

Start begins periodic health checking for the given clusters.

func (*ClusterHealthChecker) UpdateHealth

func (c *ClusterHealthChecker) UpdateHealth(health *ClusterHealth)

UpdateHealth stores a health check result.

type ClusterStatus

type ClusterStatus string

ClusterStatus represents cluster health status.

const (
	ClusterStatusUnknown     ClusterStatus = "UNKNOWN"
	ClusterStatusHealthy     ClusterStatus = "HEALTHY"
	ClusterStatusUnhealthy   ClusterStatus = "UNHEALTHY"
	ClusterStatusUnreachable ClusterStatus = "UNREACHABLE"
)

type ConsoleProvider

type ConsoleProvider = infracontract.ConsoleProvider

type CredentialProvider

type CredentialProvider = infracontract.CredentialProvider

type DataVolumeClient

type DataVolumeClient interface {
	Get(ctx context.Context, namespace, name string, opts k8smetav1.GetOptions) (*cdiv1beta1.DataVolume, error)
	List(ctx context.Context, namespace string, opts k8smetav1.ListOptions) (*cdiv1beta1.DataVolumeList, error)
}

DataVolumeClient abstracts CDI DataVolume read operations.

type DirectoryAction

type DirectoryAction = directorycontract.DirectoryAction

DirectoryAction identifies the canonical create/update/blocked result semantics shared by preview and execution summaries.

type DirectoryActionSummary

type DirectoryActionSummary = directorycontract.DirectoryActionSummary

DirectoryActionSummary captures action-count totals for preview/result aggregation without reintroducing provider-specific flow semantics.

type DirectoryConflict

type DirectoryConflict = directorycontract.DirectoryConflict

DirectoryConflict captures canonical conflict classification details.

type DirectoryConflictCode

type DirectoryConflictCode = directorycontract.DirectoryConflictCode

DirectoryConflictCode identifies canonical pre-persistence conflict classes.

type DirectoryEnrichmentMode

type DirectoryEnrichmentMode = directorycontract.DirectoryEnrichmentMode

DirectoryEnrichmentMode identifies the canonical scheduled enrichment mode.

type DirectoryJoinKeyType

type DirectoryJoinKeyType = directorycontract.DirectoryJoinKeyType

DirectoryJoinKeyType identifies the explicit join rule used by scheduled enrichment.

type DirectoryPreviewItem

type DirectoryPreviewItem = directorycontract.DirectoryPreviewItem

DirectoryPreviewItem is the canonical preview row returned to admin clients.

type DirectoryPreviewMatch

type DirectoryPreviewMatch = directorycontract.DirectoryPreviewMatch

DirectoryPreviewMatch captures the canonical apply action and safe-match anchor.

type DirectoryPreviewMatchBy

type DirectoryPreviewMatchBy = directorycontract.DirectoryPreviewMatchBy

DirectoryPreviewMatchBy identifies the canonical safe-match anchor used by preview.

type DirectorySyncCapability

type DirectorySyncCapability = directorycontract.DirectorySyncCapability

DirectorySyncCapability is an optional auth-provider admin extension.

type DirectorySyncDescriptor

type DirectorySyncDescriptor = directorycontract.DirectorySyncDescriptor

DirectorySyncDescriptor describes provider-owned directory sync input.

type DirectorySyncPreview

type DirectorySyncPreview = directorycontract.DirectorySyncPreview

DirectorySyncPreview is the provider-agnostic preview response contract.

type DirectorySyncRequestError

type DirectorySyncRequestError = directorycontract.DirectorySyncRequestError

DirectorySyncRequestError indicates provider_request validation failure.

type DirectoryUserRecord

type DirectoryUserRecord = directorycontract.DirectoryUserRecord

DirectoryUserRecord is the canonical directory import record consumed by core.

type DynamicSSAClient

type DynamicSSAClient interface {
	// ApplyYAML submits YAML bytes as an SSA Patch to Kubernetes.
	// fieldManager is always FieldOwner ("kubevirt-shepherd").
	ApplyYAML(ctx context.Context, namespace string, yamlData []byte) (*unstructured.Unstructured, error)

	// ApplyClusterScopedYAML submits cluster-scoped YAML bytes as an SSA Patch.
	// Used for non-namespaced resources such as Namespace.
	ApplyClusterScopedYAML(ctx context.Context, gvr schema.GroupVersionResource, yamlData []byte) (*unstructured.Unstructured, error)

	// DryRunApplyYAML validates YAML via SSA DryRun without creating the resource.
	DryRunApplyYAML(ctx context.Context, namespace string, yamlData []byte) error
}

DynamicSSAClient submits unstructured resources via Server-Side Apply. Used for all VM write operations (CreateVM / UpdateVM / ValidateSpec).

ADR-0011: Backend is a "YAML porter", not a "Struct assembly factory". All VM writes go through rendered YAML → Unstructured → SSA Patch.

type EventClient

type EventClient interface {
	List(ctx context.Context, namespace string, opts k8smetav1.ListOptions) (*corev1.EventList, error)
}

EventClient abstracts namespace-scoped Kubernetes Event reads.

type ExternalCohort

type ExternalCohort = runtimecontract.ExternalCohort

ExternalCohort is the provider-agnostic external organization shape.

type InfrastructureProvider

type InfrastructureProvider = infracontract.InfrastructureProvider

type InstanceTypeProvider

type InstanceTypeProvider = infracontract.InstanceTypeProvider

type KubeVirtCRClient

type KubeVirtCRClient interface {
	// GetFeatureGates fetches explicitly configured feature gates from the cluster-level KubeVirt CR.
	// Source: spec.configuration.developerConfiguration.featureGates ([]string).
	// Returns nil slice (not error) if DeveloperConfiguration is nil or FeatureGates is empty.
	// Returns error only on API failure (e.g., permission denied, cluster unreachable).
	GetFeatureGates(ctx context.Context) ([]string, error)

	// GetVersion fetches the observed running KubeVirt version from the cluster-level KubeVirt CR.
	// Source: status.observedKubeVirtVersion (set by the KubeVirt operator on successful reconciliation).
	// Returns empty string (not error) if the field is not yet populated (e.g., operator still deploying).
	// Returns error only on API failure (e.g., permission denied, cluster unreachable).
	GetVersion(ctx context.Context) (string, error)
}

KubeVirtCRClient provides access to the cluster-scoped KubeVirt CR. Used by CapabilityDetector to fetch enabled feature gates and running version (ADR-0014).

The KubeVirt CR is always: namespace="kubevirt", name="kubevirt". Separation from VirtualMachineClient keeps the VM CRUD ACL from CR read ACL.

type KubeVirtClusterClient

type KubeVirtClusterClient interface {
	VM() VirtualMachineClient          // Read + lifecycle (type-safe)
	VMI() VirtualMachineInstanceClient // VMI read + pause/unpause
	DataVolume() DataVolumeClient      // CDI DataVolume reads for provisioning observability
	StorageProfile() StorageProfileClient
	PVC() PersistentVolumeClaimClient   // PVC reads for provisioning observability
	StorageClass() StorageClassClient   // StorageClass reads for clone expansion preflight
	Events() EventClient                // CoreV1 Events for best-effort failure summaries
	Namespaces() NamespaceClient        // CoreV1 Namespaces for idempotent namespace creation
	Nodes() NodeClient                  // CoreV1 Nodes for host placement enrichment
	Pods() PodClient                    // CoreV1 Pods for PVC clone in-use preflight
	Authorization() AuthorizationClient // SAR for CDI clone source RBAC preflight
	SSA() DynamicSSAClient              // Write: CreateVM/UpdateVM (Unstructured SSA, ADR-0011)
	KubeVirt() KubeVirtCRClient         // KubeVirt CR access for capability detection (ADR-0014)
}

KubeVirtClusterClient provides kubevirt clients for a specific cluster. Composition root creates the actual implementation using kubecli.

type KubeVirtMapper

type KubeVirtMapper struct{}

KubeVirtMapper maps between KubeVirt K8s types and domain types. Anti-Corruption Layer: isolates domain logic from K8s API changes.

func NewKubeVirtMapper

func NewKubeVirtMapper() *KubeVirtMapper

NewKubeVirtMapper creates a new KubeVirtMapper.

func (*KubeVirtMapper) MapSnapshot

func (m *KubeVirtMapper) MapSnapshot(name, vmName, namespace string, ready bool, createdAt time.Time) *domain.Snapshot

MapSnapshot maps a VirtualMachineSnapshot to a domain Snapshot.

func (*KubeVirtMapper) MapVM

MapVM maps a KubeVirt VirtualMachine (and optional VMI) to a domain VM. Defensive programming: all pointer fields must check nil.

func (*KubeVirtMapper) MapVMList

MapVMList maps a slice of KubeVirt VMs to domain VMList.

type KubeVirtProvider

type KubeVirtProvider = infracontract.KubeVirtProvider

type KubeVirtProviderImpl

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

KubeVirtProviderImpl implements KubeVirtProvider using our client abstraction. ADR-0001: Use official kubevirt.io/client-go client (bound at composition root). ADR-0004: Interface composition (implements InfrastructureProvider + sub-providers). ADR-0011: VM writes use Server-Side Apply via DynamicSSAClient.

func NewKubeVirtProvider

func NewKubeVirtProvider(clientFactory ClusterClientFactory, operationTimeout time.Duration) *KubeVirtProviderImpl

NewKubeVirtProvider creates a new KubeVirtProvider. clientFactory creates a cluster client for the specified cluster.

func (*KubeVirtProviderImpl) CanClonePVCSource

func (p *KubeVirtProviderImpl) CanClonePVCSource(
	ctx context.Context,
	cluster, namespace string,
) (allowed bool, reason string, err error)

CanClonePVCSource checks whether the current cluster credential can create the CDI clone source subresource in the source namespace.

func (*KubeVirtProviderImpl) CreateVM

func (p *KubeVirtProviderImpl) CreateVM(ctx context.Context, cluster, namespace string, spec *domain.VMSpec) (*domain.VM, error)

CreateVM creates a VM via SSA Apply (ADR-0011).

The provider acts as a "YAML porter" — it submits the rendered YAML as an SSA Patch, never constructing typed structs.

func (*KubeVirtProviderImpl) DeleteVM

func (p *KubeVirtProviderImpl) DeleteVM(ctx context.Context, cluster, namespace, name string) error

DeleteVM deletes a VM.

func (*KubeVirtProviderImpl) DryRunVMMutation

func (p *KubeVirtProviderImpl) DryRunVMMutation(
	ctx context.Context,
	cluster, namespace, name string,
	mutation *domain.VMMutation,
) error

func (*KubeVirtProviderImpl) EnsureNamespace

func (p *KubeVirtProviderImpl) EnsureNamespace(ctx context.Context, cluster, namespace string) error

EnsureNamespace idempotently creates the target namespace on the selected cluster when it does not already exist.

func (*KubeVirtProviderImpl) ExecuteVMMutation

func (p *KubeVirtProviderImpl) ExecuteVMMutation(
	ctx context.Context,
	cluster, namespace, name string,
	mutation *domain.VMMutation,
) (*domain.VM, error)

func (*KubeVirtProviderImpl) GetDataVolume

func (p *KubeVirtProviderImpl) GetDataVolume(ctx context.Context, cluster, namespace, name string) (*domain.DataVolume, error)

GetDataVolume retrieves a CDI DataVolume for provisioning observability.

func (*KubeVirtProviderImpl) GetPersistentVolumeClaim

func (p *KubeVirtProviderImpl) GetPersistentVolumeClaim(ctx context.Context, cluster, namespace, name string) (*domain.PersistentVolumeClaim, error)

GetPersistentVolumeClaim retrieves a PVC backing a CDI DataVolume.

func (*KubeVirtProviderImpl) GetStorageClass

func (p *KubeVirtProviderImpl) GetStorageClass(ctx context.Context, cluster, name string) (*domain.StorageClass, error)

GetStorageClass retrieves a cluster-scoped StorageClass for clone-expansion preflight.

func (*KubeVirtProviderImpl) GetStorageProfile

func (p *KubeVirtProviderImpl) GetStorageProfile(ctx context.Context, cluster, name string) (*domain.StorageProfile, error)

GetStorageProfile retrieves the CDI StorageProfile for a target storage class.

func (*KubeVirtProviderImpl) GetVM

func (p *KubeVirtProviderImpl) GetVM(ctx context.Context, cluster, namespace, name string) (*domain.VM, error)

GetVM retrieves a VM from the specified cluster.

func (*KubeVirtProviderImpl) GetVMManifestYAML

func (p *KubeVirtProviderImpl) GetVMManifestYAML(ctx context.Context, cluster, namespace, name string) (string, error)

func (*KubeVirtProviderImpl) ListEventsForObject

func (p *KubeVirtProviderImpl) ListEventsForObject(ctx context.Context, cluster string, ref domain.ObjectReference) ([]domain.ProvisioningEvent, error)

ListEventsForObject lists best-effort Kubernetes Events for the referenced object.

func (*KubeVirtProviderImpl) ListPodsUsingPVC

func (p *KubeVirtProviderImpl) ListPodsUsingPVC(
	ctx context.Context,
	cluster, namespace, claimName string,
) ([]domain.ObjectReference, error)

ListPodsUsingPVC returns non-terminal pods that currently reference the source PVC.

func (*KubeVirtProviderImpl) ListVMs

func (p *KubeVirtProviderImpl) ListVMs(ctx context.Context, cluster, namespace string, opts ListOptions) (*domain.VMList, error)

ListVMs lists VMs in the specified namespace.

func (*KubeVirtProviderImpl) Name

func (p *KubeVirtProviderImpl) Name() string

Name returns the provider name.

func (*KubeVirtProviderImpl) OpenSerialConsoleStream

func (p *KubeVirtProviderImpl) OpenSerialConsoleStream(ctx context.Context, cluster, namespace, name string) (net.Conn, error)

OpenSerialConsoleStream opens a raw serial console stream backed by the official KubeVirt client.

func (*KubeVirtProviderImpl) OpenVNCStream

func (p *KubeVirtProviderImpl) OpenVNCStream(ctx context.Context, cluster, namespace, name string) (net.Conn, error)

OpenVNCStream opens a raw VNC stream backed by the official KubeVirt client.

func (*KubeVirtProviderImpl) PauseVM

func (p *KubeVirtProviderImpl) PauseVM(ctx context.Context, cluster, namespace, name string) error

PauseVM pauses a running VM.

func (*KubeVirtProviderImpl) RestartVM

func (p *KubeVirtProviderImpl) RestartVM(ctx context.Context, cluster, namespace, name string) error

RestartVM restarts a VM.

func (*KubeVirtProviderImpl) StartVM

func (p *KubeVirtProviderImpl) StartVM(ctx context.Context, cluster, namespace, name string) error

StartVM starts a stopped VM.

func (*KubeVirtProviderImpl) StopVM

func (p *KubeVirtProviderImpl) StopVM(ctx context.Context, cluster, namespace, name string) error

StopVM stops a running VM.

func (*KubeVirtProviderImpl) Type

func (p *KubeVirtProviderImpl) Type() string

Type returns the provider type.

func (*KubeVirtProviderImpl) UnpauseVM

func (p *KubeVirtProviderImpl) UnpauseVM(ctx context.Context, cluster, namespace, name string) error

UnpauseVM unpauses a paused VM.

func (*KubeVirtProviderImpl) UpdateVM

func (p *KubeVirtProviderImpl) UpdateVM(ctx context.Context, cluster, namespace, name string, spec *domain.VMSpec) (*domain.VM, error)

UpdateVM updates a VM via SSA Apply (ADR-0011).

Unlike the previous Get-Modify-Put pattern, SSA is declarative: the caller provides the full desired state in spec.RenderedYAML, and the API server merges it with existing state, preserving fields owned by other managers.

Safety: The YAML metadata.name is validated against the `name` parameter to prevent accidental overwrites of a different VM.

func (*KubeVirtProviderImpl) ValidateSpec

func (p *KubeVirtProviderImpl) ValidateSpec(ctx context.Context, cluster, namespace string, spec *domain.VMSpec) (*domain.ValidationResult, error)

ValidateSpec performs dry-run validation via SSA DryRun (ADR-0011).

Server-side DryRun is more authoritative than Go compiler checks for external CRDs: it validates against the actual CRD schema installed on the cluster.

type KubeconfigLoader

type KubeconfigLoader func(cluster string) ([]byte, error)

KubeconfigLoader resolves cluster kubeconfig bytes by cluster ID/name.

type KubevirtSSAApplier

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

KubevirtSSAApplier submits VirtualMachine resources via dynamic client + SSA. Implements DynamicSSAClient.

Architecture (ADR-0011):

DB Template YAML → text/template render → YAML string
                                           ↓
                          json.Marshal unstructured.Unstructured
                                           ↓
                  dynamic client Patch(types.ApplyPatchType)
                  FieldManager: "kubevirt-shepherd", Force: true

func NewKubevirtSSAApplier

func NewKubevirtSSAApplier(dynamicClient dynamic.Interface) *KubevirtSSAApplier

NewKubevirtSSAApplier creates a new SSA Applier backed by the given dynamic client.

func (*KubevirtSSAApplier) ApplyClusterScopedYAML

func (a *KubevirtSSAApplier) ApplyClusterScopedYAML(
	ctx context.Context,
	gvr schema.GroupVersionResource,
	yamlData []byte,
) (*unstructured.Unstructured, error)

ApplyClusterScopedYAML submits cluster-scoped YAML bytes via SSA Patch.

func (*KubevirtSSAApplier) ApplyYAML

func (a *KubevirtSSAApplier) ApplyYAML(ctx context.Context, namespace string, yamlData []byte) (*unstructured.Unstructured, error)

ApplyYAML submits YAML bytes as an SSA Patch to Kubernetes.

The method:

  1. Decodes YAML into an Unstructured object (zero dependency on typed structs).
  2. Marshals to JSON (required by types.ApplyPatchType).
  3. Patches via dynamic client with FieldManager and Force=true.

Force=true ensures kubevirt-shepherd owns all fields it declares, overwriting any conflicting field ownership (e.g., manual kubectl edits).

func (*KubevirtSSAApplier) DryRunApplyYAML

func (a *KubevirtSSAApplier) DryRunApplyYAML(ctx context.Context, namespace string, yamlData []byte) error

DryRunApplyYAML validates YAML via SSA DryRun without creating the resource. Used by ValidateSpec to leverage server-side validation (more authoritative than compile-time checks for external CRD fields).

type ListOptions

type ListOptions = infracontract.ListOptions

type MigrationProvider

type MigrationProvider = infracontract.MigrationProvider

type MockProvider

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

MockProvider implements InfrastructureProvider for testing without a K8s cluster.

func NewMockProvider

func NewMockProvider() *MockProvider

NewMockProvider creates a new MockProvider.

func (*MockProvider) CanClonePVCSource

func (p *MockProvider) CanClonePVCSource(_ context.Context, _, namespace string) (allowed bool, reason string, err error)

func (*MockProvider) CreateVM

func (p *MockProvider) CreateVM(_ context.Context, _, namespace string, spec *domain.VMSpec) (*domain.VM, error)

func (*MockProvider) DeleteVM

func (p *MockProvider) DeleteVM(_ context.Context, _, namespace, name string) error

func (*MockProvider) DryRunVMMutation

func (p *MockProvider) DryRunVMMutation(_ context.Context, _, namespace, name string, mutation *domain.VMMutation) error

func (*MockProvider) EnsureNamespace

func (p *MockProvider) EnsureNamespace(_ context.Context, _, namespace string) error

func (*MockProvider) ExecuteVMMutation

func (p *MockProvider) ExecuteVMMutation(ctx context.Context, cluster, namespace, name string, mutation *domain.VMMutation) (*domain.VM, error)

func (*MockProvider) GetDataVolume

func (p *MockProvider) GetDataVolume(_ context.Context, _, namespace, name string) (*domain.DataVolume, error)

func (*MockProvider) GetPersistentVolumeClaim

func (p *MockProvider) GetPersistentVolumeClaim(_ context.Context, _, namespace, name string) (*domain.PersistentVolumeClaim, error)

func (*MockProvider) GetStorageClass

func (p *MockProvider) GetStorageClass(_ context.Context, _, name string) (*domain.StorageClass, error)

func (*MockProvider) GetStorageProfile

func (p *MockProvider) GetStorageProfile(_ context.Context, _, name string) (*domain.StorageProfile, error)

func (*MockProvider) GetVM

func (p *MockProvider) GetVM(_ context.Context, _, namespace, name string) (*domain.VM, error)

func (*MockProvider) GetVMManifestYAML

func (p *MockProvider) GetVMManifestYAML(_ context.Context, _, namespace, name string) (string, error)

func (*MockProvider) ListEventsForObject

func (p *MockProvider) ListEventsForObject(_ context.Context, _ string, ref domain.ObjectReference) ([]domain.ProvisioningEvent, error)

func (*MockProvider) ListPodsUsingPVC

func (p *MockProvider) ListPodsUsingPVC(_ context.Context, _, namespace, claimName string) ([]domain.ObjectReference, error)

func (*MockProvider) ListVMs

func (p *MockProvider) ListVMs(_ context.Context, _, namespace string, _ ListOptions) (*domain.VMList, error)

func (*MockProvider) Name

func (p *MockProvider) Name() string

func (*MockProvider) OpenSerialConsoleStream

func (p *MockProvider) OpenSerialConsoleStream(_ context.Context, _, namespace, name string) (net.Conn, error)

func (*MockProvider) OpenVNCStream

func (p *MockProvider) OpenVNCStream(_ context.Context, _, namespace, name string) (net.Conn, error)

func (*MockProvider) PauseVM

func (p *MockProvider) PauseVM(_ context.Context, _, namespace, name string) error

func (*MockProvider) Reset

func (p *MockProvider) Reset()

Reset clears all mock data.

func (*MockProvider) RestartVM

func (p *MockProvider) RestartVM(_ context.Context, _, namespace, name string) error

func (*MockProvider) Seed

func (p *MockProvider) Seed(vms []*domain.VM)

Seed populates the mock provider with test data.

func (*MockProvider) SeedDataVolumes

func (p *MockProvider) SeedDataVolumes(items []*domain.DataVolume)

func (*MockProvider) SeedEvents

func (p *MockProvider) SeedEvents(ref domain.ObjectReference, items []domain.ProvisioningEvent)

func (*MockProvider) SeedPVCConsumers

func (p *MockProvider) SeedPVCConsumers(namespace, claimName string, items []domain.ObjectReference)

func (*MockProvider) SeedPVCs

func (p *MockProvider) SeedPVCs(items []*domain.PersistentVolumeClaim)

func (*MockProvider) SeedStorageClasses

func (p *MockProvider) SeedStorageClasses(items []*domain.StorageClass)

func (*MockProvider) SeedStorageProfiles

func (p *MockProvider) SeedStorageProfiles(items []*domain.StorageProfile)

func (*MockProvider) SetCloneSourceAccess

func (p *MockProvider) SetCloneSourceAccess(namespace string, allowed bool, reason string)

func (*MockProvider) SetSerialOpenError

func (p *MockProvider) SetSerialOpenError(err error)

func (*MockProvider) SetVNCOpenError

func (p *MockProvider) SetVNCOpenError(err error)

func (*MockProvider) StartVM

func (p *MockProvider) StartVM(_ context.Context, _, namespace, name string) error

func (*MockProvider) StopVM

func (p *MockProvider) StopVM(_ context.Context, _, namespace, name string) error

func (*MockProvider) Type

func (p *MockProvider) Type() string

func (*MockProvider) UnpauseVM

func (p *MockProvider) UnpauseVM(_ context.Context, _, namespace, name string) error

func (*MockProvider) UpdateVM

func (p *MockProvider) UpdateVM(_ context.Context, _, namespace, name string, spec *domain.VMSpec) (*domain.VM, error)

func (*MockProvider) ValidateSpec

func (p *MockProvider) ValidateSpec(_ context.Context, _, _ string, _ *domain.VMSpec) (*domain.ValidationResult, error)

type NamespaceClient

type NamespaceClient interface {
	Get(ctx context.Context, name string, opts k8smetav1.GetOptions) (*corev1.Namespace, error)
}

NamespaceClient abstracts cluster-scoped Namespace reads.

type NamespaceProvisioner

type NamespaceProvisioner = infracontract.NamespaceProvisioner

type NodeClient

type NodeClient interface {
	Get(ctx context.Context, name string, opts k8smetav1.GetOptions) (*corev1.Node, error)
	List(ctx context.Context, opts k8smetav1.ListOptions) (*corev1.NodeList, error)
}

NodeClient abstracts cluster-scoped Node reads used for host placement enrichment.

type Notification

type Notification = notificationcontract.Notification

Notification represents a notification message.

type NotificationProvider

type NotificationProvider = notificationcontract.NotificationProvider

NotificationProvider defines the notification interface.

type PersistentVolumeClaimClient

type PersistentVolumeClaimClient interface {
	Get(ctx context.Context, namespace, name string, opts k8smetav1.GetOptions) (*corev1.PersistentVolumeClaim, error)
}

PersistentVolumeClaimClient abstracts PVC read operations.

type PodClient

type PodClient interface {
	List(ctx context.Context, namespace string, opts k8smetav1.ListOptions) (*corev1.PodList, error)
}

PodClient abstracts namespace-scoped Pod reads used for PVC clone preflight checks.

type ScheduledDirectoryEnrichmentCapability

type ScheduledDirectoryEnrichmentCapability = directorycontract.ScheduledDirectoryEnrichmentCapability

ScheduledDirectoryEnrichmentCapability is an optional provider-owned scheduler plan.

type ScheduledDirectoryEnrichmentPlan

type ScheduledDirectoryEnrichmentPlan = directorycontract.ScheduledDirectoryEnrichmentPlan

ScheduledDirectoryEnrichmentPlan is the provider-owned plan consumed by the core scheduler.

func NormalizeScheduledDirectoryEnrichmentPlan

func NormalizeScheduledDirectoryEnrichmentPlan(
	plan *ScheduledDirectoryEnrichmentPlan,
) (*ScheduledDirectoryEnrichmentPlan, *time.Location, error)

NormalizeScheduledDirectoryEnrichmentPlan validates and defaults a provider-owned scheduled enrichment plan into the canonical core shape.

type SnapshotProvider

type SnapshotProvider = infracontract.SnapshotProvider

type StorageClassClient

type StorageClassClient interface {
	Get(ctx context.Context, name string, opts k8smetav1.GetOptions) (*storagev1.StorageClass, error)
	List(ctx context.Context, opts k8smetav1.ListOptions) (*storagev1.StorageClassList, error)
}

StorageClassClient abstracts cluster-scoped StorageClass reads.

type StorageProfileClient

type StorageProfileClient interface {
	Get(ctx context.Context, name string, opts k8smetav1.GetOptions) (*cdiv1beta1.StorageProfile, error)
}

StorageProfileClient abstracts CDI StorageProfile reads.

type VMLiveUpdateTargets

type VMLiveUpdateTargets struct {
	CPUCores        *float64
	MemoryGi        *float64
	DiskGB          *int
	CPURequest      *float64
	MemoryRequestGi *float64
}

VMLiveUpdateTargets carries the requested online resource expansions.

Scope:

  • CPU: integer total vCPU expansion only, mapped to KubeVirt socket hotplug
  • Memory: 0.5 Gi steps via memory.guest + requests/limits
  • Disk: integer Gi expansion of the root DataVolume request

type VMMutationProvider

type VMMutationProvider = infracontract.VMMutationProvider

type VMRenderInput

type VMRenderInput struct {
	Name     string
	CPUCores float64 // CPU limit in cores (0.5 step: 0.5, 1.0, 1.5, ...)
	MemoryGi float64 // Memory limit in Gi (0.5 step: 0.5, 1.0, 1.5, ...)
	DiskGB   int     // Desired root disk size for CDI-backed boot sources.
	// Image accepts one of:
	//   - container disk image reference: "quay.io/containerdisks/ubuntu:22.04"
	//   - CDI registry/http import: "import-image:<docker://...|https://...>"
	//   - CDI clone source PVC: "clone-pvc:<claim>" or "clone-pvc:<namespace>/<claim>"
	//
	// Direct existing PVC transport ("pvc:<claim>") is intentionally unsupported.
	Image        string
	StorageClass string
	CloudInit    string
	Labels       map[string]string
	// CPURequest is for overcommit: CPU request in cores (must be <= CPUCores).
	CPURequest float64
	// MemoryRequestGi is for overcommit: Memory request in Gi (must be <= MemoryGi).
	MemoryRequestGi float64
	// SpecOverrides carries advanced KubeVirt spec path/value overrides (ADR-0018 Hybrid Model).
	// Keys are dot-notation paths starting with "spec." prefix.
	// Applied as deep-merge patches after template rendering.
	SpecOverrides map[string]interface{}

	// DVAccessModes sets the DataVolume PVC access mode(s), e.g. ["ReadWriteMany"].
	// When set, the renderer uses the CDI 'pvc' format instead of 'storage' format.
	// This is an explicit field because it changes the DV YAML structure.
	DVAccessModes []string
	// DVVolumeMode sets the DataVolume PVC volume mode: "Block" or "Filesystem".
	DVVolumeMode string
}

VMRenderInput contains the fields needed to render a VM YAML template. This is a projection of domain.VMSpec with all fields needed for rendering.

Resource granularity: All CPU/Memory values must be in 0.5-step increments. Non-standard values (0.7, 1.2, etc.) are rejected at render time.

type VMResourceUpdatePlan

type VMResourceUpdatePlan struct {
	Mutation        *domain.VMMutation
	RequiresRestart bool
	ApplyMode       string
}

func PlanVMResourceUpdatePatch

func PlanVMResourceUpdatePatch(namespace string, current *domain.VM, target VMLiveUpdateTargets) (*VMResourceUpdatePlan, error)

type VNCStreamProvider

type VNCStreamProvider = infracontract.VNCStreamProvider

type VirtualMachineClient

type VirtualMachineClient interface {
	// Read operations (type-safe via kubevirt.io/client-go)
	Get(ctx context.Context, namespace, name string, opts k8smetav1.GetOptions) (*kubevirtv1.VirtualMachine, error)
	List(ctx context.Context, namespace string, opts k8smetav1.ListOptions) (*kubevirtv1.VirtualMachineList, error)
	Patch(ctx context.Context, namespace, name string, pt types.PatchType, data []byte, opts k8smetav1.PatchOptions, subresources ...string) (*kubevirtv1.VirtualMachine, error)
	// Delete remains on typed client (not SSA-related, standard K8s operation)
	Delete(ctx context.Context, namespace, name string, opts k8smetav1.DeleteOptions) error
	// Lifecycle sub-resource methods (stable across KubeVirt versions)
	Start(ctx context.Context, namespace, name string, opts *kubevirtv1.StartOptions) error
	Stop(ctx context.Context, namespace, name string, opts *kubevirtv1.StopOptions) error
	Restart(ctx context.Context, namespace, name string, opts *kubevirtv1.RestartOptions) error
}

VirtualMachineClient abstracts KubeVirt VM read operations and lifecycle commands. Anti-Corruption Layer: decouples provider from kubevirt.io/client-go/kubecli.

Create and Update are intentionally absent (ADR-0011): All writes must go through DynamicSSAClient.ApplyYAML().

type VirtualMachineInstanceClient

type VirtualMachineInstanceClient interface {
	Get(ctx context.Context, namespace, name string, opts k8smetav1.GetOptions) (*kubevirtv1.VirtualMachineInstance, error)
	List(ctx context.Context, namespace string, opts k8smetav1.ListOptions) (*kubevirtv1.VirtualMachineInstanceList, error)
	Pause(ctx context.Context, namespace, name string, opts *kubevirtv1.PauseOptions) error
	Unpause(ctx context.Context, namespace, name string, opts *kubevirtv1.UnpauseOptions) error
	VNC(namespace, name string, preserveSession bool) (net.Conn, error)
	SerialConsole(namespace, name string, connectionTimeout time.Duration) (net.Conn, error)
}

VirtualMachineInstanceClient abstracts KubeVirt VMI operations.

type WeComError

type WeComError struct {
	ErrCode int    `json:"errcode"`
	ErrMsg  string `json:"errmsg"`
}

func (WeComError) Err

func (e WeComError) Err() error

Jump to

Keyboard shortcuts

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