server

package
v0.3.750 Latest Latest
Warning

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

Go to latest
Published: May 16, 2023 License: Apache-2.0 Imports: 51 Imported by: 34

Documentation

Index

Constants

View Source
const (

	// EnvLogFormat sets the stderr logging format, text or json only
	EnvLogFormat = "FN_LOG_FORMAT"

	// EnvLogLevel sets the stderr logging level
	EnvLogLevel = "FN_LOG_LEVEL"

	// EnvLogDest is a url of a log destination:
	// possible schemes: { udp, tcp, file }
	// file url must contain only a path, syslog must contain only a host[:port]
	// expect: [scheme://][host][:port][/path]
	// default scheme to udp:// if none given
	EnvLogDest = "FN_LOG_DEST"

	// EnvLogPrefix is a prefix to affix to each log line.
	EnvLogPrefix = "FN_LOG_PREFIX"

	// EnvDBURL is a url to a db service:
	// possible schemes: { postgres, sqlite3, mysql }
	EnvDBURL = "FN_DB_URL"

	// EnvRunnerURL is a url pointing to an Fn API service.
	EnvRunnerURL = "FN_RUNNER_API_URL"

	// EnvRunnerAddresses is a list of runner urls for an lb to use.
	EnvRunnerAddresses = "FN_RUNNER_ADDRESSES"

	// EnvPublicLoadBalancerURL is the url to inject into trigger responses to get a public url.
	EnvPublicLoadBalancerURL = "FN_PUBLIC_LB_URL"

	// EnvNodeType defines the runtime mode for fn to run in, options
	// are one of: { full, api, lb, runner, pure-runner }
	EnvNodeType = "FN_NODE_TYPE"

	// EnvPort is the port to listen on for fn http server.
	EnvPort = "FN_PORT" // be careful, Gin expects this variable to be "port"

	// EnvGRPCPort is the port to run the grpc server on for a pure-runner node.
	EnvGRPCPort = "FN_GRPC_PORT"

	// EnvAPICORSOrigins is the list of CORS origins to allow.
	EnvAPICORSOrigins = "FN_API_CORS_ORIGINS"

	// EnvAPICORSHeaders is the list of CORS headers allowed.
	EnvAPICORSHeaders = "FN_API_CORS_HEADERS"

	// EnvZipkinURL is the url of a zipkin node to send traces to.
	EnvZipkinURL = "FN_ZIPKIN_URL"

	// EnvJaegerURL is the url of a jaeger node to send traces to.
	EnvJaegerURL = "FN_JAEGER_URL"

	// EnvRIDHeader is the header name of the incoming request which holds the request ID
	EnvRIDHeader = "FN_RID_HEADER"

	// EnvProcessCollectorList is the list of procid's to collect metrics for.
	EnvProcessCollectorList = "FN_PROCESS_COLLECTOR_LIST"

	// EnvLBPlacementAlg is the algorithm to place fn calls to fn runners in lb.[0w
	EnvLBPlacementAlg = "FN_PLACER"

	// EnvMaxRequestSize sets the limit in bytes for any API request body's length.
	EnvMaxRequestSize = "FN_MAX_REQUEST_SIZE"

	// EnvMaxHeaderSize sets the limit in bytes for any API request body's length.
	EnvMaxHeaderSize = "FN_MAX_REQUEST_HEADER_SIZE"

	// EnvReadTimeout sets the timeout limit for reading a http request body.
	EnvReadTimeout = "FN_REQUEST_BODY_READ_TIMEOUT"

	// EnvReadHeaderTimeout sets the timeout limit for reading a http request header.
	EnvReadHeaderTimeout = "FN_REQUEST_HEADER_READ_TIMEOUT"

	// EnvWriteTimeout sets the timeout limit for writing a http response.
	EnvWriteTimeout = "FN_RESPONSE_WRITE_TIMEOUT"

	// EnvHTTPIdleTimeout maximum amount of time to wait for the next request.
	EnvHTTPIdleTimeout = "FN_HTTP_IDLE_TIMEOUT"

	// DefaultLogFormat is text
	DefaultLogFormat = "text"

	// DefaultLogLevel is info
	DefaultLogLevel = "info"

	// DefaultLogDest is stderr
	DefaultLogDest = "stderr"

	// DefaultPort is 8080
	DefaultPort = 8080

	// DefaultGRPCPort is 9190
	DefaultGRPCPort = 9190
)
View Source
const (
	// For backwards compat, TLS-prefix configuration-keys:
	TLSGRPCServer  = "gRPCServer"
	TLSAdminServer = "AdminServer"
	TLSWebServer   = "WebServer"

	AdminServer = "AdminServer"
	WebServer   = "WebServer"
	GRPCServer  = "gRPCServer"
)

Configuration keys to identify grpc, admin, web services:

Variables

View Source
var (
	APIViewsGetPath = DefaultAPIViewsGetPath
)
View Source
var ErrInternalServerError = errors.New("internal server error")

ErrInternalServerError returned when something exceptional happens.

Functions

func AppIDFromContext

func AppIDFromContext(ctx context.Context) string

AppIDFromContext returns the app from a context, if set.

func ContextWithAppID

func ContextWithAppID(ctx context.Context, appID string) context.Context

func ContextWithFnID

func ContextWithFnID(ctx context.Context, fnID string) context.Context

func DefaultAPIViewsGetPath

func DefaultAPIViewsGetPath(routes gin.RoutesInfo, c *gin.Context) string

func FnIDFromContext

func FnIDFromContext(ctx context.Context) string

FnIDFromContext returns the app from a context, if set.

func HandleErrorResponse

func HandleErrorResponse(ctx context.Context, w http.ResponseWriter, err error)

HandleErrorResponse used to handle response errors in the same way.

func RegisterAPIViews

func RegisterAPIViews(tagKeys []string, dist []float64)

func RegisterExtension

func RegisterExtension(ext fnext.Extension)

RegisterExtension registers the extension so it's available, but does not initialize it. This is generally what third party extensions will use in their init() method.

func WriteError

func WriteError(ctx context.Context, w http.ResponseWriter, statuscode int, err error)

WriteError easy way to do standard error response, but can set statuscode and error message easier than handleErrorResponse

Types

type FnAnnotator

type FnAnnotator interface {
	// Annotates a trigger on read
	AnnotateFn(ctx *gin.Context, a *models.App, fn *models.Fn) (*models.Fn, error)
}

FnAnnotator Is used to inject trigger context (such as request URLs) into outbound trigger resources

func NewRequestBasedFnAnnotator

func NewRequestBasedFnAnnotator() FnAnnotator

NewRequestBasedFnAnnotator creates a FnAnnotator that inspects the incoming request host and port, and uses this to generate fn invoke endpoint URLs based on those

func NewStaticURLFnAnnotator

func NewStaticURLFnAnnotator(baseURL string) FnAnnotator

NewStaticURLFnAnnotator annotates triggers bases on a given, specified URL base - e.g. "https://my.domain" ---> "https://my.domain/t/app/source"

type NodeType

type NodeType int32

NodeType is the mode to run fn in.

const (
	// ServerTypeFull runs all API endpoints, including executing tasks.
	ServerTypeFull NodeType = iota

	// ServerTypeAPI runs only control plane endpoints, to manage resources.
	ServerTypeAPI

	// ServerTypeLB runs only invoke/http trigger endpoints, routing to runner nodes.
	ServerTypeLB

	// ServerTypePureRunner runs only grpc server, to execute tasks.
	ServerTypePureRunner
)

func (NodeType) String

func (s NodeType) String() string

type Option

type Option func(context.Context, *Server) error

Option is a func that allows configuring a Server

func EnableShutdownEndpoint

func EnableShutdownEndpoint(ctx context.Context, halt context.CancelFunc) Option

EnableShutdownEndpoint adds /shutdown to initiate a shutdown of an fn server.

func LimitRequestBody

func LimitRequestBody(max int64) Option

LimitRequestBody wraps every http request to limit its size to the specified max bytes.

func WithAdminEnabled added in v0.3.713

func WithAdminEnabled(enabled bool) Option

WithAdminEnabled enables or disables the Admin server. By default the server is enabled.

func WithAdminServer

func WithAdminServer(port int) Option

WithAdminServer starts the admin server on the specified port.

func WithAgent

func WithAgent(agent agent.Agent) Option

WithAgent allows directly setting an agent

func WithAgentFromEnv

func WithAgentFromEnv() Option

WithAgentFromEnv must be provided as the last server option because it relies on all other options being set first.

func WithDBURL

func WithDBURL(dbURL string) Option

WithDBURL maps EnvDBURL

func WithDatastore

func WithDatastore(ds models.Datastore) Option

WithDatastore allows directly setting a datastore

func WithExtraCtx

func WithExtraCtx(extraCtx context.Context) Option

WithExtraCtx appends a context to the list of contexts the server will watch for cancellations / errors / signals.

func WithFnAnnotator

func WithFnAnnotator(provider FnAnnotator) Option

WithFnAnnotator adds a fnEndpoint provider to the server

func WithFullAgent

func WithFullAgent() Option

WithFullAgent is a shorthand for WithAgent(... create a full agent here ...)

func WithGRPCPort

func WithGRPCPort(port int) Option

WithGRPCPort maps EnvGRPCPort

func WithHTTPConfig

func WithHTTPConfig(service string, cfg *http.Server) Option

WithHTTPConfig allows configuring specific http servers

func WithJaeger

func WithJaeger(jaegerURL string) Option

WithJaeger maps EnvJaegerURL

func WithLogDest

func WithLogDest(dst, prefix string) Option

WithLogDest maps EnvLogDest TODO(deprecate): caller should just call SetLogDest

func WithLogFormat

func WithLogFormat(format string) Option

WithLogFormat maps EnvLogFormat TODO(deprecate): caller should just call SetLogFormat

func WithLogLevel

func WithLogLevel(ll string) Option

WithLogLevel maps EnvLogLevel TODO(deprecate): caller should just call WithLogLevel

func WithPrometheus

func WithPrometheus() Option

WithPrometheus activates the prometheus collection and /metrics endpoint

func WithRIDProvider

func WithRIDProvider(ridProvider *RIDProvider) Option

WithRIDProvider will generate request ids for each http request using the given generator.

func WithReadDataAccess

func WithReadDataAccess(ds agent.ReadDataAccess) Option

WithReadDataAccess overrides the LB read DataAccess for a server

func WithTLS

func WithTLS(service string, tlsCfg *tls.Config) Option

WithTLS configures a service with a provided TLS configuration

func WithTriggerAnnotator

func WithTriggerAnnotator(provider TriggerAnnotator) Option

WithTriggerAnnotator adds a trigggerEndpoint provider to the server

func WithType

func WithType(t NodeType) Option

WithType maps EnvNodeType

func WithWebEnabled added in v0.3.713

func WithWebEnabled(enabled bool) Option

WithWebEnabled enables or disables the web server. By default the server is enabled.

func WithWebPort

func WithWebPort(port int) Option

WithWebPort maps EnvPort

func WithZipkin

func WithZipkin(zipkinURL string) Option

WithZipkin maps EnvZipkinURL

func WithoutFnInvokeEndpoints

func WithoutFnInvokeEndpoints() Option

WithoutFnInvokeEndpoints optionally disables the fn direct invoke endpoints from a LB -supporting server, allowing extensions to replace them with their own versions

func WithoutHTTPTriggerEndpoints

func WithoutHTTPTriggerEndpoints() Option

WithoutHTTPTriggerEndpoints optionally disables the trigger and route endpoints from a LB -supporting server, allowing extensions to replace them with their own versions

func WithoutProfilerEndpoints added in v0.3.708

func WithoutProfilerEndpoints() Option

WithoutProfilerEndpoints disables the /debug endpoints

type RIDProvider

type RIDProvider struct {
	HeaderName   string              // The name of the header where the reques id is stored in the incoming request
	RIDGenerator func(string) string // Function to generate the requestID
}

RIDProvider is used to generate request IDs

type ResponseBuffer

type ResponseBuffer interface {
	http.ResponseWriter
	Status() int
}

ResponseBuffer implements http.ResponseWriter

type Server

type Server struct {
	Router      *gin.Engine
	AdminRouter *gin.Engine
	// contains filtered or unexported fields
}

Server is the object which ties together all the fn things, it is the entrypoint for managing fn resources and executing tasks.

func New

func New(ctx context.Context, opts ...Option) *Server

New creates a new Functions server with the opts given. For convenience, users may prefer to use NewFromEnv but New is more flexible if needed.

func NewFromEnv

func NewFromEnv(ctx context.Context, opts ...Option) *Server

NewFromEnv creates a new Functions server based on env vars.

func (*Server) AddAPIMiddleware

func (s *Server) AddAPIMiddleware(m fnext.Middleware)

AddAPIMiddleware add middleware

func (*Server) AddAPIMiddlewareFunc

func (s *Server) AddAPIMiddlewareFunc(m fnext.MiddlewareFunc)

AddAPIMiddlewareFunc add middlewarefunc

func (*Server) AddAppListener

func (s *Server) AddAppListener(listener fnext.AppListener)

AddAppListener adds an AppListener for the server to use.

func (*Server) AddCallListener

func (s *Server) AddCallListener(listener fnext.CallListener)

AddCallListener adds a listener that will be fired before and after a function is executed.

func (*Server) AddEndpoint

func (s *Server) AddEndpoint(method, path string, handler fnext.APIHandler)

AddEndpoint adds an endpoint to /v2/x

func (*Server) AddEndpointFunc

func (s *Server) AddEndpointFunc(method, path string, handler func(w http.ResponseWriter, r *http.Request))

AddEndpointFunc adds an endpoint to /v2/x

func (*Server) AddExtension

func (s *Server) AddExtension(ext fnext.Extension)

AddExtension both registers an extension and adds it. This is useful during extension development or if you want to build a custom server without using `fn build-server`.

func (*Server) AddExtensionByName

func (s *Server) AddExtensionByName(name string)

AddExtensionByName This essentially just makes sure the extensions are ordered properly and is what the CLI uses for the `fn build-server` command. Probably not used by much else.

func (*Server) AddFnListener

func (s *Server) AddFnListener(listener fnext.FnListener)

func (*Server) AddMiddleware

func (s *Server) AddMiddleware(m fnext.Middleware)

AddMiddleware DEPRECATED - see AddAPIMiddleware

func (*Server) AddMiddlewareFunc

func (s *Server) AddMiddlewareFunc(m fnext.MiddlewareFunc)

AddMiddlewareFunc DEPRECATED - see AddAPIMiddlewareFunc

func (*Server) AddRootMiddleware

func (s *Server) AddRootMiddleware(m fnext.Middleware)

AddRootMiddleware add middleware add middleware for end user applications

func (*Server) AddRootMiddlewareFunc

func (s *Server) AddRootMiddlewareFunc(m fnext.MiddlewareFunc)

AddRootMiddlewareFunc add middleware for end user applications

func (*Server) AddTriggerListener

func (s *Server) AddTriggerListener(listener fnext.TriggerListener)

AddTriggerListener adds an TriggerListener for the server to use.

func (*Server) Agent

func (s *Server) Agent() agent.Agent

Agent implements fnext.ExtServer

func (*Server) Datastore

func (s *Server) Datastore() models.Datastore

Datastore implements fnext.ExtServer

func (*Server) ServeFnInvoke

func (s *Server) ServeFnInvoke(c *gin.Context, app *models.App, fn *models.Fn) error

func (*Server) ServeHTTPTrigger

func (s *Server) ServeHTTPTrigger(c *gin.Context, app *models.App, fn *models.Fn, trigger *models.Trigger) error

ServeHTTPTrigger serves an HTTP trigger for a given app/fn/trigger based on the current request This is exported to allow extensions to handle their own trigger naming and publishing

func (*Server) Start

func (s *Server) Start(ctx context.Context)

Start runs any configured machinery, including the http server, agent, etc. Start will block until the context is cancelled or times out.

type TriggerAnnotator

type TriggerAnnotator interface {
	// Annotates a trigger on read
	AnnotateTrigger(ctx *gin.Context, a *models.App, t *models.Trigger) (*models.Trigger, error)
}

TriggerAnnotator Is used to inject trigger context (such as request URLs) into outbound trigger resources

func NewRequestBasedTriggerAnnotator

func NewRequestBasedTriggerAnnotator() TriggerAnnotator

NewRequestBasedTriggerAnnotator creates a TriggerAnnotator that inspects the incoming request host and port, and uses this to generate http trigger endpoint URLs based on those

func NewStaticURLTriggerAnnotator

func NewStaticURLTriggerAnnotator(baseURL string) TriggerAnnotator

NewStaticURLTriggerAnnotator annotates triggers bases on a given, specified URL base - e.g. "https://my.domain" ---> "https://my.domain/t/app/source"

Directories

Path Synopsis
Package defaultexts are the extensions that are auto-loaded in to the default fnserver binary included here as a package to simplify inclusion in testing
Package defaultexts are the extensions that are auto-loaded in to the default fnserver binary included here as a package to simplify inclusion in testing

Jump to

Keyboard shortcuts

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