Documentation ¶
Index ¶
- Constants
- Variables
- func FilesystemFromRepo(uri string) (filesystem.Filesystem, error)
- func Fingerprint(root string) (hash, log string, err error)
- func Interpolate(ee []Env) (map[string]string, error)
- func LastSpecVersion() string
- func NewErrNotInitialized(path string) error
- func RepositoriesPath() string
- func ValidateBuildEnvs(envs []Env) (errors []string)
- func ValidateEnvs(envs []Env) (errors []string)
- func ValidateLabels(labels []Label) (errors []string)
- func WithStampJournal() stampOption
- type BuildConfig
- type BuildOption
- type BuildOptions
- type BuildSpec
- type Builder
- type Client
- func (c *Client) Apply(ctx context.Context, f Function) (string, Function, error)
- func (c *Client) Build(ctx context.Context, f Function, options ...BuildOption) (Function, error)
- func (c *Client) ConfigurePAC(ctx context.Context, f Function, metadata any) error
- func (c *Client) Deploy(ctx context.Context, f Function, oo ...DeployOption) (Function, error)
- func (c *Client) Describe(ctx context.Context, name, namespace string, f Function) (d Instance, err error)
- func (c *Client) Init(cfg Function) (Function, error)
- func (c *Client) Instances() *InstanceRefs
- func (c *Client) Invoke(ctx context.Context, root string, target string, m InvokeMessage) (metadata map[string][]string, body string, err error)
- func (c *Client) List(ctx context.Context, namespace string) ([]ListItem, error)
- func (c *Client) New(ctx context.Context, cfg Function) (string, Function, error)
- func (c *Client) Push(ctx context.Context, f Function) (Function, bool, error)
- func (c *Client) Registry() string
- func (c *Client) Remove(ctx context.Context, name, namespace string, f Function, all bool) error
- func (c *Client) RemovePAC(ctx context.Context, f Function, metadata any) error
- func (c *Client) Repositories() *Repositories
- func (c *Client) RepositoriesPath() (path string)
- func (c *Client) Route(ctx context.Context, f Function) (string, Function, error)
- func (c *Client) Run(ctx context.Context, f Function, options ...RunOption) (job *Job, err error)
- func (c *Client) RunPipeline(ctx context.Context, f Function) (string, Function, error)
- func (c *Client) Runtimes() ([]string, error)
- func (c *Client) Scaffold(ctx context.Context, f Function, dest string) (err error)
- func (c *Client) Templates() *Templates
- func (c *Client) Update(ctx context.Context, f Function) (string, Function, error)
- type DNSProvider
- type DeployOption
- type DeployOptions
- type DeploySpec
- type Deployer
- type DeploymentResult
- type Describer
- type EmptyDir
- type Env
- type Envs
- type ErrNotInitialized
- type ErrRunTimeout
- type ErrRunnerNotImplemented
- type ErrRuntimeNotRecognized
- type Function
- func (f Function) BuildStamp() string
- func (f Function) Built() bool
- func (f Function) ImageName() (image string, err error)
- func (f Function) ImageNameWithDigest(newDigest string) string
- func (f Function) Initialized() bool
- func (f Function) LabelsMap() (map[string]string, error)
- func (f Function) Migrate() (migrated Function, err error)
- func (f Function) Migrated() bool
- func (f Function) Stamp(oo ...stampOption) (err error)
- func (f Function) Validate() error
- func (f Function) Write() (err error)
- func (f Function) WriteRuntimeBuiltImage(verbose bool) error
- type Git
- type HealthEndpoints
- type Instance
- type InstanceRefs
- type InvokeMessage
- type Job
- type KnativeSubscription
- type Label
- type ListItem
- type Lister
- type Local
- type Option
- func WithBuilder(d Builder) Option
- func WithDNSProvider(provider DNSProvider) Option
- func WithDeployer(d Deployer) Option
- func WithDescriber(describer Describer) Option
- func WithLister(l Lister) Option
- func WithPipelinesProvider(pp PipelinesProvider) Option
- func WithPusher(d Pusher) Option
- func WithRegistry(registry string) Option
- func WithRemover(r Remover) Option
- func WithRepositoriesPath(path string) Option
- func WithRepository(uri string) Option
- func WithRunner(r Runner) Option
- func WithStartTimeout(t time.Duration) Option
- func WithTransport(t http.RoundTripper) Option
- func WithVerbose(v bool) Option
- type Options
- type PersistentVolumeClaim
- type PipelinesProvider
- type Platform
- type PushPasswordKey
- type PushTokenKey
- type PushUsernameKey
- type Pusher
- type Remover
- type Repositories
- func (r *Repositories) Add(name, uri string) (string, error)
- func (r *Repositories) All() (repos []Repository, err error)
- func (r *Repositories) Get(name string) (repo Repository, err error)
- func (r *Repositories) List() ([]string, error)
- func (r *Repositories) Path() string
- func (r *Repositories) Remove(name string) error
- func (r *Repositories) Rename(from, to string) error
- type Repository
- func (r Repository) FS() filesystem.Filesystem
- func (r *Repository) Runtime(name string) (runtime Runtime, err error)
- func (r *Repository) Template(runtimeName, name string) (t Template, err error)
- func (r *Repository) Templates(runtimeName string) ([]Template, error)
- func (r *Repository) URL() string
- func (r *Repository) Write(dest string) (err error)
- type ResourcesLimitsOptions
- type ResourcesOptions
- type ResourcesRequestsOptions
- type RunOption
- type RunOptions
- type RunSpec
- type Runner
- type Runtime
- type ScaleOptions
- type Status
- type Subscription
- type Template
- type Templates
- type Volume
Constants ¶
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 )
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" // BuiltHash is a name of a file that holds hash of built Function in runtime // metadata dir (RunDataDir) BuiltHash = "built-hash" // BuiltImage is a name of a file that holds name of built image in runtime // metadata dir (RunDataDir) BuiltImage = "built-image" )
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) )
const ( EnvironmentLocal = "local" EnvironmentRemote = "remote" )
const ( DefaultInvokeSource = "/boson/fn" DefaultInvokeType = "boson.fn" DefaultInvokeContentType = "application/json" DefaultInvokeData = `{"message":"Hello World"}` DefaultInvokeFormat = "http" )
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" )
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 ¶
var ( ErrEnvironmentNotFound = errors.New("environment not found") ErrFunctionNotFound = errors.New("function not found") ErrMismatchedName = errors.New("name passed the function source") ErrNameRequired = errors.New("name required") ErrNamespaceRequired = errors.New("namespace 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") )
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"}, } )
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
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 ¶
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 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 ¶
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 ¶
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 ¶
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"` // Image stores last built image name NOT in func.yaml, but instead // in .func/built-image Image string `yaml:"-"` }
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 (*Client) Apply ¶
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 ¶
Build the function at path. Errors if the function is either unloadable or does not contain a populated Image.
func (*Client) ConfigurePAC ¶
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 ¶
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, namespace string, f Function) (d Instance, err error)
Describe a function. Name/Namespace takes precedence if provided. If no name/namespace is provided, the function passed is described based off of its name and currently deployed namespace.
func (*Client) Init ¶
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) 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 ¶
List currently deployed functions. If namespace is empty, the static implementation of the current "Lister" is used, which for example with the knative lister defaults to using the current kubernetes context namespace, falling back to the static default "namespace".
func (*Client) New ¶
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 ¶
Push the image for the named service to the configured registry returns in this order: 1)Function structure 2)bool indicating if push succeeded 3) error
func (*Client) Registry ¶
Repository accessor returns the default registry for use when building Functions which do not specify Registry or Image name explicitly.
func (*Client) Remove ¶
Remove a function. Name takes precedence. If no name is provided, the function defined at root is used if it exists. If calling this directly namespace must be provided in .Deploy.Namespace field except when using mocks in which case empty namespace is accepted because its existence is checked in the sub functions remover.Remove and pipilines.Remove
func (*Client) RemovePAC ¶
RemovePAC deletes generated Pipeline as Code resources on the local filesystem and on the cluster
func (*Client) RepositoriesPath ¶
RepositoriesPath accesses the currently effective repositories path, which can be set using the WithRepositoriesPath option.
func (*Client) Route ¶
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 ¶
Run the function whose code resides at root. On start, the chosen port is sent to the provided started channel
func (*Client) RunPipeline ¶
RunPipeline runs a Pipeline to build and deploy the function. Returned function contains applicable registry and deployed image name. String is the default route.
func (*Client) Runtimes ¶
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
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.
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 *DeployOptions)
func WithDeploySkipBuildCheck ¶
func WithDeploySkipBuildCheck(skipBuiltCheck bool) DeployOption
type DeployOptions ¶ added in v0.42.0
type DeployOptions struct {
// contains filtered or unexported fields
}
type DeploySpec ¶
type DeploySpec struct { // Namespace into which the function was deployed on supported platforms. Namespace string `yaml:"namespace,omitempty"` // Image is the deployed image including sha256 Image string `yaml:"image,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 Describer ¶
type Describer interface { // Describe the named function in the remote environment. Describe(ctx context.Context, name, namespace 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 ¶
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
type Envs ¶ added in v0.38.0
type Envs []Env
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
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"` // Namespace in which to deploy the Function Namespace string `yaml:"namespace,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 ¶
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 ¶
NewFunctionWith defaults as provided.
func (Function) BuildStamp ¶
BuildStamp accesses the current (last) build stamp for the function. Unbuilt functions return empty string.
func (Function) Built ¶
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 ¶
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 .Deploy.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) ImageNameWithDigest ¶ added in v0.41.0
ImageNameWithDigest works with f.Build.Image and image digest. if the func parameter newDigest is empty, just return the image name as is. TODO: This function is a temporary one for a workaround for a current solution on how the image digest is fetched (which is during/after Push). Image digest should be gotten from imageID right after building the Function. PS: I think that imageID item contains "sha256:[digest]"
func (Function) Initialized ¶
Initialized returns if the function has been initialized. Any errors are considered failure (invalid or inaccessible root, config file, etc).
func (Function) LabelsMap ¶
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 ¶
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 ¶
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
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 ¶
Validate function is logically correct, returning a bundled, and quite verbose, formatted error detailing any issues.
func (Function) WriteRuntimeBuiltImage ¶ added in v0.41.0
WriteRuntimeBuiltImage writes built image name into runtime metadata directory (.func/) from f.Build.Image
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 ¶
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 ¶
Local instance details for the function If the function is not running locally the error returned is ErrNotRunning
func (*InstanceRefs) Remote ¶
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.
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])?$"` }
type Lister ¶
type Lister interface { // List the functions currently deployed. List(ctx context.Context, namespace string) ([]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 ¶
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 ¶
WithDeployer provides the concrete implementation of a deployer.
func WithDescriber ¶
WithDescriber provides a concrete implementation of a function describer.
func WithLister ¶
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 ¶
WithPusher provides the concrete implementation of a pusher.
func WithRegistry ¶
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 ¶
WithRemover provides the concrete implementation of a remover.
func WithRepositoriesPath ¶
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 ¶
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 ¶
WithRunner provides the concrete implementation of a deployer.
func WithStartTimeout ¶ added in v0.38.0
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.
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, Function, 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 PushPasswordKey ¶ added in v0.41.0
type PushPasswordKey struct{}
PushPasswordKey is a type available for use as a context key for providing a basic auth password to pushers which support this method.
type PushTokenKey ¶ added in v0.41.0
type PushTokenKey struct{}
PushTokenKey is a type available for use as a context key for providing a token (for example a jwt bearer token) to pushers which support this method.
type PushUsernameKey ¶ added in v0.41.0
type PushUsernameKey struct{}
PushUsernameKey is a type available for use to communicate a basic authentication username to pushers which support this method.
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, namespace 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
func (r Repository) FS() filesystem.Filesystem
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 RunOption ¶ added in v0.38.0
type RunOption func(c *RunOptions)
func RunWithStartTimeout ¶ added in v0.38.0
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 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 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 ¶
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.
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"` }