runtime

package
v0.0.397 Latest Latest
Warning

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

Go to latest
Published: Dec 11, 2024 License: Apache-2.0 Imports: 30 Imported by: 0

Documentation

Index

Constants

View Source
const (
	FnServiceLivez  = "foundation.namespacelabs.dev/livez"
	FnServiceReadyz = "foundation.namespacelabs.dev/readyz"
)
View Source
const LocalIngressPort = 40080

Variables

View Source
var (
	NamingNoTLS = false // Set to true in CI.

	WorkInProgressUseShortAlias = false
)
View Source
var ClusterInjection = execution.Define[Cluster]("ns.runtime.cluster")

ClusterInjection is used in execution.Execute to provide access to the cluster instance.

View Source
var ClusterNamespaceInjection = execution.Define[ClusterNamespace]("ns.runtime.cluster-namespace")

Functions

func AttachComputedDomains

func AttachComputedDomains(ctx context.Context, ws string, env cfg.Context, cluster Planner, sch *schema.Stack_Entry, template *schema.IngressFragment, allocatedName DomainsRequest) ([]*schema.IngressFragment, error)

func CalculateDomains

func CalculateDomains(env *schema.Environment, computed *schema.ComputedNaming, allocatedName DomainsRequest) ([]*schema.Domain, error)

func ComputeIngress

func ComputeIngress(ctx context.Context, env cfg.Context, planner Planner, sch *schema.Stack_Entry, allEndpoints []*schema.Endpoint) ([]*schema.IngressFragment, error)

func ComputeNaming

func ComputeNaming(ctx context.Context, moduleName string, env cfg.Context, planner Planner, source *schema.Naming) (*schema.ComputedNaming, error)

func DeployableCategory

func DeployableCategory(spec Deployable) string

func DeployableToProto

func DeployableToProto(spec Deployable) *runtimepb.Deployable

func HasRuntime

func HasRuntime(name string) bool

func OwnedByDeployable

func OwnedByDeployable(spec Deployable) string

func Prepare

func Prepare(ctx context.Context, key string, env cfg.Configuration, cluster Cluster) (any, error)

func PrepareKeyed

func PrepareKeyed(ctx context.Context, stateKey string, env cfg.Configuration, cluster Cluster, key string) (any, error)

func Register

func Register(name string, r InstantiateClassFunc)

func RegisterKeyedPrepare

func RegisterKeyedPrepare(key string, callback func(context.Context, cfg.Configuration, Cluster, string) (any, error))

func RegisterPrepare

func RegisterPrepare(key string, callback func(context.Context, cfg.Configuration, Cluster) (any, error))

func ResolveResolvables added in v0.0.167

func ResolveResolvables[V LikeResolvable](ctx context.Context, rt *runtimepb.RuntimeConfig, secrets ResolvableSecretSource, resolvables []V, out ResolvableSink) error

func RunAttached

func RunAttached(ctx context.Context, config cfg.Context, planner Planner, spec DeployableSpec, io TerminalIO) error

func RunAttachedStdio

func RunAttachedStdio(ctx context.Context, config cfg.Context, planner Planner, spec DeployableSpec) error

func SelectInstance added in v0.0.167

func SelectInstance(rt *runtimepb.RuntimeConfig, instance *schema.ResolvableSource) (any, error)

func SelectService added in v0.0.116

func SelectServiceEndpoint added in v0.0.116

func SelectServiceEndpoint(svc *runtimepb.Server_Service) (string, error)

func SelectServiceIngress added in v0.0.116

func SelectServiceIngress(service *runtimepb.Server_Service) (string, error)

func SelectServiceValue added in v0.0.116

func SelectServiceValue(rt *runtimepb.RuntimeConfig, ref *schema.ServiceRef, selector func(*runtimepb.Server_Service) (string, error)) (string, error)

func WriteToWriter added in v0.0.92

func WriteToWriter(w io.Writer) func(ContainerLogLine)

func WriteToWriterWithTimestamps added in v0.0.92

func WriteToWriterWithTimestamps(w io.Writer) func(ContainerLogLine)

Types

type AttachableKind

type AttachableKind string
const (
	AttachableKind_WITH_STDIN_ONLY AttachableKind = "stdin-only"
	AttachableKind_WITH_TTY        AttachableKind = "with-tty"
)

type Class

type Class interface {
	// Attaches to an existing cluster. Fails if the cluster doesn't exist or
	// the provider used would have instantiated a new cluster.
	AttachToCluster(context.Context, cfg.Configuration) (Cluster, error)

	// Attaches to an existing cluster (if not is specified in the
	// configuration), or creates a new cluster as needed.
	EnsureCluster(context.Context, cfg.Context, string) (Cluster, error)

	// Planner produces a planner for this runtime class. This may instantiate a
	// new cluster, but will attempt to do so lazily.
	Planner(context.Context, cfg.Context, string, map[string]string) (Planner, error)
}

A runtime class represents a runtime implementation type, e.g. "kubernetes". The codebase seldom interacts with Class, but instead of Cluster instances obtained from a runtime class.

func ClassFor

func ClassFor(ctx context.Context, env cfg.Context) (Class, error)

type Cluster

type Cluster interface {
	// Returns a namespace'd cluster -- one for a particular application use,
	// bound to the workspace identified by the cfg.Context.
	Bind(context.Context, cfg.Context) (ClusterNamespace, error)

	// Fetch diagnostics of a particular container reference.
	FetchDiagnostics(context.Context, *runtimepb.ContainerReference) (*runtimepb.Diagnostics, error)

	// Fetch logs of a specific container reference.
	FetchLogsTo(ctx context.Context, container *runtimepb.ContainerReference, opts FetchLogsOpts, callback func(ContainerLogLine)) error

	// Attaches to a running container.
	AttachTerminal(ctx context.Context, container *runtimepb.ContainerReference, io TerminalIO) error

	// Exposes the cluster's ingress, in the specified local address and port.
	// This is used to create stable localhost-bound ingress addresses (for e.g.
	// nslocal.host).
	ForwardIngress(ctx context.Context, localAddrs []string, localPort int, notify PortForwardedFunc) (io.Closer, error)

	// EnsureState ensures that a cluster-specific bit of initialization is done once per instance.
	EnsureState(context.Context, string) (any, error)

	// EnsureState ensures that a cluster-specific bit of initialization is done once per instance.
	EnsureKeyedState(context.Context, string, string) (any, error)

	// Deletes any runtime resource deployed by this runtime, regardless of
	// environment. If wait is true, waits until the target resources have been
	// removed. Returns true if resources were deleted.
	DeleteAllRecursively(ctx context.Context, wait bool, progress io.Writer) (bool, error)
}

A cluster represents a cluster where Namespace is capable of deployment one or more applications.

func ClusterFor

func ClusterFor(ctx context.Context, env cfg.Context) (Cluster, error)

type ClusterNamespace

type ClusterNamespace interface {
	// Returns a reference to the cluster where this namespace exists.
	Cluster() Cluster

	// DeployedConfigImageID retrieves the image reference of the "configuration
	// image" used to deploy the specified server. Configuration images are only
	// generated for production environments for now.
	DeployedConfigImageID(context.Context, Deployable) (oci.ImageID, error)

	// Returns a list of containers that the server has deployed.
	ResolveContainers(context.Context, Deployable) ([]*runtimepb.ContainerReference, error)

	// Fetch environment diagnostics, e.g. event list.
	FetchEnvironmentDiagnostics(context.Context) (*storage.EnvironmentDiagnostics, error)

	// Starts a new shell in the container of a previously deployed server. The
	// image of the server must contain the specified command. For ephemeral
	// containers, see #329.
	StartTerminal(ctx context.Context, server Deployable, io TerminalIO, command string, rest ...string) error

	// Forwards a single port.
	// XXX remove; callers should instead implement their own TCP net.Listener
	// and call DialServer as needed.
	ForwardPort(ctx context.Context, server Deployable, containerPort int32, localAddrs []string, notify SinglePortForwardedFunc) (io.Closer, error)

	// Dials a TCP port to one of the replicas of the target server. The
	// lifecycle of the connection is bound to the specified context.
	DialServer(ctx context.Context, server Deployable, port *schema.Endpoint_Port) (net.Conn, error)

	// Observes lifecyle events of the specified server. Unless OneShot is set,
	// Observe runs until the context is cancelled.
	Observe(context.Context, Deployable, ObserveOpts, func(ObserveEvent) (bool, error)) error

	// WaitUntilReady blocks until the target deployable reports ready. If the
	// deployable represents a collection of replicas, readiness waits for all
	// replicas to become ready.
	WaitUntilReady(ctx context.Context, object Deployable) error

	// Waits until the specified deployable is no longer running (typically a one-shot).
	WaitForTermination(ctx context.Context, object Deployable) ([]ContainerStatus, error)

	// Deletes a previously deployed DeployableSpec.
	DeleteDeployable(ctx context.Context, deployable Deployable) error

	// Deletes the scoped environment, and all of its associated resources (e.g.
	// after a test invocation). If wait is true, waits until the target
	// resources have been removed. Returns true if resources were deleted.
	DeleteRecursively(ctx context.Context, wait bool) (bool, error)
}

ClusterNamespace represents a target deployment environment, scoped to an application (usually the combination of an environment and workspace).

func NamespaceFor

func NamespaceFor(ctx context.Context, env cfg.Context) (ClusterNamespace, error)

type ComputedResource added in v0.0.117

type ComputedResource struct {
	ResourceInstanceID     string
	InstanceType           *schema.ResourceType
	InstanceSerializedJSON []byte
}

A resource whose instance is known.

type ContainerLogLine added in v0.0.92

type ContainerLogLine struct {
	Timestamp        time.Time
	MissingTimestamp bool
	LogLine          []byte
	Event            ContainerLogLineEvent
	ResumeErr        error
}

type ContainerLogLineEvent added in v0.0.92

type ContainerLogLineEvent string
const (
	ContainerLogLineEvent_LogLine   ContainerLogLineEvent = "ns.logline"
	ContainerLogLineEvent_Connected ContainerLogLineEvent = "ns.connected"
	ContainerLogLineEvent_Resuming  ContainerLogLineEvent = "ns.resuming"
)

type ContainerRunOpts

type ContainerRunOpts struct {
	WorkingDir                    string
	Image                         oci.ImageID
	Command                       []string
	Args                          []string
	Env                           []*schema.BinaryConfig_EnvEntry
	RunAs                         *RunAs
	ReadOnlyFilesystem            bool
	Privileged                    bool
	HostNetwork                   bool
	Capabilities                  []string
	Mounts                        []*schema.Mount
	ContainerPorts                []*schema.Endpoint_Port
	ResourceLimits                *schema.Container_ResourceLimits
	ResourceRequests              *schema.Container_ResourceLimits
	TerminationGracePeriodSeconds int64
}

type ContainerStatus

type ContainerStatus struct {
	Reference        *runtimepb.ContainerReference
	TerminationError error
}

type Deployable

type Deployable interface {
	GetPackageRef() *schema.PackageRef

	GetId() string

	GetName() string

	// Returns a string to be compatible with the proto API.
	GetDeployableClass() string // schema.DeployableClass
}

type DeployableSpec

type DeployableSpec struct {
	ErrorLocation fnerrors.Location

	PackageRef *schema.PackageRef
	Focused    bool // Set to true if the user explicitly asked for this object to be deployed.
	Attachable AttachableKind

	Description     string
	Class           schema.DeployableClass
	Id              string // Must not be empty.
	Name            string // Can be empty.
	Volumes         []*schema.Volume
	Permissions     *schema.ServerPermissions
	Replicas        int32
	Tolerations     []*schema.Server_Toleration
	Annotations     []*schema.NamedResolvable // Annotations that apply to individual pods.
	NodeSelector    []*schema.NodeSelectorItem
	PodAntiAffinity *schema.PodAntiAffinity
	UpdateStrategy  *schema.UpdateStrategy

	MainContainer ContainerRunOpts
	Sidecars      []SidecarRunOpts
	Inits         []SidecarRunOpts

	ConfigImage         *oci.ImageID
	RuntimeConfig       *runtimepb.RuntimeConfig
	BuildVCS            *runtimepb.BuildVCS
	ResourceDeps        []*resources.ResourceDependency
	PlannedResourceDeps []*resources.ResourceDependency
	ComputedResources   []ComputedResource

	Secrets secrets.GroundedSecrets

	// The list of primitive std/runtime:Secret that this deployable depends on.
	// These are treated in a special way: each one of them is mounted under
	// /namespace/secrets automatically, and the corresponding SecretInstance
	// entries are generated by the runtime-specific planner.
	SecretResources []SecretResourceDependency

	// Where to mount the runtime configuration; if unset, the runtime
	// configuration is not persisted, and not mounted.
	MountRuntimeConfigPath string

	SetContainerField []*runtimepb.SetContainerField

	Extensions []*schema.DefExtension

	Endpoints         []*schema.Endpoint         // Owned by this deployable.
	InternalEndpoints []*schema.InternalEndpoint // Owned by this deployable.

	Probes []*schema.Probe
}

func (DeployableSpec) GetDeployableClass

func (d DeployableSpec) GetDeployableClass() string

func (DeployableSpec) GetId

func (d DeployableSpec) GetId() string

func (DeployableSpec) GetName

func (d DeployableSpec) GetName() string

func (DeployableSpec) GetPackageName

func (d DeployableSpec) GetPackageName() string

func (DeployableSpec) GetPackageRef added in v0.0.83

func (d DeployableSpec) GetPackageRef() *schema.PackageRef

type DeploymentPlan

type DeploymentPlan struct {
	Definitions []*schema.SerializedInvocation
	Hints       []string

	// A unique ID that is consistent across invocations, for the same runtime,
	// that represents a tenant namespace.
	NamespaceReference string
}

type DeploymentSpec

type DeploymentSpec struct {
	Specs []DeployableSpec
}

type DomainsRequest

type DomainsRequest struct {
	ServerID    string
	ServiceName string
	Key         string // Usually `{ServiceName}-{ServerID}`
	Alias       string

	// Set to true if the service we're allocating a domain for should be TLS
	// terminated, regardless of whether we can emit a public-CA rooted
	// certificate or not. E.g. for gRPC.
	RequiresTLS bool

	UserSpecified []*schema.DomainSpec
}

type EndpointPortForwarder

type EndpointPortForwarder interface {
	io.Closer
	Update([]*schema.Endpoint)
}

type ErrContainerExitStatus

type ErrContainerExitStatus struct {
	ExitCode int32
}

func (ErrContainerExitStatus) Error

func (e ErrContainerExitStatus) Error() string

type ErrContainerFailed

type ErrContainerFailed struct {
	Name     string
	Failures []ErrContainerFailed_Failure
}

func (ErrContainerFailed) Error

func (e ErrContainerFailed) Error() string

type ErrContainerFailed_Failure

type ErrContainerFailed_Failure struct {
	Reference *runtimepb.ContainerReference // A pointer that can be passed to the runtime to fetch logs.
	Reason    string
	Message   string
	ExitCode  int32
}

type FetchLogsOpts

type FetchLogsOpts struct {
	TailLines        int // Only used if it's a positive value.
	Follow           bool
	FetchLastFailure bool
}

type ForwardedPort

type ForwardedPort struct {
	LocalPort     uint
	ContainerPort uint
}

type ForwardedPortEvent

type ForwardedPortEvent struct {
	Endpoint *schema.Endpoint

	Added   []ForwardedPort
	Removed bool
	Error   error
}

type IngressClass added in v0.0.113

type IngressClass interface {
	Name() string

	// ComputeBaseNaming returns a base naming configuration that is specific
	// to the target runtime (e.g. kubernetes cluster).
	ComputeNaming(context.Context, *schema.Environment, *schema.Naming) (*schema.ComputedNaming, error)
}

type InstantiateClassFunc

type InstantiateClassFunc func(context.Context, cfg.Configuration) (Class, error)

type LikeResolvable added in v0.0.167

type LikeResolvable interface {
	GetName() string
	GetValue() *schema.Resolvable
}

type ObserveEvent

type ObserveEvent struct {
	Deployable         *runtimepb.Deployable
	ContainerReference *runtimepb.ContainerReference
	Version            string
	Added              bool
	Removed            bool
}

type ObserveOpts

type ObserveOpts struct {
}

type Planner

type Planner interface {
	// Plans a deployment, i.e. produces a series of instructions that will
	// instantiate the required deployment resources to run the servers in the
	// specified Deployment. This method is side-effect free; mutations are
	// applied when the generated plan is applied.
	PlanDeployment(context.Context, DeploymentSpec) (*DeploymentPlan, error)

	// Plans an ingress deployment, i.e. produces a series of instructions that
	// will instantiate the required deployment resources to run the servers
	// with the specified Ingresses. This method is side-effect free; mutations
	// are applied when the generated plan is applied.
	PlanIngress(context.Context, *schema.Stack, []*schema.IngressFragment) (*DeploymentPlan, error)

	// PrepareProvision is called before invoking a provisioning tool, to offer
	// the runtime implementation a way to pass runtime-specific information to
	// the tool. E.g. what's the Kubernetes namespace we're working with.
	PrepareProvision(context.Context) (*rtypes.RuntimeProvisionProps, error)

	// Returns the set of platforms that the target runtime operates on, e.g. linux/amd64.
	TargetPlatforms(context.Context) ([]specs.Platform, error)

	// The registry we should upload to.
	Registry() registry.Manager

	// The ingress class this runtime implementation uses.
	Ingress() IngressClass

	// Returns DNS-resolvable names for a particular service; the first one
	// being a short-hand usable within the same namespace, and the latter being
	// a fully qualified domain name.
	MakeServiceName(string) (string, string)

	EnsureClusterNamespace(context.Context) (ClusterNamespace, error)
}

A planner is capable of generating namespace-specific deployment plans. It may obtain external data in order to produce a plan, but none of its methods mutate outside state in order to do so.

func PlannerFor

func PlannerFor(ctx context.Context, env cfg.Context) (Planner, error)

type PortForwardedFunc

type PortForwardedFunc func(ForwardedPortEvent)

type ResolvableSecretSource added in v0.0.167

type ResolvableSecretSource interface {
	Allocate(context.Context, *schema.PackageRef) (*SecretRef, error)
}

type ResolvableSink added in v0.0.167

type ResolvableSink interface {
	SetValue(key, value string) error
	SetSecret(key string, secret *SecretRef) error
	SetExperimentalFromDownwardsFieldPath(key, value string) error
	// XXX replace with late bound FieldSelector.
	SetLateBoundResourceFieldSelector(key string, _ runtimepb.SetContainerField_ValueSource, src *schema.ResourceConfigFieldSelector) error
}

type ResolvableSinkMap added in v0.0.167

type ResolvableSinkMap map[string]string

func (*ResolvableSinkMap) SetExperimentalFromDownwardsFieldPath added in v0.0.167

func (x *ResolvableSinkMap) SetExperimentalFromDownwardsFieldPath(key, value string) error

func (*ResolvableSinkMap) SetLateBoundResourceFieldSelector added in v0.0.167

func (x *ResolvableSinkMap) SetLateBoundResourceFieldSelector(key string, _ runtimepb.SetContainerField_ValueSource, src *schema.ResourceConfigFieldSelector) error

func (*ResolvableSinkMap) SetSecret added in v0.0.167

func (x *ResolvableSinkMap) SetSecret(key string, secret *SecretRef) error

func (*ResolvableSinkMap) SetValue added in v0.0.167

func (x *ResolvableSinkMap) SetValue(key, value string) error

type RunAs

type RunAs struct {
	UserID  string
	FSGroup *string
}

type SecretRef added in v0.0.167

type SecretRef struct {
	Name string
	Key  string
}

type SecretResourceDependency

type SecretResourceDependency struct {
	SecretRef   *schema.PackageRef
	ResourceRef *schema.PackageRef
}

type SidecarRunOpts

type SidecarRunOpts struct {
	Name      string
	BinaryRef *schema.PackageRef
	ContainerRunOpts
}

type SinglePortForwardedFunc

type SinglePortForwardedFunc func(ForwardedPort)

type TerminalIO

type TerminalIO struct {
	TTY bool

	Stdin  io.Reader
	Stdout io.Writer
	Stderr io.Writer

	// Optional. If set, a runtime can listen on this channel for terminal resize requests.
	ResizeQueue chan termios.WinSize
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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