functions

package
v0.40.1 Latest Latest
Warning

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

Go to latest
Published: Mar 13, 2024 License: Apache-2.0 Imports: 40 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// DefaultRegistry through which containers of functions will be shuttled.
	DefaultRegistry = "index.docker.io"

	// DefaultTemplate is the default function signature / environmental context
	// of the resultant function.  All runtimes are expected to have at least
	// one implementation of each supported function signature.  Currently that
	// includes an HTTP Handler ("http") and Cloud Events handler ("events")
	DefaultTemplate = "http"

	// DefaultStartTimeout is the suggested startup timeout to use by
	// runner implementations.
	DefaultStartTimeout = 60 * time.Second
)
View Source
const (
	// FunctionFile is the file used for the serialized form of a function.
	FunctionFile = "func.yaml"

	// RunDataDir holds transient runtime metadata
	// By default it is excluded from source control.
	RunDataDir       = ".func"
	RunDataLocalFile = "local.yaml"
)
View Source
const (
	StorageMediumDefault = ""       // use whatever the default is for the node, assume anything we don't explicitly handle is this
	StorageMediumMemory  = "Memory" // use memory (e.g. tmpfs on linux)
)
View Source
const (
	EnvironmentLocal  = "local"
	EnvironmentRemote = "remote"
)
View Source
const (
	DefaultInvokeSource      = "/boson/fn"
	DefaultInvokeType        = "boson.fn"
	DefaultInvokeContentType = "application/json"
	DefaultInvokeData        = `{"message":"Hello World"}`
	DefaultInvokeFormat      = "http"
)
View Source
const (
	// DefaultReadinessEndpoint for final deployed function instances
	DefaultReadinessEndpoint = "/health/readiness"
	// DefaultLivenessEndpoint for final deployed function instances
	DefaultLivenessEndpoint = "/health/liveness"
	// DefaultTemplatesPath is the root of the defined repository
	DefaultTemplatesPath = "."
	// DefaultInvocationFormat is a named invocation hint for the convenience
	// helper .Invoke.  It is usually set at the template level.  The default
	// ('http') is a plain HTTP POST.
	DefaultInvocationFormat = "http"
)
View Source
const (
	// DefaultRepositoryName is the name by which the currently default repo can
	// be referred.  This name is assumed when no template prefix is provided
	// when determining a template canonical (full) name.
	// Unless a single-repo override is defined, this is usually referring to the
	// builtin (embedded) repository.
	DefaultRepositoryName = "default"
)

Variables

View Source
var (
	ErrEnvironmentNotFound       = errors.New("environment not found")
	ErrMismatchedName            = errors.New("name passed the function source")
	ErrNameRequired              = errors.New("name required")
	ErrNotBuilt                  = errors.New("not built")
	ErrNotRunning                = errors.New("function not running")
	ErrRepositoriesNotDefined    = errors.New("custom template repositories location not specified")
	ErrRepositoryNotFound        = errors.New("repository not found")
	ErrRootRequired              = errors.New("function root path is required")
	ErrRuntimeNotFound           = errors.New("language runtime not found")
	ErrRuntimeRequired           = errors.New("language runtime required")
	ErrTemplateMissingRepository = errors.New("template name missing repository prefix")
	ErrTemplateNotFound          = errors.New("template not found")
	ErrTemplatesNotFound         = errors.New("templates path (runtimes) not found")
	ErrContextCanceled           = errors.New("the operation was canceled")

	// TODO: change the wording of this error to not be CLI-specific;
	// eg "registry required".  Then catch the error in the CLI and add the
	// cli-specific usage hints there
	ErrRegistryRequired = errors.New("registry required to build function, please set with `--registry` or the FUNC_REGISTRY environment variable")
)
View Source
var (
	// DefaultPlatforms is a suggestion to builder implementations which
	// platforms should be the default.  Due to spotty implementation support
	// use of this set is left up to the discretion of the builders
	// themselves.  In the event the builder receives build options which
	// specify a set of platforms to use in leau of the default (see the
	// BuildWithPlatforms functionl option), the builder should return
	// an error if the request can not proceed.
	DefaultPlatforms = []Platform{
		{OS: "linux", Architecture: "amd64"},
		{OS: "linux", Architecture: "arm64"},
		{OS: "linux", Architecture: "arm", Variant: "v7"},
	}
)
View Source
var EmbeddedTemplatesFS filesystem.Filesystem = newEmbeddedTemplatesFS()

Functions

func FilesystemFromRepo

func FilesystemFromRepo(uri string) (filesystem.Filesystem, error)

FilesystemFromRepo attempts to fetch a filesystem from a git repository indicated by the given URI. Returns nil if there is not a repo at the URI.

func Fingerprint added in v0.38.0

func Fingerprint(root string) (hash, log string, err error)

Fingerprint the files at a given path. Returns a hash calculated from the filenames and modification timestamps of the files within the given root. Also returns a logfile consiting of the filenames and modification times which contributed to the hash. Intended to determine if there were appreciable changes to a function's source code, certain directories and files are ignored, such as .git and .func. Future updates will include files explicitly marked as ignored by a .funcignore.

func Interpolate

func Interpolate(ee []Env) (map[string]string, error)

Interpolate Env slice Values with no special format are preserved as simple values. Values which do include the interpolation format (begin with {{) but are not keyed as "env" are also preserved as is. Values properly formatted as {{ env:NAME }} are interpolated (substituted) with the value of the local environment variable "NAME", and an error is returned if that environment variable does not exist.

func LastSpecVersion

func LastSpecVersion() string

LastSpecVersion returns the string value for the most recent migration

func NewErrNotInitialized added in v0.38.0

func NewErrNotInitialized(path string) error

func RepositoriesPath

func RepositoriesPath() string

RepositoriesPath is a convenience method for accessing the default path to repositories that will be used by new instances of a Client unless options such as WithRepositoriesPath are used to override. The path will be created if it does not already exist.

func ValidateBuildEnvs

func ValidateBuildEnvs(envs []Env) (errors []string)

ValidateBuildEnvs checks that input BuildEnvs are correct and contain all necessary fields. Returns array of error messages, empty if no errors are found

Allowed settings:

  • name: EXAMPLE1 # ENV directly from a value value: value1
  • name: EXAMPLE2 # ENV from the local ENV var value: {{ env:MY_ENV }}

func ValidateEnvs

func ValidateEnvs(envs []Env) (errors []string)

ValidateEnvs checks that input Envs are correct and contain all necessary fields. Returns array of error messages, empty if no errors are found

Allowed settings:

  • name: EXAMPLE1 # ENV directly from a value value: value1
  • name: EXAMPLE2 # ENV from the local ENV var value: {{ env:MY_ENV }}
  • name: EXAMPLE3 value: {{ secret:secretName:key }} # ENV from a key in secret
  • value: {{ secret:secretName }} # all key-pair values from secret are set as ENV
  • name: EXAMPLE4 value: {{ configMap:configMapName:key }} # ENV from a key in configMap
  • value: {{ configMap:configMapName }} # all key-pair values from configMap are set as ENV

func ValidateLabels

func ValidateLabels(labels []Label) (errors []string)

ValidateLabels checks that input labels are correct and contain all necessary fields. Returns array of error messages, empty if no errors are found

Allowed settings:

  • key: EXAMPLE1 # label directly from a value value: value1
  • key: EXAMPLE2 # label from the local ENV var value: {{ env:MY_ENV }}

func WithStampJournal added in v0.38.0

func WithStampJournal() stampOption

WithStampJournaling is a Stamp option which causes the stamp logfile to be created with a timestamp prefix. This has the effect of creating a stamp journal, useful for debugging. The default behavior is to only retain the most recent log file as "built.log".

Types

type BuildConfig

type BuildConfig struct {
	Buildpacks    []string          `yaml:"buildpacks,omitempty"`
	BuilderImages map[string]string `yaml:"builderImages,omitempty"`
}

BuildConfig defines builders and buildpacks

type BuildOption added in v0.38.0

type BuildOption func(c *BuildOptions)

func BuildWithPlatforms added in v0.38.0

func BuildWithPlatforms(pp []Platform) BuildOption

type BuildOptions added in v0.38.0

type BuildOptions struct {
	Platforms []Platform
}

type BuildSpec

type BuildSpec struct {
	// Git stores information about an optionally associated git repository.
	Git Git `yaml:"git,omitempty"`

	// BuilderImages define optional explicit builder images to use by
	// builder implementations in leau of the in-code defaults.  They key
	// is the builder's short name.  For example:
	// builderImages:
	//   pack: example.com/user/my-pack-node-builder
	//   s2i: example.com/user/my-s2i-node-builder
	BuilderImages map[string]string `yaml:"builderImages,omitempty"`

	// Optional list of buildpacks to use when building the function
	Buildpacks []string `yaml:"buildpacks,omitempty"`

	// Builder is the name of the subsystem that will complete the underlying
	// build (pack, s2i, etc)
	Builder string `yaml:"builder,omitempty" jsonschema:"enum=pack,enum=s2i"`

	// Build Env variables to be set
	BuildEnvs Envs `yaml:"buildEnvs,omitempty"`

	// PVCSize specifies the size of persistent volume claim used to store function
	// when using deployment and remote build process (only relevant when Remote is true).
	PVCSize string `yaml:"pvcSize,omitempty"`
}

BuildSpec

type Builder

type Builder interface {
	// Build a function project with source located at path.
	Build(context.Context, Function, []Platform) error
}

Builder of function source to runnable image.

type Client

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

Client for managing function instances.

func New

func New(options ...Option) *Client

New client for function management.

func (*Client) Apply

func (c *Client) Apply(ctx context.Context, f Function) (string, Function, error)

Apply (aka upsert)

The general-purpose high-level method to initiate a synchronization of a function's source code and it's deployed instance(s).

Invokes all lower-level methods, including initialization, as necessary to create a running function whose source code and metadata match that provided by the passed function instance, returning the final route and any errors.

func (*Client) Build

func (c *Client) Build(ctx context.Context, f Function, options ...BuildOption) (Function, error)

Build the function at path. Errors if the function is either unloadable or does not contain a populated Image.

func (*Client) ConfigurePAC

func (c *Client) ConfigurePAC(ctx context.Context, f Function, metadata any) error

ConfigurePAC generates Pipeline resources on the local filesystem, on the cluster and also on the remote git provider (ie. GitHub, GitLab or BitBucket repo)

func (*Client) Deploy

func (c *Client) Deploy(ctx context.Context, f Function, opts ...DeployOption) (Function, error)

Deploy the function at path. Errors if the function has not been built unless explicitly instructed to ignore this build check.

func (*Client) Describe

func (c *Client) Describe(ctx context.Context, name string, f Function) (d Instance, err error)

Describe a function. Name takes precedence. If no name is provided, the function defined at root is used.

func (*Client) Init

func (c *Client) Init(cfg Function) (Function, error)

Initialize a new function with the given function struct defaults. Does not build/push/deploy. Local FS changes only. For higher-level control see New or Apply.

<path> will default to the absolute path of the current working directory. <name> will default to the current working directory. When <name> is provided but <path> is not, a directory <name> is created in the current working directory and used for <path>.

func (*Client) Instances

func (c *Client) Instances() *InstanceRefs

Instances accessor

func (*Client) Invoke

func (c *Client) Invoke(ctx context.Context, root string, target string, m InvokeMessage) (metadata map[string][]string, body string, err error)

Invoke is a convenience method for triggering the execution of a function for testing and development. Returned is a map of metadata and a stringified version of the content. The target argument is optional, naming the running instance of the function which should be invoked. This can be the literal names "local" or "remote", or can be a URL to an arbitrary endpoint. If not provided, a running local instance is preferred, with the remote function triggered if there is no locally running instance. Example:

myClient.Invoke(myContext, myFunction, "local", NewInvokeMessage())

The message sent to the function is defined by the invoke message. See NewInvokeMessage for its defaults. Functions are invoked in a manner consistent with the settings defined in their metadata. For example HTTP vs CloudEvent

func (*Client) List

func (c *Client) List(ctx context.Context) ([]ListItem, error)

List currently deployed functions.

func (*Client) New

func (c *Client) New(ctx context.Context, cfg Function) (string, Function, error)

New function.

Creates a new running function from the path indicated by the config Function. Used by Apply when the path is not yet an initialized function. Errors if the path is alrady an initialized function.

Use Apply for higher level control. Use Init, Build, Push, Deploy independently for lower level control. Returns the primary route to the function or error.

func (*Client) Push

func (c *Client) Push(ctx context.Context, f Function) (Function, error)

Push the image for the named service to the configured registry

func (*Client) Registry

func (c *Client) Registry() string

Repository accessor returns the default registry for use when building Functions which do not specify Registry or Image name explicitly.

func (*Client) Remove

func (c *Client) Remove(ctx context.Context, cfg Function, deleteAll bool) error

Remove a function. Name takes precedence. If no name is provided, the function defined at root is used if it exists.

func (*Client) RemovePAC

func (c *Client) RemovePAC(ctx context.Context, f Function, metadata any) error

RemovePAC deletes generated Pipeline as Code resources on the local filesystem and on the cluster

func (*Client) Repositories

func (c *Client) Repositories() *Repositories

Repositories accessor

func (*Client) RepositoriesPath

func (c *Client) RepositoriesPath() (path string)

RepositoriesPath accesses the currently effective repositories path, which can be set using the WithRepositoriesPath option.

func (*Client) Route

func (c *Client) Route(ctx context.Context, f Function) (string, Function, error)

Route returns the current primary route to the function at root.

Note that local instances of the Function created by the .Run method are not considered here. This method is intended to specifically apply to the logical group of function instances actually available as network sevices; this excludes local testing instances.

For access to these local test function instances routes, use the instances manager directly ( see .Instances().Get() ).

func (*Client) Run

func (c *Client) Run(ctx context.Context, f Function, options ...RunOption) (job *Job, err error)

Run the function whose code resides at root. On start, the chosen port is sent to the provided started channel

func (*Client) RunPipeline

func (c *Client) RunPipeline(ctx context.Context, f Function) (Function, error)

RunPipeline runs a Pipeline to build and deploy the function. Returned function contains applicable registry and deployed image name.

func (*Client) Runtimes

func (c *Client) Runtimes() ([]string, error)

Runtimes available in totality. Not all repository/template combinations necessarily exist, and further validation is performed when a template+runtime is chosen. from a given repository. This is the global list of all available. Returned list is unique and sorted.

func (*Client) Scaffold added in v0.38.0

func (c *Client) Scaffold(ctx context.Context, f Function, dest string) (err error)

Scaffold writes a functions's scaffolding to a given path. It also updates the included symlink to function source 'f' to point to the current function's source.

func (*Client) Templates

func (c *Client) Templates() *Templates

Templates accessor

func (*Client) Update

func (c *Client) Update(ctx context.Context, f Function) (string, Function, error)

Update function

Updates a function which has already been initialized to run the latest source code.

Use Apply for higher level control. Use Init, Build, Push and Deploy independently for lower level control. Returns final primary route to the Function and any errors.

type DNSProvider

type DNSProvider interface {
	// Provide the given name by routing requests to address.
	Provide(Function) error
}

DNSProvider exposes DNS services necessary for serving the function.

type DeployOption

type DeployOption func(f *DeployParams)

func WithDeploySkipBuildCheck

func WithDeploySkipBuildCheck(skipBuiltCheck bool) DeployOption

type DeployParams

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

type DeploySpec

type DeploySpec struct {
	// Namespace into which the function is deployed on supported platforms.
	Namespace string `yaml:"namespace,omitempty"`

	// Map containing user-supplied annotations
	// Example: { "division": "finance" }
	Annotations map[string]string `yaml:"annotations,omitempty"`

	// Options to be set on deployed function (scaling, etc.)
	Options Options `yaml:"options,omitempty"`

	// Map of user-supplied labels
	Labels []Label `yaml:"labels,omitempty"`

	// Health endpoints specified by the language pack
	HealthEndpoints HealthEndpoints `yaml:"healthEndpoints,omitempty"`

	// ServiceAccountName is the name of the service account used for the
	// function pod. The service account must exist in the namespace to
	// succeed.
	// More info: https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/
	ServiceAccountName string `yaml:"serviceAccountName,omitempty"`

	Subscriptions []KnativeSubscription `yaml:"subscriptions,omitempty"`
}

DeploySpec

type Deployer

type Deployer interface {
	// Deploy a function of given name, using given backing image.
	Deploy(context.Context, Function) (DeploymentResult, error)
}

Deployer of function source to running status.

type DeploymentResult

type DeploymentResult struct {
	Status    Status
	URL       string
	Namespace string
}

type Describer

type Describer interface {
	// Describe the named function in the remote environment.
	Describe(ctx context.Context, name string) (Instance, error)
}

Describer of function instances

type EmptyDir added in v0.38.0

type EmptyDir struct {
	// medium represents what type of storage medium should back this directory.
	// The default is "" which means to use the node's default medium.
	// Must be an empty string (default) or Memory.
	// More info: https://kubernetes.io/docs/concepts/storage/volumes#emptydir
	Medium string `yaml:"medium,omitempty"`
	// sizeLimit is the total amount of local storage required for this EmptyDir volume.
	// The size limit is also applicable for memory medium.
	// The maximum usage on memory medium EmptyDir would be the minimum value between
	// the SizeLimit specified here and the sum of memory limits of all containers in a pod.
	// The default is nil which means that the limit is undefined.
	// More info: http://kubernetes.io/docs/user-guide/volumes#emptydir
	SizeLimit *string `yaml:"sizeLimit,omitempty"`
}

type Env

type Env struct {
	Name  *string `yaml:"name,omitempty" jsonschema:"pattern=^[-._a-zA-Z][-._a-zA-Z0-9]*$"`
	Value *string `yaml:"value,omitempty"`
}

func (Env) KeyValuePair

func (e Env) KeyValuePair() string

KeyValuePair returns a string representation of the Env field in form NAME=VALUE if NAME is not defined for an Env, empty string is returned

func (Env) String

func (e Env) String() string

type Envs added in v0.38.0

type Envs []Env

func (Envs) Slice added in v0.38.0

func (ee Envs) Slice() []string

Slice returns Envs as a []strings in format NAME=VALUE Note that Env structs with a nil pointer for name are ignored because "=VALUE" is an invalid environment variable declaration.

func (Envs) String added in v0.38.0

func (ee Envs) String() string

String returns Envs as a space-separated set of environment variable declarations in the form "KEY=VALUE K2=V2"

type ErrNotInitialized

type ErrNotInitialized struct {
	Path string
}

ErrNotInitialized indicates that a function is uninitialized

func (ErrNotInitialized) Error added in v0.38.0

func (e ErrNotInitialized) Error() string

type ErrRunTimeout added in v0.38.0

type ErrRunTimeout struct {
	Timeout time.Duration
}

func (ErrRunTimeout) Error added in v0.38.0

func (e ErrRunTimeout) Error() string

type ErrRunnerNotImplemented added in v0.38.0

type ErrRunnerNotImplemented struct {
	Runtime string
}

ErrRunnerNotImplemented indicates the feature is not available for the requested runtime.

func (ErrRunnerNotImplemented) Error added in v0.38.0

func (e ErrRunnerNotImplemented) Error() string

type ErrRuntimeNotRecognized added in v0.38.0

type ErrRuntimeNotRecognized struct {
	Runtime string
}

ErrRuntimeNotRecognized indicates a runtime which is not in the set of those known.

func (ErrRuntimeNotRecognized) Error added in v0.38.0

func (e ErrRuntimeNotRecognized) Error() string

type Function

type Function struct {
	// SpecVersion at which this function is known to be compatible.
	// More specifically, it is the highest migration which has been applied.
	// For details see the .Migrated() and .Migrate() methods.
	SpecVersion string `yaml:"specVersion"` // semver format

	// Root on disk at which to find/create source and config files.
	Root string `yaml:"-"`

	// Name of the function.
	Name string `yaml:"name,omitempty" jsonschema:"pattern=^[a-z0-9]([-a-z0-9]*[a-z0-9])?$"`

	// Domain of the function optionally specifies the domain to use as the
	// route of the function. By default the cluster's default will be used.
	// Note that the value defined here must be one which the cluster is
	// configured to recognize, or this will have no effect and the cluster
	// default will be applied.  This value shuld therefore ideally be
	// validated by the client.
	Domain string `yaml:"domain,omitempty"`

	// Runtime is the language plus context.  nodejs|go|quarkus|rust etc.
	Runtime string `yaml:"runtime,omitempty"`

	// Template for the function.
	Template string `yaml:"-"`

	// Registry at which to store interstitial containers, in the form
	// [registry]/[user].
	Registry string `yaml:"registry,omitempty"`

	// Image is the full OCI image tag in form:
	//   [registry]/[namespace]/[name]:[tag]
	// example:
	//   quay.io/alice/my.function.name
	// Registry is optional and is defaulted to DefaultRegistry
	// example:
	//   alice/my.function.name
	// If Image is provided, it overrides the default of concatenating
	// "Registry+Name:latest" to derive the Image.
	Image string `yaml:"image,omitempty"`

	// ImageDigest is the SHA256 hash of the latest image that has been built
	ImageDigest string `yaml:"imageDigest,omitempty"`

	// Created time is the moment that creation was successfully completed
	// according to the client which is in charge of what constitutes being
	// fully "Created" (aka initialized)
	Created time.Time `yaml:"created"`

	// Invoke defines hints for use when invoking this function.
	// See Client.Invoke for usage.
	Invoke string `yaml:"invoke,omitempty" jsonschema:"enum=http,enum=cloudevent"`

	// Build defines the build properties for a function
	Build BuildSpec `yaml:"build,omitempty"`

	// Run defines the runtime properties for a function
	Run RunSpec `yaml:"run,omitempty"`

	// Deploy defines the deployment properties for a function
	Deploy DeploySpec `yaml:"deploy,omitempty"`

	Local Local `yaml:"-"`
}

Function

func NewFunction

func NewFunction(root string) (f Function, err error)

NewFunction from a given path. Invalid paths, or no function at path are errors. Syntactic errors are returned immediately (yaml unmarshal errors). Functions which are syntactically valid are also then logically validated. Functions from earlier versions are brought up to current using migrations. Migrations are run prior to validators such that validation can omit concerning itself with backwards compatibility. Migrators must therefore selectively consider the minimal validation necessary to enable migration.

func NewFunctionWith

func NewFunctionWith(defaults Function) Function

NewFunctionWith defaults as provided.

func (Function) BuildStamp

func (f Function) BuildStamp() string

BuildStamp accesses the current (last) build stamp for the function. Unbuilt functions return empty string.

func (Function) Built

func (f Function) Built() bool

Built returns true if the function is considered built. Note that this only considers the function as it exists on-disk at f.Root.

func (Function) ImageName

func (f Function) ImageName() (image string, err error)

ImageName returns a full image name (OCI container tag) for the Function based off of the Function's `Registry` member plus `Name`. Used to calculate the final value for .Image when none is provided explicitly.

form: [registry]/[user]/[function]:latest example: quay.io/alice/my.function.name:latest

Also nested namespaces should be supported: form: [registry]/[parent]/[user]/[function]:latest example: quay.io/project/alice/my.function.name:latest

Registry values which only contain a single token are presumed to indicate the namespace at the default registry.

func (Function) ImageWithDigest

func (f Function) ImageWithDigest() string

ImageWithDigest returns the full reference to the image including SHA256 Digest. If Digest is empty, image:tag is returned. TODO: Populate this only on a successful deploy, as this results on a dirty git tree on every build.

func (Function) Initialized

func (f Function) Initialized() bool

Initialized returns if the function has been initialized. Any errors are considered failure (invalid or inaccessible root, config file, etc).

func (Function) LabelsMap

func (f Function) LabelsMap() (map[string]string, error)

LabelsMap combines default labels with the labels slice provided. It will the resulting slice with ValidateLabels and return a key/value map.

  • key: EXAMPLE1 # Label directly from a value value: value1
  • key: EXAMPLE2 # Label from the local ENV var value: {{ env:MY_ENV }}

func (Function) Migrate

func (f Function) Migrate() (migrated Function, err error)

Migrate applies any necessary migrations, returning a new migrated version of the function. It is the caller's responsibility to .Write() the function to persist to disk.

func (Function) Migrated

func (f Function) Migrated() bool

Migrated returns whether the function has been migrated to the highest level the currently executing system is aware of (or beyond). returns true.

func (Function) Stamp added in v0.38.0

func (f Function) Stamp(oo ...stampOption) (err error)

Stamp a function as being built.

This is a performance optimization used when updates to the function are known to have no effect on its built container. This stamp is checked before certain operations, and if it has been updated, the build can be skuipped. If in doubt, just use .Write only.

Updates the build stamp at ./func/built (and the log at .func/built.log) to reflect the current state of the filesystem. Note that the caller should call .Write first to flush any changes to the function in-memory to the filesystem prior to calling stamp.

The runtime data directory .func is created in the function root if necessary.

func (Function) Validate

func (f Function) Validate() error

Validate function is logically correct, returning a bundled, and quite verbose, formatted error detailing any issues.

func (Function) Write

func (f Function) Write() (err error)

Write Function struct (metadata) to Disk at f.Root

type Git

type Git struct {
	URL        string `yaml:"url,omitempty"`
	Revision   string `yaml:"revision,omitempty"`
	ContextDir string `yaml:"contextDir,omitempty"`
}

type HealthEndpoints

type HealthEndpoints struct {
	Liveness  string `yaml:"liveness,omitempty"`
	Readiness string `yaml:"readiness,omitempty"`
}

HealthEndpoints specify the liveness and readiness endpoints for a Runtime

type Instance

type Instance struct {
	// Route is the primary route of a function instance.
	Route string
	// Routes is the primary route plus any other route at which the function
	// can be contacted.
	Routes        []string       `json:"routes" yaml:"routes"`
	Name          string         `json:"name" yaml:"name"`
	Image         string         `json:"image" yaml:"image"`
	Namespace     string         `json:"namespace" yaml:"namespace"`
	Subscriptions []Subscription `json:"subscriptions" yaml:"subscriptions"`
}

Instance data about the runtime state of a function in a given environment.

A function instance is a logical running function space, which share a unique route (or set of routes). Due to autoscaling and load balancing, there is a one to many relationship between a given route and processes. By default the system creates the 'local' and 'remote' named instances when a function is run (locally) and deployed, respectively. See the .InstanceRefs(f) accessor for the map of named environments to these function information structures.

type InstanceRefs

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

InstanceRefs manager

InstanceRefs are point-in-time snapshots of a function's runtime state in a given environment. By default 'local' and 'remote' environmnts are available when a function is run locally and deployed (respectively).

func (*InstanceRefs) Get

func (s *InstanceRefs) Get(ctx context.Context, f Function, environment string) (Instance, error)

Get the instance data for a function in the named environment. For convenient access to the default 'local' and 'remote' environment see the Local and Remote methods, respectively. Instance returned is populated with a point-in-time snapshot of the function state in the named environment.

func (*InstanceRefs) Local

func (s *InstanceRefs) Local(ctx context.Context, f Function) (Instance, error)

Local instance details for the function If the function is not running locally the error returned is ErrNotRunning

func (*InstanceRefs) Remote

func (s *InstanceRefs) Remote(ctx context.Context, name, root string) (Instance, error)

Remote instance details for the function

Since this is specific to the implicitly available 'remote' environment, the request can be completed with either a name or the local source. Therefore either name or root path can be passed. If name is not passed, the function at root is loaded and its name used for describing the remote instance. Name takes precedence.

type InvokeMessage

type InvokeMessage struct {
	ID          string
	Source      string
	Type        string
	ContentType string
	Data        string
	Format      string //optional override for function-defined message format
}

InvokeMesage is the message used by the convenience method Invoke to provide a simple way to trigger the execution of a function during development.

func NewInvokeMessage

func NewInvokeMessage() InvokeMessage

NewInvokeMessage creates a new InvokeMessage with fields populated

type Job

type Job struct {
	Function Function
	Host     string
	Port     string
	Errors   chan error
	// contains filtered or unexported fields
}

Job represents a running function job (presumably started by this process' Runner instance. In order for this to function along with the noop runner used by client, the zero value of the struct is set up to noop without errors.

func NewJob

func NewJob(f Function, host, port string, errs chan error, onStop func() error, verbose bool) (j *Job, err error)

Create a new Job which represents a running function task by providing the port on which it was started, a channel on which runtime errors can be received, and a stop function.

func (*Job) Dir added in v0.38.0

func (j *Job) Dir() string

Directory within which all data about this current job is placed. ${f.Root}/.func/runs/${j.Port}

func (*Job) Stop

func (j *Job) Stop() error

Stop the Job, running the provided stop delegate and removing runtime metadata from disk.

type KnativeSubscription added in v0.40.0

type KnativeSubscription struct {
	Source  string            `yaml:"source"`
	Filters map[string]string `yaml:"filters,omitempty"`
}

KnativeSubscription

type Label

type Label struct {
	// Key consist of optional prefix part (ended by '/') and name part
	// Prefix part validation pattern: [a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*
	// Name part validation pattern: ([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9]
	Key   *string `` /* 144-byte string literal not displayed */
	Value *string `yaml:"value,omitempty" jsonschema:"pattern=^(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])?$"`
}

func (Label) String

func (l Label) String() string

type ListItem

type ListItem struct {
	Name      string `json:"name" yaml:"name"`
	Namespace string `json:"namespace" yaml:"namespace"`
	Runtime   string `json:"runtime" yaml:"runtime"`
	URL       string `json:"url" yaml:"url"`
	Ready     string `json:"ready" yaml:"ready"`
}

type Lister

type Lister interface {
	// List the functions currently deployed.
	List(ctx context.Context) ([]ListItem, error)
}

Lister of deployed functions.

type Local added in v0.40.0

type Local struct {
	// Remote indicates the deployment (and possibly build) process are to
	// be triggered in a remote environment rather than run locally.
	Remote bool `yaml:"remote,omitempty"`
}

Local represents the transient runtime metadata which is only relevant to the local copy of the function

type Option

type Option func(*Client)

Option defines a function which when passed to the Client constructor optionally mutates private members at time of instantiation.

func WithBuilder

func WithBuilder(d Builder) Option

WithBuilder provides the concrete implementation of a builder.

func WithDNSProvider

func WithDNSProvider(provider DNSProvider) Option

WithDNSProvider proivdes a DNS provider implementation for registering the effective DNS name which is either explicitly set via WithName or is derived from the root path.

func WithDeployer

func WithDeployer(d Deployer) Option

WithDeployer provides the concrete implementation of a deployer.

func WithDescriber

func WithDescriber(describer Describer) Option

WithDescriber provides a concrete implementation of a function describer.

func WithLister

func WithLister(l Lister) Option

WithLister provides the concrete implementation of a lister.

func WithPipelinesProvider

func WithPipelinesProvider(pp PipelinesProvider) Option

WithPipelinesProvider sets implementation of provider responsible for CI/CD pipelines

func WithPusher

func WithPusher(d Pusher) Option

WithPusher provides the concrete implementation of a pusher.

func WithRegistry

func WithRegistry(registry string) Option

WithRegistry sets the default registry which is consulted when an image name is not explicitly provided. Can be fully qualified, including the registry and namespace (ex: 'quay.io/myname') or simply the namespace (ex: 'myname').

func WithRemover

func WithRemover(r Remover) Option

WithRemover provides the concrete implementation of a remover.

func WithRepositoriesPath

func WithRepositoriesPath(path string) Option

WithRepositoriesPath sets the location on disk to use for extensible template repositories. Extensible template repositories are additional templates that exist on disk and are not built into the binary.

func WithRepository

func WithRepository(uri string) Option

WithRepository sets a specific URL to a Git repository from which to pull templates. This setting's existence precldes the use of either the inbuilt templates or any repositories from the extensible repositories path.

func WithRunner

func WithRunner(r Runner) Option

WithRunner provides the concrete implementation of a deployer.

func WithStartTimeout added in v0.38.0

func WithStartTimeout(t time.Duration) Option

WithStartTimeout sets a custom default timeout for functions which do not define their own. This is useful in situations where the client is operating in a restricted environment and all functions tend to take longer to start up than usual, or when the client is running functions which in general take longer to start. If a timeout is specified on the function itself, that will take precidence. Use the RunWithTimeout option on the Run method to specify a timeout with precidence.

func WithTransport

func WithTransport(t http.RoundTripper) Option

WithTransport sets a custom transport to use internally.

func WithVerbose

func WithVerbose(v bool) Option

WithVerbose toggles verbose logging.

type Options

type Options struct {
	Scale     *ScaleOptions     `yaml:"scale,omitempty"`
	Resources *ResourcesOptions `yaml:"resources,omitempty"`
}

type PersistentVolumeClaim added in v0.38.0

type PersistentVolumeClaim struct {
	// claimName is the name of a PersistentVolumeClaim in the same namespace as the pod using this volume.
	// More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#persistentvolumeclaims
	ClaimName *string `yaml:"claimName,omitempty"`
	// readOnly Will force the ReadOnly setting in VolumeMounts.
	// Default false.
	ReadOnly bool `yaml:"readOnly,omitempty"`
}

type PipelinesProvider

type PipelinesProvider interface {
	Run(context.Context, Function) (string, error)
	Remove(context.Context, Function) error
	ConfigurePAC(context.Context, Function, any) error
	RemovePAC(context.Context, Function, any) error
}

PipelinesProvider manages lifecyle of CI/CD pipelines used by a function

type Platform added in v0.38.0

type Platform struct {
	OS           string
	Architecture string
	Variant      string
}

Platform upon which a function may run

type Pusher

type Pusher interface {
	// Push the image of the function.
	// Returns Image Digest - SHA256 hash of the produced image
	Push(ctx context.Context, f Function) (string, error)
}

Pusher of function image to a registry.

type Remover

type Remover interface {
	// Remove the function from remote.
	Remove(ctx context.Context, name string) error
}

Remover of deployed services.

type Repositories

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

Repositories manager

func (*Repositories) Add

func (r *Repositories) Add(name, uri string) (string, error)

Add a repository of the given name from the URI. Name, if not provided, defaults to the repo name (sans optional .git suffix). Returns the final name as added.

func (*Repositories) All

func (r *Repositories) All() (repos []Repository, err error)

All repositories under management The default repository is always first. If a path to custom repositories is defined, these are included next. If repositories is in single-repo mode, it will be the only repo returned.

func (*Repositories) Get

func (r *Repositories) Get(name string) (repo Repository, err error)

Get a repository by name, error if it does not exist.

func (*Repositories) List

func (r *Repositories) List() ([]string, error)

List all repositories the current configuration of the repo manager has defined.

func (*Repositories) Path

func (r *Repositories) Path() string

Path returns the currently active repositories path under management. Blank indicates that the system was not instantiated to use any repositories on disk.

func (*Repositories) Remove

func (r *Repositories) Remove(name string) error

Remove a repository of the given name from the repositories. (removes its directory in Path)

func (*Repositories) Rename

func (r *Repositories) Rename(from, to string) error

Rename a repository

type Repository

type Repository struct {
	// Name of the repository
	// This can be for instance:
	// directory name on FS or last part of git URL or arbitrary value defined by the Template author.
	Name string
	// Runtimes containing Templates loaded from the repo
	Runtimes []Runtime
	// contains filtered or unexported fields
}

Repository represents a collection of runtimes, each containing templates.

func NewRepository

func NewRepository(name, uri string) (r Repository, err error)

NewRepository creates a repository instance from any of: a path on disk, a remote or local URI, or from the embedded default repo if uri not provided. Name (optional), if provided takes precedence over name derived from repo at the given URI.

uri (optional), the path either locally or remote from which to load the repository files. If not provided, the internal default is assumed.

func (Repository) FS added in v0.38.0

FS returns the underlying filesystem of this repository.

func (*Repository) Runtime

func (r *Repository) Runtime(name string) (runtime Runtime, err error)

Runtime of the given name within the repository.

func (*Repository) Template

func (r *Repository) Template(runtimeName, name string) (t Template, err error)

Template from repo for given runtime.

func (*Repository) Templates

func (r *Repository) Templates(runtimeName string) ([]Template, error)

Templates returns the set of all templates for a given runtime. If runtime not found, an empty list is returned.

func (*Repository) URL

func (r *Repository) URL() string

URL attempts to read the remote git origin URL of the repository. Best effort; returns empty string if the repository is not a git repo or the repo has been mutated beyond recognition on disk (ex: removing the origin remote)

func (*Repository) Write

func (r *Repository) Write(dest string) (err error)

Write all files in the repository to the given path.

type ResourcesLimitsOptions

type ResourcesLimitsOptions struct {
	CPU         *string `yaml:"cpu,omitempty" jsonschema:"pattern=^([+-]?[0-9.]+)([eEinumkKMGTP]*[-+]?[0-9]*)$"`
	Memory      *string `yaml:"memory,omitempty" jsonschema:"pattern=^([+-]?[0-9.]+)([eEinumkKMGTP]*[-+]?[0-9]*)$"`
	Concurrency *int64  `yaml:"concurrency,omitempty" jsonschema_extras:"minimum=0"`
}

type ResourcesOptions

type ResourcesOptions struct {
	Requests *ResourcesRequestsOptions `yaml:"requests,omitempty"`
	Limits   *ResourcesLimitsOptions   `yaml:"limits,omitempty"`
}

type ResourcesRequestsOptions

type ResourcesRequestsOptions struct {
	CPU    *string `yaml:"cpu,omitempty" jsonschema:"pattern=^([+-]?[0-9.]+)([eEinumkKMGTP]*[-+]?[0-9]*)$"`
	Memory *string `yaml:"memory,omitempty" jsonschema:"pattern=^([+-]?[0-9.]+)([eEinumkKMGTP]*[-+]?[0-9]*)$"`
}

type RunOption added in v0.38.0

type RunOption func(c *RunOptions)

func RunWithStartTimeout added in v0.38.0

func RunWithStartTimeout(t time.Duration) RunOption

RunWithStartTimeout sets a specific timeout for this run request to start. If not provided, the client's run timeout (set by default to DefaultRunTimeout and configurable via the WithRunTimeout client instantiation option) is used.

type RunOptions added in v0.38.0

type RunOptions struct {
	StartTimeout time.Duration
}

type RunSpec

type RunSpec struct {
	// List of volumes to be mounted to the function
	Volumes []Volume `yaml:"volumes,omitempty"`

	// Env variables to be set
	Envs Envs `yaml:"envs,omitempty"`

	// StartTimeout specifies that this function should have a custom timeout
	// when starting. This setting is currently respected by the host runner,
	// with containerized docker runner and deployed Knative service integration
	// in development.
	StartTimeout time.Duration `yaml:"startTimeout,omitempty"`
}

RunSpec

type Runner

type Runner interface {
	// Run the function, returning a Job with metadata, error channels, and
	// a stop function.  The process can be stopped by running the returned stop
	// function, either on context cancellation or in a defer.
	// The duration is the time to wait for the job to start.
	Run(context.Context, Function, time.Duration) (*Job, error)
}

Runner runs the function locally.

type Runtime

type Runtime struct {
	// Name of the runtime
	Name string
	// Templates defined for the runtime
	Templates []Template
}

Runtime is a division of templates within a repository of templates for a given runtime (source language plus environmentally available services and libraries)

type ScaleOptions

type ScaleOptions struct {
	Min         *int64   `yaml:"min,omitempty" jsonschema_extras:"minimum=0"`
	Max         *int64   `yaml:"max,omitempty" jsonschema_extras:"minimum=0"`
	Metric      *string  `yaml:"metric,omitempty" jsonschema:"enum=concurrency,enum=rps"`
	Target      *float64 `yaml:"target,omitempty" jsonschema_extras:"minimum=0.01"`
	Utilization *float64 `yaml:"utilization,omitempty" jsonschema:"minimum=1,maximum=100"`
}

type Status

type Status int

Status of the function from the DeploymentResult

const (
	Failed Status = iota
	Deployed
	Updated
)

type Subscription

type Subscription struct {
	Source string `json:"source" yaml:"source"`
	Type   string `json:"type" yaml:"type"`
	Broker string `json:"broker" yaml:"broker"`
}

Subscriptions currently active to event sources

type Template

type Template interface {
	// Name of this template.
	Name() string
	// Runtime for which this template applies.
	Runtime() string
	// Repository within which this template is contained.  Value is set to the
	// currently effective name of the repository, which may vary. It is user-
	// defined when the repository is added, and can be set to "default" when
	// the client is loaded in single repo mode. I.e. not canonical.
	Repository() string
	// Fullname is a calculated field of [repo]/[name] used
	// to uniquely reference a template which may share a name
	// with one in another repository.
	Fullname() string
	// Write updates fields of function f and writes project files to path pointed by f.Root.
	Write(ctx context.Context, f *Function) error
}

Template is a function project template. It can be used to instantiate new function project.

type Templates

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

Templates Manager

func (*Templates) Get

func (t *Templates) Get(runtime, fullname string) (Template, error)

Template returns the named template in full form '[repo]/name' for the specified runtime. Templates from the default repository do not require the repo name prefix, though it can be provided.

func (*Templates) List

func (t *Templates) List(runtime string) ([]string, error)

List the full name of templates available for the runtime. Full name is the optional repository prefix plus the template's repository local name. Default templates grouped first sans prefix.

func (*Templates) Write

func (t *Templates) Write(f *Function) error

Write a function's template to disk. Returns a function which may have been modified dependent on the content of the template (which can define default function fields, builders, buildpacks, etc)

type Volume

type Volume struct {
	Secret                *string                `yaml:"secret,omitempty" jsonschema:"oneof_required=secret"`
	ConfigMap             *string                `yaml:"configMap,omitempty" jsonschema:"oneof_required=configmap"`
	PersistentVolumeClaim *PersistentVolumeClaim `yaml:"persistentVolumeClaim,omitempty" jsonschema:"oneof_required=persistentVolumeClaim"`
	EmptyDir              *EmptyDir              `yaml:"emptyDir,omitempty" jsonschema:"oneof_required=emptyDir"`
	Path                  *string                `yaml:"path,omitempty"`
}

func (Volume) String

func (v Volume) String() string

Jump to

Keyboard shortcuts

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