Migrate to Go modules

Signed-off-by: Alex Ellis (OpenFaaS Ltd) <alexellis2@gmail.com>
This commit is contained in:
Alex Ellis (OpenFaaS Ltd)
2021-01-20 12:12:11 +00:00
committed by Alex Ellis
parent 2e2250afe8
commit 7ce266adc0
667 changed files with 211781 additions and 17546 deletions

View File

@ -4,6 +4,7 @@
package auth
import (
"crypto/subtle"
"net/http"
)
@ -12,10 +13,13 @@ func DecorateWithBasicAuth(next http.HandlerFunc, credentials *BasicAuthCredenti
return func(w http.ResponseWriter, r *http.Request) {
user, password, ok := r.BasicAuth()
w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
if !ok || !(credentials.Password == password && user == credentials.User) {
const noMatch = 0
if !ok ||
user != credentials.User ||
subtle.ConstantTimeCompare([]byte(credentials.Password), []byte(password)) == noMatch {
w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte("invalid credentials"))
return

View File

@ -5,6 +5,11 @@ import (
"time"
)
const (
defaultReadTimeout = 10 * time.Second
defaultMaxIdleConns = 1024
)
// FaaSHandlers provide handlers for OpenFaaS
type FaaSHandlers struct {
// FunctionProxy provides the function invocation proxy logic. Use proxy.NewHandlerFunc to
@ -22,7 +27,9 @@ type FaaSHandlers struct {
LogHandler http.HandlerFunc
// UpdateHandler an existing function/service
UpdateHandler http.HandlerFunc
UpdateHandler http.HandlerFunc
// HealthHandler defines the default health endpoint bound to "/healthz
// If the handler is not set, then the "/healthz" path will not be configured
HealthHandler http.HandlerFunc
InfoHandler http.HandlerFunc
ListNamespaceHandler http.HandlerFunc
@ -30,10 +37,51 @@ type FaaSHandlers struct {
// FaaSConfig set config for HTTP handlers
type FaaSConfig struct {
TCPPort *int
ReadTimeout time.Duration
WriteTimeout time.Duration
EnableHealth bool
// TCPPort is the public port for the API.
TCPPort *int
// HTTP timeout for reading a request from clients.
ReadTimeout time.Duration
// HTTP timeout for writing a response from functions.
WriteTimeout time.Duration
// EnableHealth enables/disables the default health endpoint bound to "/healthz".
//
// Deprecated: basic auth is enabled automatcally by setting the HealthHandler in the FaaSHandlers
// struct. This value is not longer read or used.
EnableHealth bool
// EnableBasicAuth enforces basic auth on the API. If set, reads secrets from file-system
// location specificed in `SecretMountPath`.
EnableBasicAuth bool
// SecretMountPath specifies where to read secrets from for embedded basic auth.
SecretMountPath string
// MaxIdleConns with a default value of 1024, can be used for tuning HTTP proxy performance.
MaxIdleConns int
// MaxIdleConnsPerHost with a default value of 1024, can be used for tuning HTTP proxy performance.
MaxIdleConnsPerHost int
}
// GetReadTimeout is a helper to safely return the configured ReadTimeout or the default value of 10s
func (c *FaaSConfig) GetReadTimeout() time.Duration {
if c.ReadTimeout <= 0*time.Second {
return defaultReadTimeout
}
return c.ReadTimeout
}
// GetMaxIdleConns is a helper to safely return the configured MaxIdleConns or the default value of 1024
func (c *FaaSConfig) GetMaxIdleConns() int {
if c.MaxIdleConns < 1 {
return defaultMaxIdleConns
}
return c.MaxIdleConns
}
// GetMaxIdleConns is a helper to safely return the configured MaxIdleConns or the default value which
// should then match the MaxIdleConns
func (c *FaaSConfig) GetMaxIdleConnsPerHost() int {
if c.MaxIdleConnsPerHost < 1 {
return c.GetMaxIdleConns()
}
return c.MaxIdleConnsPerHost
}

View File

@ -3,92 +3,45 @@ package types
// FunctionDeployment represents a request to create or update a Function.
type FunctionDeployment struct {
// Service corresponds to a Service
// Service is the name of the function deployment
Service string `json:"service"`
// Image corresponds to a Docker image
// Image is a fully-qualified container image
Image string `json:"image"`
// Network is specific to Docker Swarm - default overlay network is: func_functions
Network string `json:"network"`
// Namespace for the function, if supported by the faas-provider
Namespace string `json:"namespace,omitempty"`
// EnvProcess corresponds to the fprocess variable for your container watchdog.
EnvProcess string `json:"envProcess"`
// EnvProcess overrides the fprocess environment variable and can be used
// with the watchdog
EnvProcess string `json:"envProcess,omitempty"`
// EnvVars provides overrides for functions.
EnvVars map[string]string `json:"envVars"`
// EnvVars can be provided to set environment variables for the function runtime.
EnvVars map[string]string `json:"envVars,omitempty"`
// RegistryAuth is the registry authentication (optional)
// in the same encoded format as Docker native credentials
// (see ~/.docker/config.json)
RegistryAuth string `json:"registryAuth,omitempty"`
// Constraints are specific to back-end orchestration platform
Constraints []string `json:"constraints"`
// Constraints are specific to the faas-provider.
Constraints []string `json:"constraints,omitempty"`
// Secrets list of secrets to be made available to function
Secrets []string `json:"secrets"`
Secrets []string `json:"secrets,omitempty"`
// Labels are metadata for functions which may be used by the
// back-end for making scheduling or routing decisions
Labels *map[string]string `json:"labels"`
// faas-provider or the gateway
Labels *map[string]string `json:"labels,omitempty"`
// Annotations are metadata for functions which may be used by the
// back-end for management, orchestration, events and build tasks
Annotations *map[string]string `json:"annotations"`
// faas-provider or the gateway
Annotations *map[string]string `json:"annotations,omitempty"`
// Limits for function
Limits *FunctionResources `json:"limits"`
Limits *FunctionResources `json:"limits,omitempty"`
// Requests of resources requested by function
Requests *FunctionResources `json:"requests"`
Requests *FunctionResources `json:"requests,omitempty"`
// ReadOnlyRootFilesystem removes write-access from the root filesystem
// mount-point.
ReadOnlyRootFilesystem bool `json:"readOnlyRootFilesystem"`
// Namespace for the function to be deployed into
Namespace string `json:"namespace,omitempty"`
}
// FunctionResources Memory and CPU
type FunctionResources struct {
Memory string `json:"memory"`
CPU string `json:"cpu"`
}
// FunctionStatus exported for system/functions endpoint
type FunctionStatus struct {
// Name corresponds to a Service
Name string `json:"name"`
// Image corresponds to a Docker image
Image string `json:"image"`
// InvocationCount count of invocations
InvocationCount float64 `json:"invocationCount"`
// Replicas desired within the cluster
Replicas uint64 `json:"replicas"`
// EnvProcess is the process to pass to the watchdog, if in use
EnvProcess string `json:"envProcess"`
// AvailableReplicas is the count of replicas ready to receive
// invocations as reported by the backend
AvailableReplicas uint64 `json:"availableReplicas"`
// Labels are metadata for functions which may be used by the
// backend for making scheduling or routing decisions
Labels *map[string]string `json:"labels"`
// Annotations are metadata for functions which may be used by the
// backend for management, orchestration, events and build tasks
Annotations *map[string]string `json:"annotations"`
// Namespace where the function can be accessed
Namespace string `json:"namespace,omitempty"`
ReadOnlyRootFilesystem bool `json:"readOnlyRootFilesystem,omitempty"`
}
// Secret for underlying orchestrator
@ -97,3 +50,65 @@ type Secret struct {
Namespace string `json:"namespace,omitempty"`
Value string `json:"value,omitempty"`
}
// FunctionResources Memory and CPU
type FunctionResources struct {
Memory string `json:"memory,omitempty"`
CPU string `json:"cpu,omitempty"`
}
// FunctionStatus exported for system/functions endpoint
type FunctionStatus struct {
// Name is the name of the function deployment
Name string `json:"name"`
// Image is a fully-qualified container image
Image string `json:"image"`
// Namespace for the function, if supported by the faas-provider
Namespace string `json:"namespace,omitempty"`
// EnvProcess overrides the fprocess environment variable and can be used
// with the watchdog
EnvProcess string `json:"envProcess,omitempty"`
// EnvVars set environment variables for the function runtime
EnvVars map[string]string `json:"envVars,omitempty"`
// Constraints are specific to the faas-provider
Constraints []string `json:"constraints,omitempty"`
// Secrets list of secrets to be made available to function
Secrets []string `json:"secrets,omitempty"`
// Labels are metadata for functions which may be used by the
// faas-provider or the gateway
Labels *map[string]string `json:"labels,omitempty"`
// Annotations are metadata for functions which may be used by the
// faas-provider or the gateway
Annotations *map[string]string `json:"annotations,omitempty"`
// Limits for function
Limits *FunctionResources `json:"limits,omitempty"`
// Requests of resources requested by function
Requests *FunctionResources `json:"requests,omitempty"`
// ReadOnlyRootFilesystem removes write-access from the root filesystem
// mount-point.
ReadOnlyRootFilesystem bool `json:"readOnlyRootFilesystem,omitempty"`
// ** Status fields *8
// InvocationCount count of invocations
InvocationCount float64 `json:"invocationCount,omitempty"`
// Replicas desired within the cluster
Replicas uint64 `json:"replicas,omitempty"`
// AvailableReplicas is the count of replicas ready to receive
// invocations as reported by the faas-provider
AvailableReplicas uint64 `json:"availableReplicas,omitempty"`
}

View File

@ -0,0 +1,112 @@
package types
import (
"fmt"
"os"
"strconv"
"time"
)
// OsEnv implements interface to wrap os.Getenv
type OsEnv struct {
}
// Getenv wraps os.Getenv
func (OsEnv) Getenv(key string) string {
return os.Getenv(key)
}
// HasEnv provides interface for os.Getenv
type HasEnv interface {
Getenv(key string) string
}
// ReadConfig constitutes config from env variables
type ReadConfig struct {
}
// ParseIntValue parses the the int in val or, if there is an error, returns the
// specified default value
func ParseIntValue(val string, fallback int) int {
if len(val) > 0 {
parsedVal, parseErr := strconv.Atoi(val)
if parseErr == nil && parsedVal >= 0 {
return parsedVal
}
}
return fallback
}
// ParseIntOrDurationValue parses the the duration in val or, if there is an error, returns the
// specified default value
func ParseIntOrDurationValue(val string, fallback time.Duration) time.Duration {
if len(val) > 0 {
parsedVal, parseErr := strconv.Atoi(val)
if parseErr == nil && parsedVal >= 0 {
return time.Duration(parsedVal) * time.Second
}
}
duration, durationErr := time.ParseDuration(val)
if durationErr != nil {
return fallback
}
return duration
}
// ParseBoolValue parses the the boolean in val or, if there is an error, returns the
// specified default value
func ParseBoolValue(val string, fallback bool) bool {
if len(val) > 0 {
return val == "true"
}
return fallback
}
// ParseString verifies the string in val is not empty. When empty, it returns the
// specified default value
func ParseString(val string, fallback string) string {
if len(val) > 0 {
return val
}
return fallback
}
// Read fetches config from environmental variables.
func (ReadConfig) Read(hasEnv HasEnv) (*FaaSConfig, error) {
cfg := &FaaSConfig{
ReadTimeout: ParseIntOrDurationValue(hasEnv.Getenv("read_timeout"), time.Second*10),
WriteTimeout: ParseIntOrDurationValue(hasEnv.Getenv("write_timeout"), time.Second*10),
EnableBasicAuth: ParseBoolValue(hasEnv.Getenv("basic_auth"), false),
// default value from Gateway
SecretMountPath: ParseString(hasEnv.Getenv("secret_mount_path"), "/run/secrets/"),
}
port := ParseIntValue(hasEnv.Getenv("port"), 8080)
cfg.TCPPort = &port
cfg.MaxIdleConns = 1024
maxIdleConns := hasEnv.Getenv("max_idle_conns")
if len(maxIdleConns) > 0 {
val, err := strconv.Atoi(maxIdleConns)
if err != nil {
return nil, fmt.Errorf("invalid value for max_idle_conns: %s", maxIdleConns)
}
cfg.MaxIdleConns = val
}
cfg.MaxIdleConnsPerHost = 1024
maxIdleConnsPerHost := hasEnv.Getenv("max_idle_conns_per_host")
if len(maxIdleConnsPerHost) > 0 {
val, err := strconv.Atoi(maxIdleConnsPerHost)
if err != nil {
return nil, fmt.Errorf("invalid value for max_idle_conns_per_host: %s", maxIdleConnsPerHost)
}
cfg.MaxIdleConnsPerHost = val
}
return cfg, nil
}

View File

@ -3,20 +3,27 @@
package types
// ScaleServiceRequest scales the service to the requested replcia count.
type ScaleServiceRequest struct {
ServiceName string `json:"serviceName"`
Replicas uint64 `json:"replicas"`
}
// InfoRequest provides information about the underlying provider
type InfoRequest struct {
Provider string `json:"provider"`
Version ProviderVersion `json:"version"`
Orchestration string `json:"orchestration"`
// DeleteFunctionRequest delete a deployed function
type DeleteFunctionRequest struct {
FunctionName string `json:"functionName"`
}
// ProviderVersion provides the commit sha and release version number of the underlying provider
type ProviderVersion struct {
SHA string `json:"sha"`
Release string `json:"release"`
// ProviderInfo provides information about the configured provider
type ProviderInfo struct {
Name string `json:"provider"`
Version *VersionInfo `json:"version"`
Orchestration string `json:"orchestration"`
}
// VersionInfo provides the commit message, sha and release version number
type VersionInfo struct {
CommitMessage string `json:"commit_message,omitempty"`
SHA string `json:"sha"`
Release string `json:"release"`
}