server

package
v0.9.1 Latest Latest
Warning

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

Go to latest
Published: May 14, 2025 License: MIT Imports: 39 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DefaultHttpPort  = 80
	DefaultHttpsPort = 443
)
View Source
const (
	B  int64 = 1
	KB       = B << 10
	MB       = KB << 10
	GB       = MB << 10
)
View Source
const (
	DefaultDeployTimeout         = time.Second * 30
	DefaultDrainTimeout          = time.Second * 30
	DefaultPauseTimeout          = time.Second * 30
	DefaultWriterAffinityTimeout = time.Second * 3

	DefaultHealthCheckPath     = "/up"
	DefaultHealthCheckInterval = time.Second
	DefaultHealthCheckTimeout  = time.Second * 5

	MaxIdleConnsPerHost = 100
	ProxyBufferSize     = 32 * KB

	DefaultTargetTimeout       = time.Second * 30
	DefaultMaxMemoryBufferSize = 1 * MB
	DefaultMaxRequestBodySize  = 0
	DefaultMaxResponseBodySize = 0

	DefaultStopMessage = ""
)
View Source
const (
	ACMEStagingDirectoryURL = "https://acme-staging-v02.api.letsencrypt.org/directory"
)
View Source
const LoadBalancerWriteCookieName = "kamal-writer"
View Source
const RolloutCookieName = "kamal-rollout"
View Source
const (
	StatusClientClosedRequest = 499
)

Variables

View Source
var (
	ErrMaximumSizeExceeded = errors.New("maximum size exceeded")
	ErrWriteAfterRead      = errors.New("write after read")
)
View Source
var (
	ErrorHealthCheckRequestTimedOut  = errors.New("request timed out")
	ErrorHealthCheckUnexpectedStatus = errors.New("unexpected status")
)
View Source
var (
	ErrorServiceNotFound             = errors.New("service not found")
	ErrorTargetFailedToBecomeHealthy = errors.New("target failed to become healthy within configured timeout")
	ErrorHostInUse                   = errors.New("host settings conflict with another service")
	ErrorNoServerName                = errors.New("no server name provided")
	ErrorUnknownServerName           = errors.New("unknown server name")
)
View Source
var (
	ErrorRolloutTargetNotSet                 = errors.New("rollout target not set")
	ErrorUnableToLoadErrorPages              = errors.New("unable to load error pages")
	ErrorAutomaticTLSDoesNotSupportWildcards = errors.New("automatic TLS does not support wildcards")
)
View Source
var (
	ErrorInvalidHostPattern = errors.New("invalid host pattern")
	ErrorDraining           = errors.New("target is draining")
)
View Source
var ErrorNoHealthyTargets = errors.New("no healthy targets")
View Source
var ErrorUnableToLoadCertificate = errors.New("unable to load certificate")

Functions

func EnsureTrailingSlash added in v0.9.0

func EnsureTrailingSlash(path string) string

func LoggingRequestContext

func LoggingRequestContext(r *http.Request) *loggingRequestContext

func NewBufferedReadCloser

func NewBufferedReadCloser(r io.ReadCloser, maxBytes, maxMemBytes int64) (io.ReadCloser, error)

func NormalizeHosts added in v0.9.0

func NormalizeHosts(hosts []string) []string

func NormalizePathPrefixes added in v0.9.0

func NormalizePathPrefixes(pathPrefixes []string) []string

func PerformConcurrently added in v0.8.5

func PerformConcurrently(fns ...func())

func RoutingContext added in v0.9.0

func RoutingContext(r *http.Request) *routingContext

func SetErrorResponse

func SetErrorResponse(w http.ResponseWriter, r *http.Request, statusCode int, templateArguments any)

func WithErrorPageMiddleware

func WithErrorPageMiddleware(pages fs.FS, root bool, next http.Handler) (http.Handler, error)

func WithLoggingMiddleware

func WithLoggingMiddleware(logger *slog.Logger, httpPort, httpsPort int, next http.Handler) http.Handler

func WithRequestBufferMiddleware

func WithRequestBufferMiddleware(maxMemBytes, maxBytes int64, next http.Handler) http.Handler

func WithRequestIDMiddleware

func WithRequestIDMiddleware(next http.Handler) http.Handler

func WithRequestStartMiddleware added in v0.8.3

func WithRequestStartMiddleware(next http.Handler) http.Handler

func WithResponseBufferMiddleware

func WithResponseBufferMiddleware(maxMemBytes, maxBytes int64, next http.Handler) http.Handler

Types

type Buffer

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

func NewBufferedWriteCloser

func NewBufferedWriteCloser(maxBytes, maxMemBytes int64) *Buffer

func (*Buffer) Close

func (b *Buffer) Close() error

func (*Buffer) Overflowed

func (b *Buffer) Overflowed() bool

func (*Buffer) Read

func (b *Buffer) Read(p []byte) (n int, err error)

func (*Buffer) Send

func (b *Buffer) Send(w io.Writer) error

func (*Buffer) Write

func (b *Buffer) Write(p []byte) (int, error)

type BufferPool

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

func NewBufferPool

func NewBufferPool(bufferSize int64) *BufferPool

func (*BufferPool) Get

func (b *BufferPool) Get() []byte

func (*BufferPool) Put

func (b *BufferPool) Put(content []byte)

type CertManager added in v0.8.0

type CertManager interface {
	GetCertificate(hello *tls.ClientHelloInfo) (*tls.Certificate, error)
	HTTPHandler(handler http.Handler) http.Handler
}

type CommandHandler

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

func NewCommandHandler

func NewCommandHandler(router *Router) *CommandHandler

func (*CommandHandler) Close

func (h *CommandHandler) Close() error

func (*CommandHandler) Deploy

func (h *CommandHandler) Deploy(args DeployArgs, reply *bool) error

func (*CommandHandler) List

func (h *CommandHandler) List(args bool, reply *ListResponse) error

func (*CommandHandler) Pause

func (h *CommandHandler) Pause(args PauseArgs, reply *bool) error

func (*CommandHandler) Remove

func (h *CommandHandler) Remove(args RemoveArgs, reply *bool) error

func (*CommandHandler) Resume

func (h *CommandHandler) Resume(args ResumeArgs, reply *bool) error

func (*CommandHandler) RolloutDeploy

func (h *CommandHandler) RolloutDeploy(args RolloutDeployArgs, reply *bool) error

func (*CommandHandler) RolloutSet

func (h *CommandHandler) RolloutSet(args RolloutSetArgs, reply *bool) error

func (*CommandHandler) RolloutStop

func (h *CommandHandler) RolloutStop(args RolloutStopArgs, reply *bool) error

func (*CommandHandler) Start

func (h *CommandHandler) Start(socketPath string) error

func (*CommandHandler) Stop

func (h *CommandHandler) Stop(args StopArgs, reply *bool) error

type Config

type Config struct {
	Bind        string
	HttpPort    int
	HttpsPort   int
	MetricsPort int

	AlternateConfigDir string
}

func (Config) CertificatePath

func (c Config) CertificatePath() string

func (Config) SocketPath

func (c Config) SocketPath() string

func (Config) StatePath

func (c Config) StatePath() string

type DeployArgs

type DeployArgs struct {
	Service        string
	TargetURLs     []string
	ReaderURLs     []string
	DeployTimeout  time.Duration
	DrainTimeout   time.Duration
	ServiceOptions ServiceOptions
	TargetOptions  TargetOptions
}

type ErrorPageMiddleware

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

func (*ErrorPageMiddleware) ServeHTTP

func (h *ErrorPageMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request)

type HealthCheck

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

func NewHealthCheck

func NewHealthCheck(consumer HealthCheckConsumer, endpoint *url.URL, interval time.Duration, timeout time.Duration) *HealthCheck

func (*HealthCheck) Close

func (hc *HealthCheck) Close()

type HealthCheckConfig

type HealthCheckConfig struct {
	Path     string        `json:"path"`
	Interval time.Duration `json:"interval"`
	Timeout  time.Duration `json:"timeout"`
}

type HealthCheckConsumer

type HealthCheckConsumer interface {
	HealthCheckCompleted(success bool)
}

type ListResponse

type ListResponse struct {
	Targets ServiceDescriptionMap `json:"services"`
}

type LoadBalancer added in v0.9.0

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

func NewLoadBalancer added in v0.9.0

func NewLoadBalancer(targets TargetList, writerAffinityTimeout time.Duration, readTargetsAcceptWebsockets bool) *LoadBalancer

func (*LoadBalancer) Dispose added in v0.9.0

func (lb *LoadBalancer) Dispose()

func (*LoadBalancer) DrainAll added in v0.9.0

func (lb *LoadBalancer) DrainAll(timeout time.Duration)

func (*LoadBalancer) MarkAllHealthy added in v0.9.0

func (lb *LoadBalancer) MarkAllHealthy()

func (*LoadBalancer) ReadTargets added in v0.9.0

func (lb *LoadBalancer) ReadTargets() TargetList

func (*LoadBalancer) StartRequest added in v0.9.0

func (lb *LoadBalancer) StartRequest(w http.ResponseWriter, r *http.Request) func()

func (*LoadBalancer) TargetStateChanged added in v0.9.0

func (lb *LoadBalancer) TargetStateChanged(target *Target)

func (*LoadBalancer) Targets added in v0.9.0

func (lb *LoadBalancer) Targets() TargetList

func (*LoadBalancer) WaitUntilHealthy added in v0.9.0

func (lb *LoadBalancer) WaitUntilHealthy(timeout time.Duration) error

func (*LoadBalancer) WriteTargets added in v0.9.0

func (lb *LoadBalancer) WriteTargets() TargetList

type LoggingMiddleware

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

func (*LoggingMiddleware) ServeHTTP

func (h *LoggingMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request)

type PauseArgs

type PauseArgs struct {
	Service      string
	DrainTimeout time.Duration
	PauseTimeout time.Duration
}

type PauseController

type PauseController struct {
	State       PauseState    `json:"state"`
	StopMessage string        `json:"stop_message"`
	FailAfter   time.Duration `json:"fail_after"`
	// contains filtered or unexported fields
}

func NewPauseController

func NewPauseController() *PauseController

func (*PauseController) GetState

func (p *PauseController) GetState() PauseState

func (*PauseController) GetStopMessage

func (p *PauseController) GetStopMessage() string

func (*PauseController) Pause

func (p *PauseController) Pause(failAfter time.Duration) error

func (*PauseController) Resume

func (p *PauseController) Resume() error

func (*PauseController) Stop

func (p *PauseController) Stop(message string) error

func (*PauseController) UnmarshalJSON

func (p *PauseController) UnmarshalJSON(data []byte) error

func (*PauseController) Wait

func (p *PauseController) Wait() (PauseWaitAction, string)

type PauseState

type PauseState int
const (
	PauseStateRunning PauseState = iota
	PauseStatePaused
	PauseStateStopped
)

func (PauseState) String

func (ps PauseState) String() string

type PauseWaitAction

type PauseWaitAction int
const (
	PauseWaitActionProceed PauseWaitAction = iota
	PauseWaitActionTimedOut
	PauseWaitActionStopped
)

type RemoveArgs

type RemoveArgs struct {
	Service string
}

type RequestBufferMiddleware

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

func (*RequestBufferMiddleware) ServeHTTP

type RequestIDMiddleware

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

func (*RequestIDMiddleware) ServeHTTP

func (h *RequestIDMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request)

type RequestStartMiddleware added in v0.8.3

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

func (*RequestStartMiddleware) ServeHTTP added in v0.8.3

type ResponseBufferMiddleware

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

func (*ResponseBufferMiddleware) ServeHTTP

type ResumeArgs

type ResumeArgs struct {
	Service string
}

type RolloutController

type RolloutController struct {
	Percentage           int      `json:"percentage"`
	PercentageSplitPoint float64  `json:"percentage_split_point"`
	Allowlist            []string `json:"allowlist"`
}

func NewRolloutController

func NewRolloutController(percentage int, allowlist []string) *RolloutController

func (*RolloutController) RequestUsesRolloutGroup

func (rc *RolloutController) RequestUsesRolloutGroup(r *http.Request) bool

type RolloutDeployArgs

type RolloutDeployArgs struct {
	Service       string
	TargetURLs    []string
	ReaderURLs    []string
	DeployTimeout time.Duration
	DrainTimeout  time.Duration
}

type RolloutSetArgs

type RolloutSetArgs struct {
	Service    string
	Percentage int
	Allowlist  []string
}

type RolloutStopArgs

type RolloutStopArgs struct {
	Service string
}

type Router

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

func NewRouter

func NewRouter(statePath string) *Router

func (*Router) DeployService added in v0.9.0

func (r *Router) DeployService(name string, targetURLs, readerURLs []string, options ServiceOptions, targetOptions TargetOptions, deployTimeout time.Duration, drainTimeout time.Duration) error

func (*Router) GetCertificate

func (r *Router) GetCertificate(hello *tls.ClientHelloInfo) (*tls.Certificate, error)

func (*Router) ListActiveServices

func (r *Router) ListActiveServices() ServiceDescriptionMap

func (*Router) PauseService

func (r *Router) PauseService(name string, drainTimeout time.Duration, pauseTimeout time.Duration) error

func (*Router) RemoveService

func (r *Router) RemoveService(name string) error

func (*Router) RestoreLastSavedState

func (r *Router) RestoreLastSavedState() error

func (*Router) ResumeService

func (r *Router) ResumeService(name string) error

func (*Router) ServeHTTP

func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)

func (*Router) SetRolloutSplit

func (r *Router) SetRolloutSplit(name string, percent int, allowList []string) error

func (*Router) SetRolloutTargets added in v0.9.0

func (r *Router) SetRolloutTargets(name string, targetURLs, readerURLs []string, deployTimeout time.Duration, drainTimeout time.Duration) error

func (*Router) StopRollout

func (r *Router) StopRollout(name string) error

func (*Router) StopService

func (r *Router) StopService(name string, drainTimeout time.Duration, message string) error

type Server

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

func NewServer

func NewServer(config *Config, router *Router) *Server

func (*Server) HttpPort

func (s *Server) HttpPort() int

func (*Server) HttpsPort

func (s *Server) HttpsPort() int

func (*Server) Start

func (s *Server) Start() error

func (*Server) Stop

func (s *Server) Stop()

type Service

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

func NewService

func NewService(name string, options ServiceOptions, targetOptions TargetOptions) (*Service, error)

func (*Service) Dispose added in v0.9.0

func (s *Service) Dispose()

func (*Service) Drain added in v0.9.0

func (s *Service) Drain(timeout time.Duration)

func (*Service) MarshalJSON

func (s *Service) MarshalJSON() ([]byte, error)

func (*Service) Pause

func (s *Service) Pause(drainTimeout time.Duration, pauseTimeout time.Duration) error

func (*Service) Resume

func (s *Service) Resume() error

func (*Service) ServeHTTP

func (s *Service) ServeHTTP(w http.ResponseWriter, r *http.Request)

func (*Service) SetRolloutSplit

func (s *Service) SetRolloutSplit(percentage int, allowlist []string) error

func (*Service) Stop

func (s *Service) Stop(drainTimeout time.Duration, message string) error

func (*Service) StopRollout

func (s *Service) StopRollout() error

func (*Service) UnmarshalJSON

func (s *Service) UnmarshalJSON(data []byte) error

func (*Service) UpdateLoadBalancer added in v0.9.0

func (s *Service) UpdateLoadBalancer(lb *LoadBalancer, slot TargetSlot) *LoadBalancer

func (*Service) UpdateOptions

func (s *Service) UpdateOptions(options ServiceOptions, targetOptions TargetOptions) error

type ServiceDescription

type ServiceDescription struct {
	Host   string `json:"host"`
	Path   string `json:"path"`
	TLS    bool   `json:"tls"`
	Target string `json:"target"`
	State  string `json:"state"`
}

type ServiceDescriptionMap

type ServiceDescriptionMap map[string]ServiceDescription

type ServiceMap added in v0.6.0

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

func NewServiceMap added in v0.9.0

func NewServiceMap() *ServiceMap

func (*ServiceMap) All added in v0.9.0

func (m *ServiceMap) All() iter.Seq2[string, *Service]

func (*ServiceMap) CheckAvailability added in v0.9.0

func (m *ServiceMap) CheckAvailability(name string, options ServiceOptions) *Service

func (*ServiceMap) Get added in v0.9.0

func (m *ServiceMap) Get(name string) *Service

func (*ServiceMap) Remove added in v0.9.0

func (m *ServiceMap) Remove(name string)

func (*ServiceMap) ServiceForHost added in v0.9.0

func (m *ServiceMap) ServiceForHost(host string) *Service

func (*ServiceMap) ServiceForRequest added in v0.9.0

func (m *ServiceMap) ServiceForRequest(req *http.Request) (*Service, string)

func (*ServiceMap) Set added in v0.9.0

func (m *ServiceMap) Set(service *Service)

type ServiceOptions

type ServiceOptions struct {
	Hosts                       []string      `json:"hosts"`
	PathPrefixes                []string      `json:"path_prefixes"`
	TLSEnabled                  bool          `json:"tls_enabled"`
	TLSCertificatePath          string        `json:"tls_certificate_path"`
	TLSPrivateKeyPath           string        `json:"tls_private_key_path"`
	TLSRedirect                 bool          `json:"tls_redirect"`
	ACMEDirectory               string        `json:"acme_directory"`
	ACMECachePath               string        `json:"acme_cache_path"`
	ErrorPagePath               string        `json:"error_page_path"`
	StripPrefix                 bool          `json:"strip_prefix"`
	WriterAffinityTimeout       time.Duration `json:"writer_affinity_timeout"`
	ReadTargetsAcceptWebsockets bool          `json:"read_targets_accept_websockets"`
}

func (*ServiceOptions) Normalize added in v0.9.0

func (so *ServiceOptions) Normalize()

func (ServiceOptions) ScopedCachePath

func (so ServiceOptions) ScopedCachePath() string

func (*ServiceOptions) WithHosts added in v0.9.0

func (so *ServiceOptions) WithHosts(hosts []string) ServiceOptions

func (*ServiceOptions) WithPathPrefixes added in v0.9.0

func (so *ServiceOptions) WithPathPrefixes(pathPrefixes []string) ServiceOptions

type StaticCertManager added in v0.8.0

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

StaticCertManager is a certificate manager that loads certificates from disk.

func NewStaticCertManager added in v0.8.0

func NewStaticCertManager(tlsCertificateFilePath, tlsPrivateKeyFilePath string) (*StaticCertManager, error)

func (*StaticCertManager) GetCertificate added in v0.8.0

func (m *StaticCertManager) GetCertificate(*tls.ClientHelloInfo) (*tls.Certificate, error)

func (*StaticCertManager) HTTPHandler added in v0.8.0

func (m *StaticCertManager) HTTPHandler(handler http.Handler) http.Handler

type StopArgs

type StopArgs struct {
	Service      string
	DrainTimeout time.Duration
	Message      string
}

type Target

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

func NewReadOnlyTarget added in v0.9.0

func NewReadOnlyTarget(targetURL string, options TargetOptions) (*Target, error)

func NewTarget

func NewTarget(targetURL string, options TargetOptions) (*Target, error)

func (*Target) BeginHealthChecks

func (t *Target) BeginHealthChecks(stateConsumer TargetStateConsumer)

func (*Target) Drain

func (t *Target) Drain(timeout time.Duration)

func (*Target) HealthCheckCompleted

func (t *Target) HealthCheckCompleted(success bool)

func (*Target) ReadOnly added in v0.9.0

func (t *Target) ReadOnly() bool

func (*Target) SendRequest

func (t *Target) SendRequest(w http.ResponseWriter, req *http.Request)

func (*Target) StartRequest

func (t *Target) StartRequest(req *http.Request) (*http.Request, error)

func (*Target) State added in v0.9.0

func (t *Target) State() TargetState

func (*Target) StopHealthChecks

func (t *Target) StopHealthChecks()

func (*Target) Target

func (t *Target) Target() string

type TargetList added in v0.9.0

type TargetList []*Target

func NewTargetList added in v0.9.0

func NewTargetList(targetURLs, readerURLs []string, options TargetOptions) (TargetList, error)

func (TargetList) BeginHealthChecks added in v0.9.0

func (tl TargetList) BeginHealthChecks(stateConsumer TargetStateConsumer)

func (TargetList) HasReaders added in v0.9.0

func (tl TargetList) HasReaders() bool

func (TargetList) Names added in v0.9.0

func (tl TargetList) Names() []string

func (TargetList) StopHealthChecks added in v0.9.0

func (tl TargetList) StopHealthChecks()

type TargetOptions

type TargetOptions struct {
	HealthCheckConfig   HealthCheckConfig `json:"health_check_config"`
	ResponseTimeout     time.Duration     `json:"response_timeout"`
	BufferRequests      bool              `json:"buffer_requests"`
	BufferResponses     bool              `json:"buffer_responses"`
	MaxMemoryBufferSize int64             `json:"max_memory_buffer_size"`
	MaxRequestBodySize  int64             `json:"max_request_body_size"`
	MaxResponseBodySize int64             `json:"max_response_body_size"`
	LogRequestHeaders   []string          `json:"log_request_headers"`
	LogResponseHeaders  []string          `json:"log_response_headers"`
	ForwardHeaders      bool              `json:"forward_headers"`
}

func (*TargetOptions) IsHealthCheckRequest added in v0.9.0

func (to *TargetOptions) IsHealthCheckRequest(r *http.Request) bool

type TargetSlot

type TargetSlot int
const (
	TargetSlotActive TargetSlot = iota
	TargetSlotRollout
)

type TargetState

type TargetState int
const (
	TargetStateAdding TargetState = iota
	TargetStateDraining
	TargetStateHealthy
	TargetStateUnhealthy
)

func (TargetState) String

func (ts TargetState) String() string

type TargetStateConsumer added in v0.9.0

type TargetStateConsumer interface {
	TargetStateChanged(*Target)
}

Jump to

Keyboard shortcuts

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