provider

package
v1.8.0 Latest Latest
Warning

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

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

Documentation

Overview

Package provider defines the unified interface for infrastructure operations. Each cloud provider and orchestrator (Kubernetes, Nomad, AWS ECS, Docker, Fly.io, etc.) implements the Provider interface, giving library consumers a single API for all infrastructure operations.

Index

Constants

View Source
const (
	DefaultReadinessTimeout  = 5 * time.Minute
	DefaultReadinessInterval = 5 * time.Second
)

Defaults used when a ReadinessPolicy leaves a field at zero.

View Source
const (
	ReadinessReady    = "ready"
	ReadinessFailed   = "failed"
	ReadinessTimeout  = "timeout"
	ReadinessCanceled = "canceled"
)

Readiness outcomes, as ReadinessOutcome reports them.

Variables

View Source
var ErrNotReady = errors.New("ctrlplane: workload did not become ready")

ErrNotReady is returned when a workload fails, or does not become ready before its readiness timeout, after the provider call that created or updated it returned.

View Source
var ErrProviderNotFound = errors.New("ctrlplane: provider not registered")

ErrProviderNotFound indicates the named provider is not registered.

Functions

func ContextWithCredentials added in v1.8.0

func ContextWithCredentials(ctx context.Context, creds *Credentials) context.Context

ContextWithCredentials returns a copy of ctx carrying creds. The Registry does this for you in Acquire; call it yourself only when you invoke a provider directly.

func HasCapability

func HasCapability(p Provider, capability Capability) bool

HasCapability checks whether the provider supports a given capability.

func ReadinessOutcome added in v1.8.0

func ReadinessOutcome(st *InstanceStatus, err error) string

ReadinessOutcome says how a WaitReady call that returned st and err ended: ready, failed (the provider reported StateFailed), canceled (the caller's context was cancelled) or timeout.

func TypeName added in v1.8.0

func TypeName(p Provider) string

TypeName returns p.Info().Name, the bounded name telemetry labels a provider by ("docker", "kubernetes", "nomad"), or "unknown" when p is nil or reports no name. It is not the registry key: a deployment can register one provider per cloud connection, and those keys are unbounded.

Types

type ArgoApplyRequest added in v1.5.2

type ArgoApplyRequest struct {
	InstanceID id.ID             `json:"instance_id"`
	TenantID   string            `json:"tenant_id"`
	App        ArgoCDSource      `json:"app"`
	Labels     map[string]string `json:"labels,omitempty"`
}

ArgoApplyRequest carries the rendered Argo source for one instance. The Application CR is named from the instance id and lives in the provider's configured Argo namespace.

type ArgoCDSource added in v1.5.2

type ArgoCDSource struct {
	Project        string         `json:"project,omitempty"`
	RepoURL        string         `json:"repo_url"                  validate:"required"`
	Path           string         `json:"path,omitempty"`
	TargetRevision string         `json:"target_revision,omitempty"`
	DestServer     string         `json:"dest_server,omitempty"`
	DestNamespace  string         `json:"dest_namespace,omitempty"`
	Helm           *ArgoHelm      `json:"helm,omitempty"`
	SyncPolicy     ArgoSyncPolicy `json:"sync_policy,omitzero"`
}

ArgoCDSource describes an Argo CD Application that ctrlplane manages.

type ArgoEngine added in v1.5.2

type ArgoEngine interface {
	// ArgoApply creates or updates the instance's Application resource.
	ArgoApply(ctx context.Context, req ArgoApplyRequest) (*ProvisionResult, error)

	// ArgoDelete removes the instance's Application resource.
	ArgoDelete(ctx context.Context, instanceID id.ID) error

	// ArgoStatus reports the Application's sync/health as an instance state.
	ArgoStatus(ctx context.Context, instanceID id.ID) (*InstanceStatus, error)
}

ArgoEngine is an optional provider interface for managing Argo CD Application CRs. Providers that can drive Argo CD implement it and advertise CapArgoCD; the workload dispatcher type-asserts for it when a source is SourceArgoCD.

type ArgoHelm added in v1.5.2

type ArgoHelm struct {
	ValueFiles []string          `json:"value_files,omitempty"`
	Parameters map[string]string `json:"parameters,omitempty"`
}

ArgoHelm carries Helm-specific parameters for a Helm-typed Argo Application source.

type ArgoSyncPolicy added in v1.5.2

type ArgoSyncPolicy struct {
	Automated bool `json:"automated,omitempty"`
	SelfHeal  bool `json:"self_heal,omitempty"`
	Prune     bool `json:"prune,omitempty"`
}

ArgoSyncPolicy configures how Argo CD reconciles the Application.

type Capability

type Capability string

Capability declares what a provider supports. Consumers can query capabilities before calling unsupported methods.

const (
	// CapProvision indicates the provider can create infrastructure.
	CapProvision Capability = "provision"

	// CapDeploy indicates the provider can deploy releases.
	CapDeploy Capability = "deploy"

	// CapScale indicates the provider can adjust resources.
	CapScale Capability = "scale"

	// CapLogs indicates the provider can stream logs.
	CapLogs Capability = "logs"

	// CapExec indicates the provider can execute commands in instances.
	CapExec Capability = "exec"

	// CapVolumes indicates the provider supports persistent volumes.
	CapVolumes Capability = "volumes"

	// CapGPU indicates the provider supports GPU workloads.
	CapGPU Capability = "gpu"

	// CapBlueGreen indicates the provider supports blue-green deployments.
	CapBlueGreen Capability = "strategy:blue-green"

	// CapCanary indicates the provider supports canary deployments.
	CapCanary Capability = "strategy:canary"

	// CapRolling indicates the provider supports rolling deployments.
	CapRolling Capability = "strategy:rolling"

	// CapAutoScale indicates the provider supports autoscaling.
	CapAutoScale Capability = "autoscale"

	// CapCustomDomains indicates the provider supports custom domains.
	CapCustomDomains Capability = "custom-domains"

	// CapTLS indicates the provider supports TLS termination.
	CapTLS Capability = "tls"

	// CapHelm indicates the provider can deploy a Helm chart source.
	CapHelm Capability = "source:helm"

	// CapManifests indicates the provider can apply raw/kustomize manifests.
	CapManifests Capability = "source:manifests"

	// CapArgoCD indicates the provider can manage an Argo CD Application source.
	CapArgoCD Capability = "source:argocd"
)

type ConfigFile added in v1.5.1

type ConfigFile struct {
	Name    string `db:"name"    json:"name"`    // e.g. "app-config"
	Path    string `db:"path"    json:"path"`    // mount path, e.g. "/etc/app/config.yaml"
	Format  string `db:"format"  json:"format"`  // "json", "yaml", "env", "text"
	Content string `db:"content" json:"content"` // file content (stored in vault at deploy time)
}

ConfigFile defines a configuration file (JSON/YAML/env/text) that is stored in the vault and mounted into the container at deploy time.

type Credentials added in v1.8.0

type Credentials struct {
	Values    map[string]string `json:"-"`
	Raw       any               `json:"-"`
	ExpiresAt time.Time         `json:"-"`
}

Credentials is what a provider needs to authenticate one call against its backend. Values suits flat secrets (an access key and its secret, an API token). Raw carries a provider-specific object, such as an OAuth2 token, when a flat map does not fit. Neither is ever serialized.

func CredentialsFromContext added in v1.8.0

func CredentialsFromContext(ctx context.Context) (*Credentials, bool)

CredentialsFromContext returns the credentials attached to ctx for this call. A provider that supports per-call credentials reads them here and falls back to whatever it was constructed with when ok is false, which is the case whenever no CredentialsResolver is configured.

type CredentialsResolver added in v1.8.0

type CredentialsResolver interface {
	ResolveCredentials(ctx context.Context, providerKey string) (*Credentials, error)
}

CredentialsResolver returns the credentials for the provider registered under providerKey. Ctrl Plane calls it before each provider call when you set one on the Registry, so a resolver is the place to read a vault, mint a short-lived token, or refresh one that is about to expire. Cache inside the resolver if fetching is expensive.

type CredentialsResolverFunc added in v1.8.0

type CredentialsResolverFunc func(ctx context.Context, providerKey string) (*Credentials, error)

CredentialsResolverFunc adapts a function to CredentialsResolver.

func (CredentialsResolverFunc) ResolveCredentials added in v1.8.0

func (f CredentialsResolverFunc) ResolveCredentials(ctx context.Context, providerKey string) (*Credentials, error)

ResolveCredentials implements CredentialsResolver.

type DeployRequest

type DeployRequest struct {
	InstanceID id.ID               `json:"instance_id"`
	ReleaseID  id.ID               `json:"release_id"`
	Services   []ServiceDeploySpec `json:"services"`
	Strategy   string              `json:"strategy"`
}

DeployRequest describes a deployment operation. Services lists only the services being changed in this rollout — services not listed are left at their previous version (the new Release inherits their snapshots from the prior Release).

type DeployResult

type DeployResult struct {
	ProviderRef string     `json:"provider_ref"`
	Status      string     `json:"status"`
	Endpoints   []Endpoint `json:"endpoints,omitempty"`
}

DeployResult holds the result of a deploy operation.

Endpoints is optional. Leave it nil and the instance keeps the endpoints it has. Set it when the deploy changed how the instance is reached, for example new ports, and it replaces the instance's stored endpoints in full, so list every endpoint of the instance and not only those of the services in the deploy.

type DeploymentSource added in v1.5.2

type DeploymentSource struct {
	Type      SourceType      `json:"type"                validate:"required"`
	Services  []ServiceSpec   `json:"services,omitempty"`
	Helm      *HelmSource     `json:"helm,omitempty"`
	Manifests *ManifestSource `json:"manifests,omitempty"`
	ArgoCD    *ArgoCDSource   `json:"argocd,omitempty"`
}

DeploymentSource is the typed union describing what a workload deploys. Exactly one payload field is populated, matching Type.

func (DeploymentSource) Validate added in v1.5.2

func (s DeploymentSource) Validate() error

Validate checks that Type matches a single populated payload with its required fields present. It does not deeply validate the payload (e.g. ServiceSpec invariants) — that is the owning service's responsibility.

type Endpoint

type Endpoint struct {
	ServiceName string `json:"service_name,omitempty"`
	URL         string `json:"url"`
	Port        int    `json:"port"`
	Protocol    string `json:"protocol"`
	Public      bool   `json:"public"`
}

Endpoint describes an accessible endpoint for an instance.

ServiceName names the service inside the instance that owns this endpoint — empty for legacy single-service instances. Routes can target a specific service via its name.

type ExecRequest

type ExecRequest struct {
	Command []string  `json:"command"`
	Stdin   io.Reader `json:"-"`
	TTY     bool      `json:"tty"`
}

ExecRequest describes a command to run inside an instance.

type ExecResult

type ExecResult struct {
	ExitCode int    `json:"exit_code"`
	Stdout   []byte `json:"stdout"`
	Stderr   []byte `json:"stderr"`
}

ExecResult holds the result of an exec operation.

type HealthCheckSpec

type HealthCheckSpec struct {
	Path     string        `json:"path,omitempty"`
	Port     int           `json:"port"`
	Interval time.Duration `json:"interval"`
	Timeout  time.Duration `json:"timeout"`
	Retries  int           `json:"retries"`
}

HealthCheckSpec configures health checking during deployment.

type HealthChecker added in v1.3.0

type HealthChecker interface {
	// HealthCheck tests connectivity and returns a health status.
	HealthCheck(ctx context.Context) (*HealthStatus, error)
}

HealthChecker is an optional interface that providers can implement to support health and connectivity testing from the dashboard.

type HealthStatus added in v1.3.0

type HealthStatus struct {
	Healthy   bool          `db:"healthy"    json:"healthy"`
	Message   string        `db:"message"    json:"message"`
	Latency   time.Duration `db:"latency"    json:"latency"`
	CheckedAt time.Time     `db:"checked_at" json:"checked_at"`
}

HealthStatus reports provider health after a connectivity test.

type HelmEngine added in v1.5.2

type HelmEngine interface {
	// HelmInstall installs the chart as a new release for the instance.
	HelmInstall(ctx context.Context, req HelmInstallRequest) (*ProvisionResult, error)

	// HelmUpgrade upgrades the instance's existing release.
	HelmUpgrade(ctx context.Context, req HelmUpgradeRequest) (*DeployResult, error)

	// HelmUninstall removes the instance's release.
	HelmUninstall(ctx context.Context, instanceID id.ID) error

	// HelmStatus reports the release's state.
	HelmStatus(ctx context.Context, instanceID id.ID) (*InstanceStatus, error)
}

HelmEngine is an optional provider interface for deploying Helm charts. Providers that drive the Helm SDK implement it and advertise CapHelm; the workload dispatcher type-asserts for it when a source is SourceHelm.

type HelmInstallRequest added in v1.5.2

type HelmInstallRequest struct {
	InstanceID id.ID        `json:"instance_id"`
	TenantID   string       `json:"tenant_id"`
	Namespace  string       `json:"namespace,omitempty"`
	Chart      RenderedHelm `json:"chart"`
}

HelmInstallRequest carries the rendered chart reference for a new release.

type HelmSource added in v1.5.2

type HelmSource struct {
	Repo        string         `json:"repo,omitempty"` // oci:// or https chart repo
	Chart       string         `json:"chart"                  validate:"required"`
	Version     string         `json:"version,omitempty"`
	ReleaseName string         `json:"release_name,omitempty"` // defaulted from the instance
	Namespace   string         `json:"namespace,omitempty"`
	Values      map[string]any `json:"values,omitempty"`
	ValuesFiles []string       `json:"values_files,omitempty"`
}

HelmSource describes a Helm chart to install. Values are the base values templated with variables before install; secret values are supplied at apply time and never persisted in a snapshot.

type HelmUpgradeRequest added in v1.5.2

type HelmUpgradeRequest struct {
	InstanceID id.ID        `json:"instance_id"`
	Namespace  string       `json:"namespace,omitempty"`
	Chart      RenderedHelm `json:"chart"`
}

HelmUpgradeRequest carries the rendered chart reference for upgrading an existing release.

type InstanceState

type InstanceState string

InstanceState represents the lifecycle state of an instance.

const (
	// StateProvisioning indicates the instance is being provisioned.
	StateProvisioning InstanceState = "provisioning"

	// StateStarting indicates the instance is starting up.
	StateStarting InstanceState = "starting"

	// StateRunning indicates the instance is running and healthy.
	StateRunning InstanceState = "running"

	// StateStopping indicates the instance is shutting down.
	StateStopping InstanceState = "stopping"

	// StateStopped indicates the instance is stopped.
	StateStopped InstanceState = "stopped"

	// StateFailed indicates the instance is in a failed state.
	StateFailed InstanceState = "failed"

	// StateDestroying indicates the instance is being torn down.
	StateDestroying InstanceState = "destroying"

	// StateDestroyed indicates the instance has been fully removed.
	StateDestroyed InstanceState = "destroyed"
)

type InstanceStatus

type InstanceStatus struct {
	State     InstanceState            `json:"state"`
	Ready     bool                     `json:"ready"`
	Restarts  int                      `json:"restarts"` // sum across services
	StartedAt *time.Time               `json:"started_at,omitempty"`
	Message   string                   `json:"message,omitempty"`
	Endpoints []Endpoint               `json:"endpoints"`
	Services  map[string]ServiceStatus `json:"services,omitempty"`
	Metadata  map[string]string        `json:"metadata,omitempty"`
}

InstanceStatus describes the current runtime state of an instance. State and Ready aggregate across all services (worst-of); per-service detail is in Services keyed by ServiceSpec.Name.

func WaitReady added in v1.8.0

func WaitReady(ctx context.Context, policy ReadinessPolicy, status StatusFunc) (*InstanceStatus, error)

WaitReady polls status until it reports Ready, reports StateFailed, or the policy's timeout passes. It polls once straight away. A status read that errors is retried on the next tick, since an asynchronous platform often reports "not found" for a moment after accepting a request; the last error is included if the wait times out. The returned status is the last one read, which may be nil.

Under a traced context the wait gets a "wait for instance readiness" span recording how many times it polled and how it ended.

type KustomizeSource added in v1.5.2

type KustomizeSource struct {
	Files map[string]string `json:"files"`
	Root  string            `json:"root,omitempty"`
}

KustomizeSource describes an in-memory kustomization. Files maps a relative path to its content (one entry is the kustomization.yaml). Root is the build path passed to kustomize, defaulting to the fs root.

type Location added in v1.5.1

type Location struct {
	Latitude  float64 `json:"latitude,omitempty"`
	Longitude float64 `json:"longitude,omitempty"`
	Country   string  `json:"country,omitempty"`
	City      string  `json:"city,omitempty"`
}

Location holds geographic metadata for a provider's region. Same shape as datacenter.Location but defined here so the provider package doesn't depend on datacenter — keeps the import graph pointing one way.

type LogOptions

type LogOptions struct {
	ServiceName string    `json:"service_name,omitempty"`
	Follow      bool      `json:"follow"`
	Since       time.Time `json:"since,omitzero"`
	Tail        int       `json:"tail,omitempty"`
}

LogOptions configures log streaming.

ServiceName picks one service inside the instance to stream from — empty defaults to the Main service. Single-container providers ignore this field.

type ManifestApplyRequest added in v1.5.2

type ManifestApplyRequest struct {
	InstanceID id.ID             `json:"instance_id"`
	TenantID   string            `json:"tenant_id"`
	Namespace  string            `json:"namespace,omitempty"`
	Manifests  RenderedManifests `json:"manifests"`
	Labels     map[string]string `json:"labels,omitempty"`
}

ManifestApplyRequest carries the rendered documents and metadata needed to apply a manifests source for one instance.

type ManifestEngine added in v1.5.2

type ManifestEngine interface {
	// ApplyManifests applies every rendered document, labeling each object
	// for the instance, and records what it applied so the set can later be
	// deleted or inspected.
	ApplyManifests(ctx context.Context, req ManifestApplyRequest) (*ProvisionResult, error)

	// DeleteManifests removes every object previously applied for the
	// instance. Deleting an already-absent set is not an error.
	DeleteManifests(ctx context.Context, instanceID id.ID) error

	// ManifestStatus reports the aggregate state of the applied objects.
	ManifestStatus(ctx context.Context, instanceID id.ID) (*InstanceStatus, error)
}

ManifestEngine is an optional provider interface for deploying raw or kustomize-rendered Kubernetes manifests. Providers that can apply arbitrary objects implement it and advertise CapManifests; the workload dispatcher type-asserts for it when a source is SourceManifests. Modeled as an optional interface (like HealthChecker) so providers that cannot apply manifests simply do not implement it.

type ManifestSource added in v1.5.2

type ManifestSource struct {
	Inline    string           `json:"inline,omitempty"`
	Kustomize *KustomizeSource `json:"kustomize,omitempty"`
}

ManifestSource describes raw Kubernetes manifests, either as inline multi-doc YAML or as a kustomize build. At least one is set.

type PortSpec

type PortSpec struct {
	Container int    `json:"container"`
	Host      int    `json:"host,omitempty"`
	Protocol  string `json:"protocol"`
}

PortSpec declares a port mapping for an instance.

type Provider

type Provider interface {
	// Info returns metadata about this provider.
	Info() ProviderInfo

	// Capabilities returns what this provider supports.
	Capabilities() []Capability

	// Provision creates infrastructure resources for an instance.
	Provision(ctx context.Context, req ProvisionRequest) (*ProvisionResult, error)

	// Deprovision tears down all resources for an instance.
	Deprovision(ctx context.Context, instanceID id.ID) error

	// Start starts a stopped instance.
	Start(ctx context.Context, instanceID id.ID) error

	// Stop gracefully stops a running instance.
	Stop(ctx context.Context, instanceID id.ID) error

	// Restart performs a stop+start cycle.
	Restart(ctx context.Context, instanceID id.ID) error

	// Status returns the current runtime status.
	Status(ctx context.Context, instanceID id.ID) (*InstanceStatus, error)

	// Deploy pushes a new release to the instance.
	Deploy(ctx context.Context, req DeployRequest) (*DeployResult, error)

	// Rollback reverts to a previous release.
	Rollback(ctx context.Context, instanceID id.ID, releaseID id.ID) error

	// Scale adjusts the instance's resource allocation.
	Scale(ctx context.Context, instanceID id.ID, spec ResourceSpec) error

	// Resources returns current resource utilization.
	Resources(ctx context.Context, instanceID id.ID) (*ResourceUsage, error)

	// Logs streams logs for the instance.
	Logs(ctx context.Context, instanceID id.ID, opts LogOptions) (io.ReadCloser, error)

	// Exec runs a command inside the instance.
	Exec(ctx context.Context, instanceID id.ID, cmd ExecRequest) (*ExecResult, error)
}

Provider is the unified interface for infrastructure operations. Each cloud/orchestrator (K8s, Nomad, AWS ECS, Docker, etc.) implements this.

type ProviderInfo

type ProviderInfo struct {
	Name     string    `json:"name"`
	Version  string    `json:"version"`
	Region   string    `json:"region"`
	Location *Location `json:"location,omitempty"`
}

ProviderInfo holds metadata about a provider. Location is optional — providers that don't know where they are (e.g. a generic SaaS API driver with no geographic identity) leave it nil.

type ProvisionRequest

type ProvisionRequest struct {
	InstanceID id.ID             `json:"instance_id"`
	TenantID   string            `json:"tenant_id"`
	Name       string            `json:"name"`
	Kind       WorkloadKind      `json:"kind"` // deployment | stateful_set
	Services   []ServiceSpec     `json:"services"`
	Labels     map[string]string `json:"labels,omitempty"` // workload-level, applied to all services
}

ProvisionRequest describes what resources to create for an instance. One ProvisionRequest produces one unit of co-scheduling — a k8s Pod, a Nomad TaskGroup allocation, or a Docker Compose project — containing every entry in Services.

type ProvisionResult

type ProvisionResult struct {
	// ProviderRef is the workload-level handle (Pod name on k8s,
	// Job ID on Nomad, Compose project name on Docker).
	ProviderRef string `json:"provider_ref"`

	// ServiceRefs maps a service's Name to the provider-specific
	// per-container/task ref (container ID on Docker, container name
	// within the Pod on k8s, Task name on Nomad). Used for per-service
	// log/exec/restart operations.
	ServiceRefs map[string]string `json:"service_refs,omitempty"`

	Endpoints []Endpoint        `json:"endpoints"`
	Metadata  map[string]string `json:"metadata,omitempty"`
}

ProvisionResult holds the result of a provision operation.

type ReadinessPolicy added in v1.8.0

type ReadinessPolicy struct {
	Timeout  time.Duration `json:"timeout"`
	Interval time.Duration `json:"interval"`
}

ReadinessPolicy says how long to wait for readiness and how often to poll. Zero values fall back to DefaultReadinessTimeout and DefaultReadinessInterval.

type ReadinessWaiter added in v1.8.0

type ReadinessWaiter interface {
	ReadinessPolicy() ReadinessPolicy
}

ReadinessWaiter is an optional interface for providers whose Provision and Deploy return before the workload is actually serving, which is how most managed container platforms (Cloud Run, ECS, Fly) behave. When a provider implements it, Ctrl Plane polls the provider's status after those calls and only records success once the status reports Ready. A status in StateFailed, or no readiness before the timeout, fails the instance or the deployment.

Providers that finish their work inside Provision and Deploy, like the built-in docker provider, need not implement it.

A status read that fails is retried. If the platform reports "not found" for a moment after accepting a request, wrap ctrlplane.ErrNotFound in the error: telemetry then records that read as not_found instead of a failed provider call.

type Registry

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

Registry manages named providers. Thread-safe.

func NewRegistry

func NewRegistry() *Registry

NewRegistry creates an empty provider registry.

func (*Registry) Acquire added in v1.8.0

func (r *Registry) Acquire(ctx context.Context, name string) (context.Context, Provider, error)

Acquire resolves a provider like Resolve and returns a context that carries its credentials. Pass the returned context to the provider call.

func (*Registry) All

func (r *Registry) All() map[string]Provider

All returns a snapshot of all registered providers.

func (*Registry) Default

func (r *Registry) Default() (Provider, error)

Default returns the fallback provider.

func (*Registry) DefaultName added in v1.8.0

func (r *Registry) DefaultName() string

DefaultName returns the fallback provider name, or "" when none is set.

func (*Registry) Get

func (r *Registry) Get(name string) (Provider, error)

Get retrieves a provider by registry key. See Resolve for how a name that is not a key is matched.

func (*Registry) List

func (r *Registry) List() []string

List returns all registered provider names.

func (*Registry) Register

func (r *Registry) Register(name string, p Provider)

Register adds a provider under the given name.

func (*Registry) Resolve added in v1.8.0

func (r *Registry) Resolve(name string) (string, Provider, error)

Resolve looks a provider up and returns the registry key it is held under along with the provider itself.

The key you passed to Register is matched first. When nothing is registered under name, Resolve falls back to the provider whose Info().Name equals name, as long as exactly one does. That keeps rows written before instances recorded registry keys resolvable: those rows hold Info().Name, and for most providers the key and the name are the same string anyway.

func (*Registry) ResolveDefault added in v1.8.0

func (r *Registry) ResolveDefault() (string, Provider, error)

ResolveDefault returns the fallback provider and the registry key it is held under.

func (*Registry) SetCredentialsResolver added in v1.8.0

func (r *Registry) SetCredentialsResolver(res CredentialsResolver)

SetCredentialsResolver makes the registry fetch credentials for a provider before each call made through Acquire or WithCredentials. Pass nil to turn it off. Providers that never read CredentialsFromContext are unaffected either way.

func (*Registry) SetDefault

func (r *Registry) SetDefault(name string)

SetDefault sets the fallback provider name.

func (*Registry) SetMetrics added in v1.8.0

func (r *Registry) SetMetrics(m gometrics.Metrics)

SetMetrics times every credentials resolver call on m. A nil m records nothing. In a Forge app the ctrlplane extension passes app.Metrics() in for you.

func (*Registry) WithCredentials added in v1.8.0

func (r *Registry) WithCredentials(ctx context.Context, key string) (context.Context, error)

WithCredentials attaches the credentials for the provider registered under key to ctx. Without a resolver it returns ctx unchanged.

type RenderedHelm added in v1.5.2

type RenderedHelm struct {
	Repo        string         `json:"repo,omitempty"`
	Chart       string         `json:"chart"`
	Version     string         `json:"version,omitempty"`
	ReleaseName string         `json:"release_name,omitempty"`
	Namespace   string         `json:"namespace,omitempty"`
	Values      map[string]any `json:"values,omitempty"`
}

RenderedHelm is a Helm chart reference with its values fully resolved.

type RenderedManifests added in v1.5.2

type RenderedManifests struct {
	Docs []string `json:"docs"`
}

RenderedManifests holds concrete Kubernetes YAML documents — the output of templating inline YAML or running a kustomize build. Each Docs entry is exactly one YAML document.

type RenderedSource added in v1.5.2

type RenderedSource struct {
	Type      SourceType         `json:"type"`
	Services  []ServiceSpec      `json:"services,omitempty"`
	Helm      *RenderedHelm      `json:"helm,omitempty"`
	Manifests *RenderedManifests `json:"manifests,omitempty"`
	ArgoCD    *ArgoCDSource      `json:"argocd,omitempty"` // templated in place
}

RenderedSource is the fully-resolved deployment source a provider applies. It is produced by the render package from a DeploymentSource plus a resolved variable scope; the provider never sees raw templates or the variable layer. Secret values are never embedded here — they travel separately as SecretBindings and are materialized at apply time.

type ResourceSpec

type ResourceSpec struct {
	CPUMillis int    `json:"cpu_millis"`
	MemoryMB  int    `json:"memory_mb"`
	DiskMB    int    `json:"disk_mb,omitempty"`
	Replicas  int    `json:"replicas"`
	GPU       string `json:"gpu,omitempty"`
}

ResourceSpec declares desired resources for an instance.

type ResourceUsage

type ResourceUsage struct {
	CPUPercent    float64 `json:"cpu_percent"`
	MemoryUsedMB  int     `json:"memory_used_mb"`
	MemoryLimitMB int     `json:"memory_limit_mb"`
	DiskUsedMB    int     `json:"disk_used_mb,omitempty"`
	NetworkInMB   float64 `json:"network_in_mb"`
	NetworkOutMB  float64 `json:"network_out_mb"`
}

ResourceUsage reports actual resource utilization.

type SecretBinding added in v1.5.2

type SecretBinding struct {
	// VarName is the logical variable name the binding was resolved from.
	VarName string `json:"var_name"`

	// EnvKey is the environment-variable name the workload sees. Defaults
	// to UPPER_SNAKE(VarName) when the variable does not specify one.
	EnvKey string `json:"env_key"`

	// Ref locates the secret value in the vault, resolved at apply time.
	Ref SecretRef `json:"ref"`
}

SecretBinding is a resolved secret-typed variable. The provider materializes it as a native Secret and wires it via valueFrom/envFrom; the plaintext value is never carried in this struct, the render output, or any persisted snapshot. Lives in the provider package alongside SecretRef so vars and render can reference it without a provider → vars import edge.

type SecretRef added in v1.5.1

type SecretRef struct {
	Key  string             `db:"key"  json:"key"`
	Type secrets.SecretType `db:"type" json:"type"`
}

SecretRef is a lightweight reference to a secret needed at deploy time. The secret value itself is fetched from the vault by Key when a Workload is deployed; specs only carry the reference, never the value.

Lives in the provider package so ServiceSpec can embed it without creating a template ↔ provider import cycle.

type ServiceDeploySpec added in v1.5.1

type ServiceDeploySpec struct {
	Name        string            `json:"name"                   validate:"required"`
	Image       string            `json:"image"                  validate:"required"`
	Env         map[string]string `json:"env,omitempty"`
	HealthCheck *HealthCheckSpec  `json:"health_check,omitempty"`

	// Command and Args override the image's ENTRYPOINT and CMD.
	Command []string `json:"command,omitempty"`
	Args    []string `json:"args,omitempty"`

	// Ports replaces the ports the service listens on.
	Ports []PortSpec `json:"ports,omitempty"`

	// Resources replaces the service's CPU, memory and replica size.
	Resources *ResourceSpec `json:"resources,omitempty"`
}

ServiceDeploySpec is a per-service slice of a Deploy operation. A Deploy carries Services []ServiceDeploySpec — partial deploys leave services not listed here untouched.

Command, Args, Ports and Resources are optional. Leave one nil and the provider keeps what the service already runs with; set it and the provider should apply it with the new image. Providers that cannot change a field on deploy may ignore it.

func (ServiceDeploySpec) Snapshot added in v1.8.0

Snapshot returns the Release snapshot this deploy spec produces when applied on top of prior, the service's snapshot from the previous Release. Pass nil when there is none. Optional fields left unset on the spec keep their value from prior.

type ServiceRole added in v1.5.1

type ServiceRole string

ServiceRole categorises a service inside a Workload by lifecycle.

  • RoleMain: long-lived process; the workload's primary container. Every workload must have exactly one Main service. Workload health defaults to the Main service's readiness.
  • RoleSidecar: long-lived process that runs alongside Main inside the same co-scheduling unit (k8s Pod, Nomad TaskGroup, Docker Compose project). Examples: log-forwarding agent, envoy proxy, metrics shipper. Started after Main in dependency order.
  • RoleInit: run-once before Main and Sidecars start. The Main/Sidecars do not start until every Init has exited successfully. An Init failure marks the Instance as Failed.
const (
	RoleMain    ServiceRole = "main"
	RoleSidecar ServiceRole = "sidecar"
	RoleInit    ServiceRole = "init"
)

type ServiceSnapshot added in v1.5.1

type ServiceSnapshot struct {
	Name      string            `json:"name"`
	Image     string            `json:"image"`
	Env       map[string]string `json:"env,omitempty"`
	Command   []string          `json:"command,omitempty"`
	Args      []string          `json:"args,omitempty"`
	Ports     []PortSpec        `json:"ports,omitempty"`
	Resources *ResourceSpec     `json:"resources,omitempty"`
}

ServiceSnapshot is the per-service slice of a Release. Releases are always self-contained — partial deploys produce a new Release whose non-targeted services are inherited from the prior Release.

Command, Args, Ports and Resources are recorded when a deploy set them, or carried over from the previous Release when it did not, so a rollback restores them too.

func SnapshotOf added in v1.8.0

func SnapshotOf(svc ServiceSpec) ServiceSnapshot

SnapshotOf records a provisioned service as a Release snapshot. A zero ResourceSpec is left out, so restoring the snapshot never asks a provider to size a service down to nothing.

func (ServiceSnapshot) DeploySpec added in v1.8.0

func (s ServiceSnapshot) DeploySpec() ServiceDeploySpec

DeploySpec returns the deploy spec that restores this snapshot, as a rollback does.

type ServiceSpec added in v1.5.1

type ServiceSpec struct {
	// Name is the service's identifier within the workload. Must be
	// unique among the workload's services and DNS-safe (lowercase
	// alphanumerics + hyphens) so providers can use it as a network
	// alias for service-to-service discovery.
	Name string `json:"name" validate:"required"`

	// Image is the container image reference, e.g. "nginx:1.25".
	Image string `json:"image" validate:"required"`

	// Role determines lifecycle (Main / Sidecar / Init). Defaults to
	// Main when empty; validation enforces exactly one Main per workload.
	Role ServiceRole `json:"role,omitempty"`

	// DependsOn lists service names that must reach Running before this
	// service starts. Used for ordering Sidecars relative to Main and
	// for chaining Inits. A cycle is a validation error.
	DependsOn []string `json:"depends_on,omitempty"`

	// Resources / Env / Ports / Volumes / HealthCheck are per-service.
	// Two services in the same workload can request different CPU/memory
	// or expose different ports.
	Resources   ResourceSpec      `json:"resources"`
	Env         map[string]string `json:"env,omitempty"`
	Ports       []PortSpec        `json:"ports,omitempty"`
	Volumes     []VolumeSpec      `json:"volumes,omitempty"`
	HealthCheck *HealthCheckSpec  `json:"health_check,omitempty"`

	// Secrets references env-injected secrets resolved against the
	// vault at deploy time. Per-service so a sidecar can have its own
	// credentials without leaking them to the main container.
	Secrets []SecretRef `json:"secrets,omitempty"`

	// ConfigFiles describes vault-backed files mounted into this
	// service's filesystem at deploy time.
	ConfigFiles []ConfigFile `json:"config_files,omitempty"`

	// Annotations is per-service free-form metadata (e.g. k8s
	// container annotations). Workload-level metadata lives on the
	// Workload's Labels map.
	Annotations map[string]string `json:"annotations,omitempty"`

	// Command and Args optionally override the container image's
	// ENTRYPOINT and CMD respectively. Empty leaves the image
	// defaults in place.
	Command []string `json:"command,omitempty"`
	Args    []string `json:"args,omitempty"`
}

ServiceSpec is the per-service slice of a Workload's spec. A Workload is `Services []ServiceSpec` plus workload-level fields (Replicas, Kind, Labels). Each entry produces one container/task within the replica's co-scheduling unit.

SecretRef and ConfigFile are spec-level descriptors of vault-backed data the provider mounts at provision time; they live in this package (rather than template/) so this struct can embed them without a cycle.

type ServiceStatus added in v1.5.1

type ServiceStatus struct {
	State       InstanceState `json:"state"`
	Ready       bool          `json:"ready"`
	Restarts    int           `json:"restarts"`
	ProviderRef string        `json:"provider_ref,omitempty"`
	Message     string        `json:"message,omitempty"`
}

ServiceStatus is the per-service runtime state reported back from the provider. InstanceStatus.Services map keys these by ServiceSpec.Name.

type SourceType added in v1.5.2

type SourceType string

SourceType identifies which kind of deployment a DeploymentSource describes. Exactly one of the DeploymentSource payload fields is set, matching the Type.

const (
	// SourceServices deploys container services (the ServiceSpec model).
	SourceServices SourceType = "services"

	// SourceHelm deploys a Helm chart.
	SourceHelm SourceType = "helm"

	// SourceManifests deploys raw multi-doc YAML and/or a kustomize build.
	SourceManifests SourceType = "manifests"

	// SourceArgoCD delegates deployment to Argo CD via an Application CR.
	SourceArgoCD SourceType = "argocd"
)

type StatusFunc added in v1.8.0

type StatusFunc func(ctx context.Context) (*InstanceStatus, error)

StatusFunc reads the current status of the workload being waited on.

type VolumeSpec

type VolumeSpec struct {
	Name      string `json:"name"`
	MountPath string `json:"mount_path"`
	SizeMB    int    `json:"size_mb"`
	Type      string `json:"type"`
}

VolumeSpec declares a volume mount for an instance.

type WorkloadKind added in v1.5.1

type WorkloadKind string

WorkloadKind picks the runtime topology a workload deploys as.

  • KindDeployment: stateless replicas. On Kubernetes this becomes a Deployment; on Nomad a Job/TaskGroup; on Docker N independent Compose projects. Volumes are shared/ephemeral by default.
  • KindStatefulSet: replicas with stable per-replica identity and storage. On Kubernetes this becomes a StatefulSet + headless Service with volumeClaimTemplates; on Docker per-replica named volumes give equivalent semantics.
const (
	KindDeployment  WorkloadKind = "deployment"
	KindStatefulSet WorkloadKind = "stateful_set"
)

Directories

Path Synopsis
Package docker is a Docker-backed provider.Provider.
Package docker is a Docker-backed provider.Provider.
Package kubernetes implements a Kubernetes-based infrastructure provider for the ctrlplane.
Package kubernetes implements a Kubernetes-based infrastructure provider for the ctrlplane.
Package nomad is a HashiCorp Nomad-backed provider.Provider.
Package nomad is a HashiCorp Nomad-backed provider.Provider.

Jump to

Keyboard shortcuts

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