lifecycle

package
v5.20.1 Latest Latest
Warning

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

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

Documentation

Overview

Package lifecycle provides cluster lifecycle command helpers.

This package contains utilities for building and executing standard cluster lifecycle commands (start, stop, delete, etc.) with consistent messaging, timing, and error handling patterns.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNoCurrentContext indicates no current context is set in kubeconfig.
	ErrNoCurrentContext = errors.New("no current context set in kubeconfig")

	// ErrContextNotFound indicates the specified context was not found in kubeconfig.
	ErrContextNotFound = errors.New("context not found in kubeconfig")

	// ErrClusterNotFound indicates the cluster referenced by the context was not found.
	ErrClusterNotFound = errors.New("cluster not found in kubeconfig")

	// ErrUnknownContextPattern indicates the context name doesn't match any known distribution pattern.
	ErrUnknownContextPattern = errors.New(
		"unknown distribution: context does not match kind-, k3d-, or admin@ pattern",
	)

	// ErrEmptyClusterName is returned when cluster name detection results in an empty string.
	// This happens with malformed contexts like "kind-", "k3d-", or "admin@".
	ErrEmptyClusterName = errors.New("empty cluster name detected from context")

	// ErrUnableToDetectProvider indicates the provider could not be determined from the server endpoint.
	ErrUnableToDetectProvider = errors.New("unable to detect provider from server endpoint")

	// ErrNoCloudCredentials indicates no cloud provider credentials were found for a public IP.
	ErrNoCloudCredentials = errors.New("public IP detected but no cloud provider credentials found")

	// ErrNoHostInURL indicates a URL was parsed but contained no host component.
	ErrNoHostInURL = errors.New("no host found in URL")
)

Detection errors.

View Source
var (
	// ErrClusterNameRequired indicates that a cluster name is required but was not provided.
	ErrClusterNameRequired = errors.New(
		"cluster name is required: use --name flag, create a ksail.yaml config, or set a kubeconfig context",
	)

	// ErrClusterNotFoundInDistributions indicates the cluster was not found in any distribution.
	ErrClusterNotFoundInDistributions = errors.New("cluster not found in any distribution")

	// ErrCreateNotSupported indicates create is not supported without specifying distribution.
	ErrCreateNotSupported = errors.New("create not supported without specifying distribution")

	// ErrUnknownDistribution indicates an unknown distribution was specified.
	ErrUnknownDistribution = errors.New("unknown distribution")

	// ErrUnsupportedDistribution indicates an unsupported distribution was specified.
	ErrUnsupportedDistribution = errors.New("unsupported distribution")
)

Lifecycle errors.

View Source
var ErrClusterConfigRequired = errors.New("cluster configuration is required")

ErrClusterConfigRequired indicates that a nil cluster configuration was provided.

View Source
var ErrMissingClusterProvisionerDependency = errors.New("missing cluster provisioner dependency")

ErrMissingClusterProvisionerDependency indicates that a lifecycle command resolved a nil provisioner.

Functions

func CreateMinimalProvisioner added in v5.13.0

func CreateMinimalProvisioner(
	info *ClusterInfo,
) (clusterprovisioner.ClusterProvisioner, error)

CreateMinimalProvisioner creates a minimal provisioner for lifecycle operations. These provisioners only need enough configuration to identify containers. It uses the detected ClusterInfo to create the appropriate provisioner with the correct provider configuration.

func CreateMinimalProvisionerForProvider added in v5.19.0

func CreateMinimalProvisionerForProvider(
	info *ClusterInfo,
) (clusterprovisioner.ClusterProvisioner, error)

CreateMinimalProvisionerForProvider creates provisioners for all distributions that support the given provider, and returns the first one that can operate on the cluster. This is used when we only have --name and --provider flags without distribution info.

func DetectDistributionFromContext added in v5.13.0

func DetectDistributionFromContext(contextName string) (v1alpha1.Distribution, string, error)

DetectDistributionFromContext detects the Kubernetes distribution and cluster name from the kubeconfig context name pattern. Returns the distribution, cluster name, and any error.

Context name patterns:

  • kind-<cluster-name> → Vanilla (Kind)
  • k3d-<cluster-name> → K3s (K3d)
  • admin@<cluster-name> → Talos

Returns an error if the pattern is unrecognized or if the extracted cluster name is empty.

func ExtractClusterNameFromContext

func ExtractClusterNameFromContext(context string, distribution v1alpha1.Distribution) string

ExtractClusterNameFromContext extracts the cluster name from a context string. For kind clusters, contexts follow the pattern "kind-<cluster-name>". For k3d clusters, contexts follow the pattern "k3d-<cluster-name>". Returns empty string if the context doesn't match the expected pattern.

func GetClusterNameFromConfig

func GetClusterNameFromConfig(
	clusterCfg *v1alpha1.Cluster,
	factory clusterprovisioner.Factory,
) (string, error)

GetClusterNameFromConfig extracts the cluster name from the KSail cluster configuration. When a context is explicitly set, it derives the cluster name from it. Otherwise, it loads the distribution config and extracts the name from there. This function is exported for use in command handlers that need the cluster name for operations beyond the standard lifecycle actions.

func GetCurrentKubeContext added in v5.16.0

func GetCurrentKubeContext() (string, error)

GetCurrentKubeContext reads the current context from the default kubeconfig. This is exported for use by other commands that need context-based auto-detection.

func HandleRunE

func HandleRunE(
	cmd *cobra.Command,
	cfgManager *ksailconfigmanager.ConfigManager,
	deps Deps,
	config Config,
) error

HandleRunE orchestrates the standard lifecycle workflow. It performs the following steps in order:

  1. Create a new timer stage (config was already loaded in WrapHandler)
  2. Execute the lifecycle action via RunWithConfig

Note: The cluster configuration is already loaded by WrapHandler, so this function uses the cached config from cfgManager.Config.

func NewSimpleLifecycleCmd added in v5.13.0

func NewSimpleLifecycleCmd(config SimpleLifecycleConfig) *cobra.Command

NewSimpleLifecycleCmd creates a simple lifecycle command (start/stop) with --name and --provider flags. The cluster is resolved in the following priority order:

  1. From --name flag (required if no config or context available)
  2. From ksail.yaml config file (if present)
  3. From current kubeconfig context (if detectable)

The provider is resolved in the following priority order:

  1. From --provider flag
  2. From ksail.yaml config file (if present)
  3. Defaults to Docker

func NewStandardRunE

func NewStandardRunE(
	runtimeContainer *runtime.Runtime,
	cfgManager *ksailconfigmanager.ConfigManager,
	config Config,
) func(*cobra.Command, []string) error

NewStandardRunE creates a standard RunE handler for simple lifecycle commands. It handles dependency injection from the runtime container and delegates to HandleRunE with the provided lifecycle configuration.

This is the recommended way to create lifecycle command handlers for standard operations like start, stop, and delete. The returned function can be assigned directly to a cobra.Command's RunE field.

func RunWithConfig

func RunWithConfig(
	cmd *cobra.Command,
	deps Deps,
	config Config,
	clusterCfg *v1alpha1.Cluster,
) error

RunWithConfig executes a lifecycle command using a pre-loaded cluster configuration. This function is useful when the cluster configuration has already been loaded, avoiding the need to reload it.

It performs the following steps:

  1. Create the cluster provisioner using the factory
  2. Extract the cluster name from the distribution config or context
  3. Execute the lifecycle action
  4. Display success message with timing information

Returns an error if provisioner creation, cluster name extraction, or the action itself fails.

func WrapHandler

func WrapHandler(
	runtimeContainer *runtime.Runtime,
	cfgManager *ksailconfigmanager.ConfigManager,
	handler func(*cobra.Command, *ksailconfigmanager.ConfigManager, Deps) error,
) func(*cobra.Command, []string) error

WrapHandler resolves lifecycle dependencies from the runtime container and invokes the provided handler function with those dependencies.

This function loads the cluster configuration first, then creates a factory using the cached distribution config from the config manager. This ensures the factory has the proper distribution-specific configuration.

The output is wrapped with StageSeparatingWriter to automatically add blank lines between CLI stages for better readability.

This function is used internally by NewStandardRunE but can also be used directly for custom lifecycle handlers that need dependency injection but require custom logic beyond the standard HandleRunE flow.

Types

type Action

type Action func(
	ctx context.Context,
	provisioner clusterprovisioner.ClusterProvisioner,
	clusterName string,
) error

Action represents a lifecycle operation executed against a cluster provisioner. The action receives a context for cancellation, the provisioner instance, and the cluster name. It returns an error if the lifecycle operation fails.

type ClusterInfo added in v5.19.0

type ClusterInfo struct {
	Distribution   v1alpha1.Distribution
	Provider       v1alpha1.Provider
	ClusterName    string
	ServerURL      string
	KubeconfigPath string
}

ClusterInfo contains the detected distribution and provider for a cluster.

func DetectClusterInfo added in v5.19.0

func DetectClusterInfo(kubeconfigPath, contextName string) (*ClusterInfo, error)

DetectClusterInfo detects the distribution and provider from the kubeconfig context. It reads the kubeconfig, determines the distribution from the context name pattern, and detects the provider by analyzing the server endpoint.

type Config

type Config struct {
	TitleEmoji         string
	TitleContent       string
	ActivityContent    string
	SuccessContent     string
	ErrorMessagePrefix string
	Action             Action
}

Config describes the messaging and action behavior for a lifecycle command. It configures the user-facing messages displayed during command execution and specifies the action to perform on the cluster provisioner.

type Deps

type Deps struct {
	Timer   timer.Timer
	Factory clusterprovisioner.Factory
}

Deps groups the injectable collaborators required by lifecycle commands.

type ResolvedClusterInfo added in v5.19.0

type ResolvedClusterInfo struct {
	ClusterName    string
	Provider       v1alpha1.Provider
	KubeconfigPath string
}

ResolvedClusterInfo contains the resolved cluster name, provider, and kubeconfig path.

func ResolveClusterInfo added in v5.19.0

func ResolveClusterInfo(
	nameFlag string,
	providerFlag v1alpha1.Provider,
	kubeconfigFlag string,
) (*ResolvedClusterInfo, error)

ResolveClusterInfo resolves the cluster name, provider, and kubeconfig from flags, config, or kubeconfig. Priority for cluster name: flag > config > kubeconfig context. Priority for provider: flag > config > default (Docker). Priority for kubeconfig: flag > env (KUBECONFIG) > config > default (~/.kube/config).

type SimpleLifecycleConfig added in v5.13.0

type SimpleLifecycleConfig struct {
	Use          string
	Short        string
	Long         string
	TitleEmoji   string
	TitleContent string
	Activity     string
	Success      string
	Action       func(
		ctx context.Context,
		provisioner clusterprovisioner.ClusterProvisioner,
		clusterName string,
	) error
}

SimpleLifecycleConfig defines the configuration for a simple lifecycle command. Simple lifecycle commands auto-detect the cluster from the kubeconfig context and don't require a ksail.yaml configuration file.

Jump to

Keyboard shortcuts

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