runtime

package
v0.8.0 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2026 License: MIT Imports: 14 Imported by: 0

Documentation

Overview

Package runtime abstracts where donkey runs apps. A Provider owns one runtime's vocabulary — Kubernetes namespaces and Deployments, Docker networks and containers — and exposes only donkey's verbs. The control plane orchestrates the runtime-neutral flow and never sees underneath.

Index

Constants

View Source
const (
	// MetaConsole is written by the console endpoints only — a deploy must
	// never wipe it.
	MetaConsole = "donkey.local/console"
	// MetaDecisions is what deploy-time analysis settled.
	MetaDecisions = "donkey.local/decisions"
)

App metadata keys, stored with the deployed app and surviving deploys. On Kubernetes they are Deployment annotations (the manifests package spells MetaConsole and MetaDecisions as AnnotationConsole/AnnotationDecisions — keep them equal); on Docker they are entries in the app's meta file.

Variables

View Source
var (
	ErrNoDisk      = errors.New("this app has no disk — add storage.paths to donkey.yaml and deploy again to give it one")
	ErrNotDeployed = errors.New("nothing with this name is deployed — deploy the app first")
	ErrBadPath     = errors.New("that path isn't allowed")
	ErrNotFound    = errors.New("there is nothing at that path on the disk")
	ErrNotAFile    = errors.New("that is a folder, not a file")
	ErrNotAFolder  = errors.New("that is a file, not a folder")
)

File-browser errors, shared so handlers can map them to honest statuses.

View Source
var ErrPlatformNotFound = errors.New("platform settings have not been initialized")
View Source
var ErrSpaceNotFound = errors.New("the space does not exist")
View Source
var MaxListEntries = 2000

File-browser page size, shared by every provider.

Functions

func CheckAppDomain

func CheckAppDomain(ctx context.Context, provider spaceConfigReader, app *config.AppConfig, space, domain string) error

func CheckServiceAttachment

func CheckServiceAttachment(ctx context.Context, r serviceAccessReader, common config.CommonOfferings, space, app, name string) error

CheckServiceAttachment allows current attachments to keep running but prevents new consumers from bypassing the space catalog through a binding.

func CheckSpaceDomains

func CheckSpaceDomains(ctx context.Context, provider spaceConfigReader, space string, hosts ...string) error

CheckSpaceDomains checks actual hostnames after the space has been created, including addresses inherited from shared-address routes.

func OfferingPolicy

func OfferingPolicy(ctx context.Context, r spaceConfigReader, space string) (config.SpaceConfig, error)

func PrepareService

func PrepareService(ctx context.Context, r spaceConfigReader, common config.CommonOfferings, space string, desc *addonv1.Offering, given map[string]any, existing bool) (map[string]any, error)

PrepareService applies space defaults only at creation. Saved values win on subsequent requests, and existing instances retain their lifecycle even when their offering is removed from the space's catalog.

func ReconcileAccess

func ReconcileAccess(ctx context.Context, provider Provider, target string) error

ReconcileAccess moves saved app users/groups into space viewers and removes the old lists. It also closes all public routes in spaces that disallow them. Membership is saved before old entries are removed, making retries safe. An empty target reconciles every space at server startup.

func SpaceConfiguration

func SpaceConfiguration(ctx context.Context, r spaceConfigReader, space string, desc *addonv1.Offering, previous *addons.Provisioning) (addons.Parameters, error)

Types

type AppRef

type AppRef struct {
	Space string
	App   string
}

type AppStatus

type AppStatus struct {
	Found        bool
	Image        string
	ReadyReplica int32
	WantReplica  int32
	// UpToDate: the observed state belongs to the latest generation. Without
	// it an old healthy instance makes a failing rollout look green.
	UpToDate bool
	// Instances are the app's running units, by name.
	Instances []string
	// PublicHost is the hostname the app serves on; empty for internal.
	PublicHost string
	// Protected says traffic reaches the app through the login gateway.
	Protected bool
	// Mode is web or api at the gateway.
	Mode string
	// CORS is the gateway's cross-origin policy; empty disables it.
	CORS string
	// Stack is what the app is written in, as its last deploy recorded it.
	Stack string
	// Security is the vulnerability scan's outcome for the running image,
	// as its deploy recorded it (opaque JSON the control plane reads).
	Security string
	// Port the app listens on (donkey.yaml's `port`).
	Port int32
	// Restarts sums restarts across instances — what separates "quietly
	// struggling" from "running".
	Restarts int32
	// StartedAt is when the newest instance came up.
	StartedAt time.Time
}

AppStatus is a snapshot of an app's health.

func (*AppStatus) Healthy

func (s *AppStatus) Healthy() bool

func (*AppStatus) ReadyText

func (s *AppStatus) ReadyText() string

type AppSummary

type AppSummary struct {
	AppRef
	Status     AppStatus
	HasStorage bool
	Addons     []string
}

type AppSummaryProvider

type AppSummaryProvider interface {
	AppSummaries(ctx context.Context) ([]AppSummary, error)
	// InvalidateAppSummaries makes completed writes visible on the next read.
	InvalidateAppSummaries()
}

AppSummaryProvider batches the overview's status, storage and service reads. Implementations may briefly cache these display values; the server always resolves management permissions separately against current space settings.

type CertificateStatus

type CertificateStatus struct {
	State       EndpointState
	Mode        string
	Issuer      string
	Reason      string
	Message     string
	ExpiresAt   time.Time
	RenewalTime time.Time
	// Renewing means a usable current certificate remains ready while its
	// replacement is being issued.
	Renewing bool
}

type Check

type Check struct {
	Name   string
	OK     bool
	Detail string
}

type DNSStatus

type DNSStatus struct {
	State      EndpointState
	Observed   bool
	RecordType string
	Expected   []string
	Message    string
}

type DeploySpec

type DeploySpec struct {
	// Hosts are reviewed sibling addresses, including apps not deployed yet.
	Hosts    map[string]string
	App      *config.AppConfig
	Space    string
	ImageRef string
	// Decisions records what this deploy settled (storage, health route), so
	// a no-build deploy keeps the same shape.
	Decisions string
	// Security is the vulnerability scan's outcome for the image (opaque
	// JSON), kept with the workload so listings show it without opening
	// the release.
	Security string
	// Stack is what the app is written in, read off its recipe (see
	// detect.Stack); "" when no base image says.
	Stack string
	// NoWait skips waiting for the app to become healthy.
	NoWait bool
}

DeploySpec is everything Deploy and Render need.

type EndpointState

type EndpointState string

EndpointState is the small common vocabulary the control plane and console use for asynchronous edge setup.

const (
	EndpointReady       EndpointState = "ready"
	EndpointIssuing     EndpointState = "issuing"
	EndpointPropagating EndpointState = "propagating"
	EndpointError       EndpointState = "error"
	EndpointUnknown     EndpointState = "unknown"
	EndpointUnmanaged   EndpointState = "unmanaged"
)

type EndpointStatus

type EndpointStatus struct {
	Certificate CertificateStatus
	DNS         DNSStatus
}

EndpointStatus describes whether an exposed hostname is ready beyond the workload itself. Certificate and DNS are deliberately independent: DNS can resolve while a certificate is still issuing, and vice versa.

type EndpointStatusProvider

type EndpointStatusProvider interface {
	// EndpointStatus receives the hostname read from the runtime's live route,
	// never stored deploy intent. Individual check failures are represented as
	// an unknown/error state so a DNS timeout cannot hide otherwise useful app
	// status.
	EndpointStatus(ctx context.Context, space, app, host string) EndpointStatus
}

EndpointStatusProvider is an optional runtime capability for the slower, edge-specific checks shown on one app's detail page. Keeping it separate from Provider.Status matters: the fleet view reads Status for every app, whereas certificate objects and live DNS answers only need checking for the app somebody is looking at.

type Evidence

type Evidence struct {
	// Summaries describe the app's instances, one line each.
	Summaries []string
	// Events are the runtime's warnings about them.
	Events []string
	// Logs are the last lines from the most broken instance.
	Logs string
}

Evidence is what donkey collects when an app is unhealthy.

type FileEntry

type FileEntry struct {
	Name string
	Size int64
	// Mode is the ls-style spelling, e.g. "-rw-rw-r--".
	Mode    string
	ModTime time.Time
	IsDir   bool
	// IsLink: neither downloadable nor openable — callers must offer neither.
	IsLink bool
}

type GatewayBackend

type GatewayBackend interface {
	GatewayRouteSource
	GatewayTLSStore
}

GatewayBackend is deliberately smaller than Provider: the edge needs a read-only route source and TLS persistence, not app deployment privileges.

type GatewayCertificate

type GatewayCertificate struct {
	Name                    string
	Certificate, PrivateKey []byte
}

type GatewayCertificateSource

type GatewayCertificateSource interface {
	GatewayCertificates(context.Context) ([]GatewayCertificate, error)
}

GatewayCertificateSource is optional: runtimes with externally managed certificates implement it; the gateway rejects that TLS mode otherwise.

type GatewayRouteSource

type GatewayRouteSource interface {
	GatewaySnapshot(context.Context) (GatewaySnapshot, error)
}

type GatewaySnapshot

type GatewaySnapshot struct {
	Routes   []config.GatewayRoute
	Spaces   map[string]config.SpaceConfig
	Platform config.PlatformConfig
}

GatewaySnapshot is a coherent route and membership view. Runtime object names, ownership labels and serialization stay in the runtime adapter.

type GatewayTLSStore

type GatewayTLSStore interface {
	// PrepareGateway performs startup-only migration of existing TLS state.
	PrepareGateway(context.Context) error
	GatewayCertificateCache() autocert.Cache
	// GatewayCA returns the saved CA, atomically initializing it if absent.
	GatewayCA(context.Context, func() ([]byte, []byte, error)) ([]byte, []byte, error)
}

type LogOptions

type LogOptions struct {
	// Component selects which part of the app: "web" or "addon-<name>".
	Component string
	Follow    bool
	TailLines int64
	Since     time.Duration
}

type NetworkState

type NetworkState struct {
	// RouteFound: the app has an address of its own (not internal).
	RouteFound bool
	Host       string
	Protected  bool
	Mode       string
	CORS       string
	OIDC       *config.OIDCClient
	// Analytics is config.AnalyticsOff when the app opted out of web
	// analytics.
	Analytics string
	// Access is legacy membership read only during startup migration.
	Access *config.AccessConfig
	Routes []PathRouteState
}

NetworkState is how an app is reached, read from actual state.

type PathRouteState

type PathRouteState struct {
	Name        string
	Host        string
	Path        string
	StripPrefix bool
	// Protected says the route sends its traffic through the login gateway.
	Protected bool
	Mode      string
	CORS      string
	// Access is read only to migrate legacy app membership.
	Access *config.AccessConfig
}

PathRouteState is one shared-address route as it exists in the runtime.

type Progress

type Progress interface {
	Line(format string, a ...any)
}

Progress narrates long operations back to the user, line by line.

type Provider

type Provider interface {
	// Concurrent first sign-ins return the configuration that won initialization.
	PlatformConfig(ctx context.Context) (config.PlatformConfig, error)
	InitPlatformConfig(ctx context.Context, initial config.PlatformConfig) (config.PlatformConfig, error)
	SetPlatformConfig(ctx context.Context, settings config.PlatformConfig) error

	// ValidateSpace is pure — no I/O, callable on every request.
	ValidateSpace(space string) error
	// CheckSpaceFree refuses a space whose place in the runtime exists but
	// isn't donkey's, so a name can never take over (or later delete) someone
	// else's namespace or network.
	CheckSpaceFree(ctx context.Context, space string) error
	ListSpaces(ctx context.Context) ([]string, error)
	// EnsureSpaceConfigs migrates existing spaces without changing saved roles or domains.
	EnsureSpaceConfigs(ctx context.Context) error
	CreateSpace(ctx context.Context, space string) error
	// SpaceConfig keeps membership and public-access policy on the space. Empty rules grant
	// nobody a role. Saving replaces the policy; the last save wins.
	SpaceConfig(ctx context.Context, space string) (config.SpaceConfig, error)
	SetSpaceConfig(ctx context.Context, space string, access config.SpaceConfig) error
	// DeleteSpace removes the complete space boundary: apps, services,
	// bindings, routes, runtime state, and data.
	DeleteSpace(ctx context.Context, space string) error

	ListApps(ctx context.Context) ([]AppRef, error)
	InternalURL(space, app string, port int) string
	Status(ctx context.Context, space, app string) (*AppStatus, error)
	// HasData is true even while the app is stopped or crash-looping — which
	// is exactly when someone needs to look at the disk.
	HasData(ctx context.Context, space, app string) bool
	// Restart returns false with no error when nothing is deployed.
	Restart(ctx context.Context, space, app string) (bool, error)
	Logs(ctx context.Context, space, app string, opts LogOptions, out io.Writer) error
	// Evidence collects why an app is unhealthy right now.
	Evidence(ctx context.Context, space, app string) Evidence

	// Deploy takes a built image live — storage, services, the app, its
	// addresses — narrated through progress. An app that never becomes
	// healthy fails with *RolloutError.
	Deploy(ctx context.Context, spec DeploySpec, progress Progress) error
	// Render is what Deploy would create, as text, without touching the
	// runtime. Credentials are left out: this lands in CI logs.
	Render(spec DeploySpec) (string, error)
	// Destroy removes only the app and everything app-owned; keepData spares
	// its disk. Space services have their own lifecycle.
	Destroy(ctx context.Context, space, app string, keepData bool) error

	GetEnv(ctx context.Context, space, app string) (map[string]string, error)
	SetEnv(ctx context.Context, space, app string, env map[string]string) error

	// AppMeta keeps small records on a deployed app that survive deploys. A
	// missing app or key reads as ""; writing nil removes the key.
	AppMeta(ctx context.Context, space, app, key string) (string, error)
	SetAppMeta(ctx context.Context, space, app, key string, value *string) error

	// Network reads actual runtime state, never stored intent. An undeployed
	// app simply has no routes.
	Network(ctx context.Context, space, app string) (*NetworkState, error)
	// ApplyNetwork changes how the app is reached, without a deploy. Existing
	// shared-address routes keep serving and follow the app's exposure. A
	// non-empty note is worth showing ("the certificate is still being issued").
	ApplyNetwork(ctx context.Context, cfg *config.AppConfig) (note string, err error)
	// ReconcileAppRoutes removes legacy app access lists and, when protect is
	// true, requires login on every route, including shared addresses.
	ReconcileAppRoutes(ctx context.Context, space, app string, protect bool) error

	// ServiceBinding is the env contract of a service instance: the space's
	// own for owner == addons.SharedOwner, an app's copy otherwise.
	ServiceBinding(ctx context.Context, space, owner, name string) (map[string]string, error)
	// ServiceConnection reads the canonical binding and its protocol together.
	// Metadata is kept separate from the environment injected into applications.
	ServiceConnection(ctx context.Context, space, name string) (ServiceConnection, error)
	// EnsureService creates the service if missing (waiting until it serves)
	// or re-applies it. The returned parameters are the resolved values the
	// instance runs with.
	EnsureService(ctx context.Context, space string, spec ServiceSpec) (binding map[string]string, parameters map[string]any, err error)
	// AttachService wires the binding into the app's env. Restarted reports
	// whether a running app picked it up on the spot.
	AttachService(ctx context.Context, space, app, name string, binding map[string]string) (restarted bool, err error)
	// DetachService unwires the binding. The service and its data stay.
	DetachService(ctx context.Context, space, app, name string) error
	// RemoveService detaches every app that uses the service first, and
	// returns who was detached.
	// With force, a plugin instance whose plugin is gone or failing is
	// dropped from donkey's records and its backing service left behind.
	RemoveService(ctx context.Context, space, name string, keepData, force bool) (detached []string, err error)
	// ServiceAttachments names the apps holding a copy of the service's
	// binding.
	ServiceAttachments(ctx context.Context, space, name string) ([]string, error)
	// ServiceEndpoint is the in-runtime address, for tunnels. An empty host
	// means the service runs elsewhere.
	ServiceEndpoint(ctx context.Context, space, name string) (host string, port int32, err error)
	// ListServices lists the bindings an owner holds.
	ListServices(ctx context.Context, space, owner string) ([]ServiceBindingInfo, error)
	// AIProxyTokens returns only credentials bound to this installation's AI
	// endpoint. Other OpenAI-compatible providers must not grant proxy access.
	AIProxyTokens(ctx context.Context) ([]string, error)
	// ServiceProxyAccess resolves a runtime IP to its space and checks that
	// space's canonical binding for the configured HTTP offering.
	ServiceProxyAccess(ctx context.Context, sourceIP, offering string) (bool, error)
	// ServiceProxySpaceAccess checks the current grant for a console request
	// whose space was authenticated by the control plane.
	ServiceProxySpaceAccess(ctx context.Context, space, offering string) (bool, error)

	// ExaProxyTokens returns only tokens bound to this installation's search endpoint.
	ExaProxyTokens(ctx context.Context) ([]string, error)

	// The app's disk. Paths are relative to the disk root, where each of the
	// app's storage paths has its own folder.
	ListFiles(ctx context.Context, space, app, path string) ([]FileEntry, error)
	StorageFolders(ctx context.Context, space, app string) ([]StorageFolder, error)
	ReadFile(ctx context.Context, space, app, path string, out io.Writer) error
	WriteFile(ctx context.Context, space, app, path string, in io.Reader) error
	RemoveFile(ctx context.Context, space, app, path string) error
	MoveFile(ctx context.Context, space, app, from, to string) error
	MakeDir(ctx context.Context, space, app, path string) error

	// Checks probes this runtime's own dependencies for doctor.
	Checks(ctx context.Context) []Check
}

Provider is one runtime. Every method takes donkey's names, never the runtime's own. Methods that change shared state are serialized per app by the caller. Providers serialize mutations of services shared by those apps.

type ResourceSample

type ResourceSample struct {
	Space string
	App   string
	// Instance is the stable identity used to distinguish replicas. Container
	// metadata is carried through to OTLP's standard resource attributes.
	Instance      string
	ContainerID   string
	ContainerName string
	KubeNamespace string
	KubePodName   string
	KubePodUID    string
	SampledAt     time.Time

	CPUCores          float64
	CPUUserCores      float64
	CPUSystemCores    float64
	CPUModesAvailable bool
	MemoryBytes       int64
}

ResourceSample is one installation-owned web container at one instant. The telemetry wire format keeps that container identity (as the OpenTelemetry semantic conventions require); retained app reports aggregate replicas.

type ResourceSampler

type ResourceSampler interface {
	ResourceSamples(ctx context.Context) ([]ResourceSample, error)
}

ResourceSampler is an optional runtime capability. Runtime resource usage is deliberately separate from Provider.Status: status is read frequently by fleet views, while Docker stats and the Kubernetes Metrics API are comparatively expensive. The server discovers this interface and samples it on its own bounded cadence.

type RolloutError

type RolloutError struct {
	App      string
	Evidence Evidence
	Reason   string
}

RolloutError means the new version never became healthy.

func (*RolloutError) Error

func (e *RolloutError) Error() string

type SecurityProvider

type SecurityProvider interface {
	UpdateSecurity(ctx context.Context, space, app, image, security string) error
}

SecurityProvider updates only the current image's security metadata. It never changes the workload or restarts it. Callers serialize with deploys.

type ServiceBindingInfo

type ServiceBindingInfo struct {
	Name     string
	Keys     []string
	Type     string
	Protocol string
	// Parameters are the resolved values the instance was created with.
	Parameters map[string]any
	// State is empty for a bound service. A plugin instance without a
	// binding reports pending, failed or stopped; Message says why.
	State   string
	Message string
}

ServiceBindingInfo is one binding as the console may see it — key names, never values.

type ServiceConnection

type ServiceConnection struct {
	Binding    map[string]string
	Type       string
	Protocol   string
	Parameters map[string]any
}

ServiceConnection is the canonical binding with its metadata.

type ServiceSpec

type ServiceSpec struct {
	Type string
	Name string
	// Parameters are values of the type's parameter schema. Missing ones
	// take the schema's defaults, or the instance's stored values when it
	// already exists.
	Parameters map[string]any
	// External: nothing is provisioned, the binding comes from URL.
	External bool
	URL      string
}

ServiceSpec asks for a service instance of the space.

type SpaceConfigsProvider

type SpaceConfigsProvider interface {
	ListSpaceConfigs(ctx context.Context) (map[string]config.SpaceConfig, error)
}

SpaceConfigsProvider lists space settings in bulk. These settings authorize requests and must be read fresh, even when workload summaries are cached.

type StorageFolder

type StorageFolder struct {
	// Name is the folder on the disk.
	Name string
	// Path is where the app has it mounted, e.g. /app/data.
	Path string
}

StorageFolder maps a folder on the disk to where the app mounts it.

type UserError

type UserError struct{ Err error }

UserError marks a caller's mistake, so handlers answer 400.

func (UserError) Error

func (e UserError) Error() string

func (UserError) Unwrap

func (e UserError) Unwrap() error

Directories

Path Synopsis
Package docker runs donkey's apps straight on a Docker engine — no Kubernetes, no kind.
Package docker runs donkey's apps straight on a Docker engine — no Kubernetes, no kind.
Package k8s wraps all Kubernetes access.
Package k8s wraps all Kubernetes access.
manifests
Package manifests turns donkey configuration into Kubernetes objects.
Package manifests turns donkey configuration into Kubernetes objects.

Jump to

Keyboard shortcuts

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