server

package
v1.47.1 Latest Latest
Warning

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

Go to latest
Published: Sep 18, 2026 License: MIT Imports: 61 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DockerRouterLabelHost                      = "mc-router.host"
	DockerRouterLabelPort                      = "mc-router.port"
	DockerRouterLabelDefault                   = "mc-router.default"
	DockerRouterLabelNetwork                   = "mc-router.network"
	DockerRouterLabelAutoScaleUp               = "mc-router.auto-scale-up"
	DockerRouterLabelAutoScaleDown             = "mc-router.auto-scale-down"
	DockerRouterLabelAutoScaleAsleepMOTD       = "mc-router.auto-scale-asleep-motd"
	DockerRouterLabelAutoScaleLoadingMOTD      = "mc-router.auto-scale-loading-motd"
	DockerRouterLabelAutoScaleWaitTimeout      = "mc-router.auto-scale-wait-timeout"
	DockerRouterLabelAutoScaleFailedMOTD       = "mc-router.auto-scale-failed-motd"
	DockerRouterLabelAutoScaleRestartDelayMOTD = "mc-router.auto-scale-restart-delay-motd"
)
View Source
const (
	AnnotationExternalServerName   = "mc-router.itzg.me/externalServerName"
	AnnotationDefaultServer        = "mc-router.itzg.me/defaultServer"
	AnnotationAutoScaleUp          = "mc-router.itzg.me/autoScaleUp"
	AnnotationAutoScaleDown        = "mc-router.itzg.me/autoScaleDown"
	AnnotationProxyServerName      = "mc-router.itzg.me/proxyServerName"
	AnnotationAutoScaleAsleepMOTD  = "mc-router.itzg.me/autoScaleAsleepMOTD"
	AnnotationAutoScaleLoadingMOTD = "mc-router.itzg.me/autoScaleLoadingMOTD"
	AnnotationAutoScaleWaitTimeout = "mc-router.itzg.me/autoScaleWaitTimeout"
)
View Source
const (
	MetricsBackendExpvar     = "expvar"
	MetricsBackendPrometheus = "prometheus"
	MetricsBackendInfluxDB   = "influxdb"
	MetricsBackendDiscard    = "discard"
)

Variables

This section is empty.

Functions

func SplitExternalHosts added in v1.36.1

func SplitExternalHosts(s string) []string

SplitExternalHosts splits a string containing external hostnames by comma and/or newline delimiters. It trims whitespace around each hostname and filters out empty strings. Examples:

  • "host1.com,host2.com" -> ["host1.com", "host2.com"]
  • "host1.com, host2.com" -> ["host1.com", "host2.com"]
  • "host1.com\nhost2.com" -> ["host1.com", "host2.com"]
  • "host1.com,\nhost2.com" -> ["host1.com", "host2.com"]

Types

type ActiveConnections

type ActiveConnections struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

func NewActiveConnections

func NewActiveConnections() *ActiveConnections

func (*ActiveConnections) Decrement

func (sm *ActiveConnections) Decrement(key string)

func (*ActiveConnections) GetCount

func (sm *ActiveConnections) GetCount(backendAddress string) int

func (*ActiveConnections) Increment

func (sm *ActiveConnections) Increment(key string)

type AllowDenyConfig

type AllowDenyConfig struct {
	Global  AllowDenyLists
	Servers map[string]AllowDenyLists
}

func ParseAllowDenyConfig

func ParseAllowDenyConfig(allowDenyListPath string) (*AllowDenyConfig, error)

func (*AllowDenyConfig) ServerAllowsPlayer

func (allowDenyConfig *AllowDenyConfig) ServerAllowsPlayer(serverAddress string, userInfo *PlayerInfo) bool

type AllowDenyLists

type AllowDenyLists struct {
	Allowlist []PlayerInfo
	Denylist  []PlayerInfo
}

type ApiServer added in v1.46.1

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

ApiServer holds the dependencies the REST handlers need, injected at startup rather than reached for as globals.

func StartApiServer

func StartApiServer(ctx context.Context, apiBinding string, routes IRoutes, configLoader *RoutesConfigLoader, webhookScaler *WebhookScaler) (*ApiServer, error)

StartApiServer starts the REST API server. It will listen on apiBinding's host:port utilizing the given routes to retrieve routes, configLoader to save routes, and scaler to scale routes via a WebhookScaler.

func (*ApiServer) GetAddr added in v1.46.1

func (a *ApiServer) GetAddr() string

type AutoScale

type AutoScale struct {
	Up          bool          `` /* 153-byte string literal not displayed */
	Down        bool          `` /* 182-byte string literal not displayed */
	DownAfter   time.Duration `default:"10m" usage:"Server scale down delay after there are no connections"`
	AllowDeny   string        `` /* 273-byte string literal not displayed */
	AsleepMOTD  string        `usage:"MOTD to display when auto-scaled down servers are accessed; if empty, no status will be served"`
	LoadingMOTD string        `usage:"MOTD to display while auto-scaled Docker servers are waking up; if empty, asleep status will be served"`
	Webhook     AutoScaleWebhookConfig
}

type AutoScaleWebhookConfig added in v1.43.0

type AutoScaleWebhookConfig struct {
	Url         string            `usage:"If set, statically-configured backends are scaled up on access and down after idle by POSTing to this URL"`
	Headers     map[string]string `usage:"Zero or more 'key=value' headers added to scaler webhook requests, e.g. for authentication tokens"`
	Timeout     time.Duration     `default:"30s" usage:"Timeout for each scaler webhook request"`
	WakeTimeout time.Duration     `default:"60s" usage:"Maximum time to wait for the backend to become reachable after a scale-up webhook"`
}

AutoScaleWebhookConfig enables scaling of statically-configured routes by POSTing to an external HTTP receiver, which owns the start/stop of the backend. This keeps the scaling privilege out of the router process.

type ClientFilter

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

ClientFilter performs allow/deny filtering of client IP addresses

func NewClientFilter

func NewClientFilter(allows []string, denies []string) (*ClientFilter, error)

NewClientFilter provides a mechanism to evaluate client IP addresses and determine if they should be allowed access or not. The allows and denies can each or both be nil or netip.ParseAddr allowed values.

func NewClientFilterAllowAll

func NewClientFilterAllowAll() *ClientFilter

func (*ClientFilter) Allow

func (f *ClientFilter) Allow(addrPort netip.AddrPort) bool

Allow determines if this filter allows the given address where addrStr is a netip.ParseAddr allowed address

type ClientInfo

type ClientInfo struct {
	Host string `json:"host"`
	Port int    `json:"port"`
}

func ClientInfoFromAddr

func ClientInfoFromAddr(addr net.Addr) *ClientInfo

type Config

type Config struct {
	Port                   int               `default:"25565" usage:"The [port] bound to listen for Minecraft client connections"`
	Default                string            `usage:"host:port of a default Minecraft server to use when mapping not found"`
	Mapping                map[string]string `usage:"Comma or newline delimited or repeated mappings of externalHostname=host:port"`
	ApiBinding             string            `usage:"The [host:port] bound for servicing API requests"`
	CpuProfile             string            `usage:"Enables CPU profiling and writes to given path"`
	ConnectionRateLimit    int               `default:"1" usage:"Max number of connections to allow per second"`
	BackendDialTimeout     time.Duration     `` /* 307-byte string literal not displayed */
	InKubeCluster          bool              `usage:"Use in-cluster Kubernetes config"`
	KubeConfig             string            `usage:"The path to a Kubernetes configuration file"`
	KubeNamespace          string            `usage:"The namespace to watch or blank for all, which is the default"`
	InDocker               bool              `usage:"Use Docker service discovery"`
	InDockerSwarm          bool              `usage:"Use Docker Swarm service discovery"`
	DockerSocket           string            `usage:"Path to Docker socket to use"`
	DockerTimeout          time.Duration     `usage:"Timeout (as duration) for the Docker integrations"`
	DockerRefreshInterval  time.Duration     `usage:"Deprecated and ignored: Docker discovery is now event-driven"`
	DockerApiVersion       string            `usage:"Instead of auto-negotiating, use specific Docker API version"`
	MetricsBackend         string            `default:"discard" usage:"Backend to use for metrics exposure/publishing: discard,expvar,influxdb,prometheus"`
	MetricsBackendConfig   MetricsBackendConfig
	MetricsRateLimitPeriod time.Duration `default:"1s" usage:"The period at which the rate limit bucket's metrics are set: 0 to disable (default 1s)"`
	UseProxyProtocol       bool          `default:"false" usage:"Send PROXY protocol to backend servers"`
	ReceiveProxyProtocol   bool          `` /* 190-byte string literal not displayed */
	DynamicProxyProtocol   bool          `` /* 220-byte string literal not displayed */
	TrustedProxies         []string      `usage:"Comma delimited list of CIDR notation IP blocks to trust when receiving PROXY protocol"`
	RecordLogins           bool          `default:"false" usage:"Log and generate metrics on player logins. Metrics only supported with influxdb or prometheus backend"`
	Routes                 RoutesConfig
	Ngrok                  NgrokConfig
	AutoScale              AutoScale

	ClientsToAllow []string `usage:"Zero or more client IP addresses or CIDRs to allow. Takes precedence over deny."`
	ClientsToDeny  []string `usage:"Zero or more client IP addresses or CIDRs to deny. Ignored if any configured to allow"`

	SimplifySRV bool `default:"false" usage:"Simplify fully qualified SRV records for mapping"`

	Webhook WebhookConfig `usage:"Webhook configuration"`
}

type ConnectionNotifier

type ConnectionNotifier interface {
	// NotifyMissingBackend is called when an inbound connection is received for a server that does not have a backend.
	NotifyMissingBackend(ctx context.Context, clientAddr net.Addr, server string, playerInfo *PlayerInfo) error

	// NotifyFailedBackendConnection is called when the backend connection failed.
	NotifyFailedBackendConnection(ctx context.Context,
		clientAddr net.Addr, serverAddress string, playerInfo *PlayerInfo, backendHostPort string, err error) error

	// NotifyConnected is called when the backend connection succeeded.
	NotifyConnected(ctx context.Context,
		clientAddr net.Addr, serverAddress string, playerInfo *PlayerInfo, backendHostPort string) error

	// NotifyDisconnected is called when the backend connection terminates.
	NotifyDisconnected(ctx context.Context,
		clientAddr net.Addr, serverAddress string, playerInfo *PlayerInfo, backendHostPort string) error
}

type Connector

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

func NewConnector

func NewConnector(ctx context.Context, routes IRoutes, downScaler IDownScaler, metrics ConnectorMetrics, sendProxyProto bool, recordLogins bool, autoScaleUpAllowDenyConfig *AllowDenyConfig) *Connector

func (*Connector) AcceptConnection

func (c *Connector) AcceptConnection(conn net.Conn)

AcceptConnection provides a way to externally supply a connection to consume. Note that this will skip rate limiting.

func (*Connector) HandleConnection

func (c *Connector) HandleConnection(frontendConn net.Conn)

func (*Connector) StartAcceptingConnections

func (c *Connector) StartAcceptingConnections(listenAddress string, connRateLimit int, metricsPeriod time.Duration) error

func (*Connector) UseAsleepMOTD added in v1.38.0

func (c *Connector) UseAsleepMOTD(motd string)

UseAsleepMOTD configures a predefined MOTD to serve when backends are asleep

func (*Connector) UseBackendDialTimeout added in v1.44.1

func (c *Connector) UseBackendDialTimeout(d time.Duration)

UseBackendDialTimeout overrides the timeout for establishing the TCP connection to a backend (values <= 0 keep the default). Backends that are reachable quickly — e.g. on-cluster Services — can use a shorter timeout so the asleep-MOTD / scale-up fallback fires promptly on a scaled-to-zero backend instead of waiting the full default.

func (*Connector) UseClientFilter

func (c *Connector) UseClientFilter(filter *ClientFilter)

func (*Connector) UseConnectionNotifier

func (c *Connector) UseConnectionNotifier(notifier ConnectionNotifier)

func (*Connector) UseDynamicProxyProtocol added in v1.47.0

func (c *Connector) UseDynamicProxyProtocol(trustedProxyNets []*net.IPNet)

func (*Connector) UseLoadingMOTD added in v1.40.2

func (c *Connector) UseLoadingMOTD(motd string)

UseLoadingMOTD configures a predefined MOTD to serve when backends are waking up

func (*Connector) UseNgrok

func (c *Connector) UseNgrok(config NgrokConfig)

func (*Connector) UseReceiveProxyProto

func (c *Connector) UseReceiveProxyProto(trustedProxyNets []*net.IPNet)

func (*Connector) WaitForConnections

func (c *Connector) WaitForConnections()

type ConnectorMetrics

type ConnectorMetrics interface {
	IncrementErrors(errorType string)
	AddBytesTransmitted(amount int64)
	IncrementConnectionsFrontend()
	IncrementConnectionsBackend(host string)
	SetActiveConnections(count int32)
	SetServerActivePlayerCounts(playerName string, playerUuid string, serverAddress string, count int)
	IncrementServerLogins(playerName string, playerUuid string, serverAddress string)
	SetServerActiveConnections(serverAddress string, value int)
	SetRateLimitAvailable(value int64)
}

type DockerScalingTarget added in v1.46.0

type DockerScalingTarget struct {
	ScalingIndicator
	// contains filtered or unexported fields
}

func NewDockerScalingTarget added in v1.46.0

func NewDockerScalingTarget(containerId, name string) *DockerScalingTarget

func (*DockerScalingTarget) ScalingKey added in v1.46.0

func (t *DockerScalingTarget) ScalingKey() string

func (*DockerScalingTarget) String added in v1.46.0

func (t *DockerScalingTarget) String() string

type DockerSwarmScalingTarget added in v1.46.0

type DockerSwarmScalingTarget struct {
	ScalingIndicator
	// contains filtered or unexported fields
}

func NewDockerSwarmScalingTarget added in v1.46.0

func NewDockerSwarmScalingTarget(serviceID string, name string) *DockerSwarmScalingTarget

func (*DockerSwarmScalingTarget) ScalingKey added in v1.46.0

func (t *DockerSwarmScalingTarget) ScalingKey() string

func (*DockerSwarmScalingTarget) String added in v1.46.0

func (t *DockerSwarmScalingTarget) String() string

type IDockerWatcher

type IDockerWatcher interface {
	Start(ctx context.Context) error
}

func NewDockerSwarmWatcher added in v1.37.0

func NewDockerSwarmWatcher(socket string, timeout time.Duration, autoScaleUp bool, autoScaleDown bool, dockerApiVersion string, routes IRoutes) IDockerWatcher

func NewDockerWatcher added in v1.37.0

func NewDockerWatcher(socket string, timeout time.Duration, autoScaleUp bool, autoScaleDown bool, dockerApiVersion string, routes IRoutes) IDockerWatcher

type IDownScaler

type IDownScaler interface {
	Reset()
	Start(ctx context.Context, scalingTarget ScalingTarget, routes IRoutes)
	Cancel(scalingTarget ScalingTarget)
	HandleContextDone(ctx context.Context)
}

func NewDownScaler

func NewDownScaler(enabled bool, delay time.Duration) IDownScaler

type IRoutes

type IRoutes interface {
	RoutesHandler

	Reset()
	// FindBackendForServerAddress returns the host:port for the external server address, if registered.
	// Otherwise, an empty string is returned. Also returns the normalized version of the given serverAddress.
	// The 3rd value returned is the scalingTarget which indicates what endpoint to scale (may differ from backend when using proxy).
	// The 4th value returned is an (optional) "waker" function which a caller must invoke to wake up serverAddress.
	// The 5th value returned is an (optional) "sleeper" function which a caller must invoke to shut down serverAddress.
	FindBackendForServerAddress(ctx context.Context, serverAddress string) (string, string, ScalingTarget, WakerFunc, SleeperFunc)
	HasRoute(serverAddress string) bool
	GetSleeper(scalingTarget ScalingTarget) SleeperFunc
	GetMappings() map[string]string
	GetDefaultRoute() (string, ScalingTarget, WakerFunc, SleeperFunc)
	GetAsleepMOTD(serverAddress string) string
	GetLoadingMOTD(serverAddress string) string
	SetCountdownDeadline(serverAddress string, deadline time.Time)
	SimplifySRV(srvEnabled bool)
	// BulkRegister registers a set of static mappings, attaching the scaler's waker/sleeper pair. nil-safe: a nil scaler registers without autoscaling.
	// Reset must be called separately and previous to this if you want to clear existing mappings.
	BulkRegister(scaler *WebhookScaler, mappings map[string]string)

	WithDownScaler(downScaler IDownScaler) IRoutes
	WithListener(listener RoutesListener) IRoutes
}

func NewRoutes

func NewRoutes(ctx context.Context) IRoutes

type K8sScalingTarget added in v1.46.0

type K8sScalingTarget struct {
	ScalingIndicator
	// contains filtered or unexported fields
}

func NewK8sScalingTarget added in v1.46.0

func NewK8sScalingTarget(namespace string, serviceName string) *K8sScalingTarget

func (*K8sScalingTarget) ScalingKey added in v1.46.0

func (t *K8sScalingTarget) ScalingKey() string

func (*K8sScalingTarget) String added in v1.46.0

func (t *K8sScalingTarget) String() string

type K8sWatcher

type K8sWatcher struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

K8sWatcher is a RouteFinder that can find routes from kubernetes services. It also watches for stateful sets to auto-scale up/down, if enabled.

func NewK8sWatcherInCluster

func NewK8sWatcherInCluster() (*K8sWatcher, error)

func NewK8sWatcherWithConfig

func NewK8sWatcherWithConfig(kubeConfigFile string) (*K8sWatcher, error)

func (*K8sWatcher) Start

func (w *K8sWatcher) Start(ctx context.Context, handler RoutesHandler) error

func (*K8sWatcher) String

func (w *K8sWatcher) String() string

func (*K8sWatcher) WithAutoScale

func (w *K8sWatcher) WithAutoScale(autoScaleUp bool, autoScaleDown bool) *K8sWatcher

func (*K8sWatcher) WithNamespace

func (w *K8sWatcher) WithNamespace(namespace string) *K8sWatcher

type MetricsBackendConfig

type MetricsBackendConfig struct {
	Influxdb struct {
		Interval        time.Duration     `default:"1m"`
		Tags            map[string]string `usage:"any extra tags to be included with all reported metrics"`
		Addr            string
		Username        string
		Password        string
		Database        string
		RetentionPolicy string
	}
}

type MetricsBuilder

type MetricsBuilder interface {
	BuildConnectorMetrics() ConnectorMetrics
	Start(ctx context.Context) error
}

func NewMetricsBuilder

func NewMetricsBuilder(backend string, config *MetricsBackendConfig) MetricsBuilder

NewMetricsBuilder creates a new MetricsBuilder based on the specified backend. If the backend is not recognized, a discard builder is returned. config can be nil if the backend is not influxdb.

type NgrokConfig

type NgrokConfig struct {
	Token      string `usage:"If set, an ngrok tunnel will be established. It is HIGHLY recommended to pass as an environment variable."`
	RemoteAddr string `usage:"If set, the TCP address to request for this edge"`
}

type NgrokConnector

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

type PlayerInfo

type PlayerInfo struct {
	Name string    `json:"name"`
	Uuid uuid.UUID `json:"uuid"`
}

func (*PlayerInfo) String

func (p *PlayerInfo) String() string

type RouteFinder

type RouteFinder interface {
	Start(ctx context.Context, handler RoutesHandler) error
	String() string
}

RouteFinder implementations find new routes in the system that can be tracked by a RoutesHandler

type RoutesConfig

type RoutesConfig struct {
	Config      string `usage:"Name or full [path] to routes config file"`
	ConfigWatch bool   `usage:"Watch for config file changes"`
}

type RoutesConfigLoader

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

func NewRoutesConfigLoader added in v1.43.2

func NewRoutesConfigLoader(scaler *WebhookScaler,
	routes IRoutes,
) *RoutesConfigLoader

func (*RoutesConfigLoader) Load added in v1.43.2

func (r *RoutesConfigLoader) Load(routesConfigFileName string) error

func (*RoutesConfigLoader) Reload added in v1.43.2

func (r *RoutesConfigLoader) Reload() error

func (*RoutesConfigLoader) SaveRoutes added in v1.43.2

func (r *RoutesConfigLoader) SaveRoutes()

func (*RoutesConfigLoader) WatchForChanges added in v1.43.2

func (r *RoutesConfigLoader) WatchForChanges(ctx context.Context) error

type RoutesConfigSchema

type RoutesConfigSchema struct {
	DefaultServer string            `json:"default-server"`
	Mappings      map[string]string `json:"mappings"`
}

RoutesConfigSchema declares the schema of the json file that can provide routes to serve

type RoutesHandler

type RoutesHandler interface {
	CreateMapping(serverAddress string, backend string, scalingTarget ScalingTarget, waker WakerFunc, sleeper SleeperFunc, asleepMOTD string, loadingMOTD string)
	// UpdateMapping atomically replaces the backend for an existing route without touching the
	// scale-down timer. Use this instead of RemoveMapping+CreateMapping when the server address
	// itself has not changed, so the timer bounce (cancel-on-remove, start-on-create) is avoided.
	// If backend is empty the timer is cancelled (container stopped externally).
	UpdateMapping(serverAddress string, backend string, scalingTarget ScalingTarget, waker WakerFunc, sleeper SleeperFunc, asleepMOTD string, loadingMOTD string)
	SetDefaultRoute(backend string, scalingTarget ScalingTarget, waker WakerFunc, sleeper SleeperFunc, asleepMOTD string, loadingMOTD string)
	RemoveDefaultRoute()
	// RemoveMapping requests that the serverAddress be removed from routes.
	// Returns true if the route existed.
	RemoveMapping(serverAddress string) bool
}

type RoutesListener added in v1.44.0

type RoutesListener interface {
	// OnRouteAdded is called when a new route is added.
	OnRouteAdded(serverAddress string, backend string)
	// OnDefaultRouteSet is called when a default route is set.
	OnDefaultRouteSet(backend string)
	// OnRouteRemoved is called when a route is removed.
	OnRouteRemoved(serverAddress string)
	// OnDefaultRouteRemoved is called when a default route is removed (or un-set).
	OnDefaultRouteRemoved()
}

type ScalingIndicator added in v1.46.0

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

func (*ScalingIndicator) EndScaling added in v1.46.0

func (i *ScalingIndicator) EndScaling() bool

func (*ScalingIndicator) IsScaling added in v1.46.0

func (i *ScalingIndicator) IsScaling() bool

func (*ScalingIndicator) StartScaling added in v1.46.0

func (i *ScalingIndicator) StartScaling() bool

type ScalingTarget added in v1.46.0

type ScalingTarget interface {
	// StartScaling and EndScaling are called when the target scales up (via WakerFunc) and scales down (via SleeperFunc).
	// Returns true if this is the first state change, which is intended to be used in a guarded conditional such as
	//
	// 	if scalingTarget.StartScaling() {
	//    defer scalingTarget.EndScaling()
	//    // invoke sleeper/waker
	// 	}
	StartScaling() bool
	EndScaling() bool
	// ScalingKey returns a unique identifier for the target suitable for use as a map key.
	ScalingKey() string
	IsScaling() bool
}

type Server

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

func NewServer

func NewServer(ctx context.Context, config *Config) (*Server, error)

func (*Server) AcceptConnection

func (s *Server) AcceptConnection(conn net.Conn)

AcceptConnection provides a way to externally supply a connection to consume Notes: - this will bypass rate limiting - this function returns immediately by starting its own go routine to handle the connection

func (*Server) ReloadConfig

func (s *Server) ReloadConfig()

ReloadConfig indicates that an external request, such as a SIGHUP, is requesting the routes config file to be reloaded, if enabled

func (*Server) Run

func (s *Server) Run()

Run will run the server until the context is done or a fatal error occurs, so this should be in a go routine.

func (*Server) WithRoutesListener added in v1.45.1

func (s *Server) WithRoutesListener(listener RoutesListener)

type SleeperFunc added in v1.38.0

type SleeperFunc func(ctx context.Context) error

SleeperFunc is a function that puts a server to sleep.

type WakerFunc added in v1.38.0

type WakerFunc func(ctx context.Context) (string, error)

TODO make sure WakerFunc and SleeperFunc are guarded by ScalingTarget.StartScaling and EndScaling- WakerFunc is a function that wakes up a server and returns its address.

type WebhookConfig

type WebhookConfig struct {
	Url         string         `usage:"If set, a POST request that contains connection status notifications will be sent to this HTTP address"`
	RequireUser bool           `` /* 126-byte string literal not displayed */
	Timeout     time.Duration  `default:"30s" usage:"Timeout for each connection status notification request"`
	Events      []WebhookEvent `` /* 198-byte string literal not displayed */
}

type WebhookEvent added in v1.44.0

type WebhookEvent string
const (
	WebhookEventConnecting          WebhookEvent = "connect"
	WebhookEventDisconnecting       WebhookEvent = "disconnect"
	WebhookEventRouteAdded          WebhookEvent = "route-added"
	WebhookEventRouteRemoved        WebhookEvent = "route-removed"
	WebhookEventDefaultRouteSet     WebhookEvent = "default-route-set"
	WebhookEventDefaultRouteRemoved WebhookEvent = "default-route-removed"
)

type WebhookNotifier

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

WebhookNotifier implements ConnectionNotifier by sending a POST request to a webhook URL. The payload is a JSON object defined by WebhookNotifierPayload.

func NewWebhookNotifier

func NewWebhookNotifier(url string, requireUser bool, timeout time.Duration, events []WebhookEvent) *WebhookNotifier

func (*WebhookNotifier) NotifyConnected

func (w *WebhookNotifier) NotifyConnected(ctx context.Context, clientAddr net.Addr, serverAddress string, playerInfo *PlayerInfo, backendHostPort string) error

func (*WebhookNotifier) NotifyDisconnected

func (w *WebhookNotifier) NotifyDisconnected(ctx context.Context, clientAddr net.Addr, serverAddress string, playerInfo *PlayerInfo, backendHostPort string) error

func (*WebhookNotifier) NotifyFailedBackendConnection

func (w *WebhookNotifier) NotifyFailedBackendConnection(ctx context.Context, clientAddr net.Addr, server string,
	playerInfo *PlayerInfo, backendHostPort string, err error) error

func (*WebhookNotifier) NotifyMissingBackend

func (w *WebhookNotifier) NotifyMissingBackend(ctx context.Context, clientAddr net.Addr, server string, playerInfo *PlayerInfo) error

func (*WebhookNotifier) OnDefaultRouteRemoved added in v1.44.0

func (w *WebhookNotifier) OnDefaultRouteRemoved()

func (*WebhookNotifier) OnDefaultRouteSet added in v1.44.0

func (w *WebhookNotifier) OnDefaultRouteSet(backend string)

func (*WebhookNotifier) OnRouteAdded added in v1.44.0

func (w *WebhookNotifier) OnRouteAdded(serverAddress string, backend string)

func (*WebhookNotifier) OnRouteRemoved added in v1.44.0

func (w *WebhookNotifier) OnRouteRemoved(serverAddress string)

type WebhookNotifierPayload

type WebhookNotifierPayload struct {
	Event           WebhookEvent  `json:"event"`
	Timestamp       time.Time     `json:"timestamp"`
	Status          WebhookStatus `json:"status"`
	Client          *ClientInfo   `json:"client,omitempty"`
	Server          string        `json:"server"`
	PlayerInfo      *PlayerInfo   `json:"player,omitempty"`
	BackendHostPort string        `json:"backend,omitempty"`
	Error           string        `json:"error,omitempty"`
}

type WebhookScalePayload added in v1.43.0

type WebhookScalePayload struct {
	Action        string `json:"action"`
	ServerAddress string `json:"serverAddress"`
	Backend       string `json:"backend"`
}

WebhookScalePayload is the JSON body POSTed to the scaler webhook receiver.

type WebhookScaleResponse added in v1.43.0

type WebhookScaleResponse struct {
	Backend string `json:"backend"`
}

WebhookScaleResponse is the optional JSON body a receiver may return from a scale-up call to override the configured backend for this wake — useful when the backend's address is dynamic (e.g. a container IP that changes on every start). An empty/absent body keeps the configured backend.

type WebhookScaler added in v1.43.0

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

WebhookScaler scales statically-configured backends by POSTing to an external HTTP receiver, which owns the privilege to start/stop the backend. A single URL handles both directions; the payload's action field distinguishes scale up from scale down.

func NewWebhookScaler added in v1.43.0

func NewWebhookScaler(url string, headers map[string]string, requestTimeout time.Duration, wakeTimeout time.Duration) *WebhookScaler

NewWebhookScaler builds a WebhookScaler. An empty url disables the waker/sleeper.

type WebhookScalingTarget added in v1.46.0

type WebhookScalingTarget struct {
	ScalingIndicator
	// contains filtered or unexported fields
}

func NewWebhookScalingTarget added in v1.46.0

func NewWebhookScalingTarget(backend string) *WebhookScalingTarget

func (*WebhookScalingTarget) ScalingKey added in v1.46.0

func (t *WebhookScalingTarget) ScalingKey() string

func (*WebhookScalingTarget) String added in v1.46.0

func (t *WebhookScalingTarget) String() string

type WebhookStatus added in v1.44.0

type WebhookStatus string
const (
	WebhookStatusMissingBackend          WebhookStatus = "missing-backend"
	WebhookStatusFailedBackendConnection WebhookStatus = "failed-backend-connection"
	WebhookStatusSuccess                 WebhookStatus = "success"
)

Jump to

Keyboard shortcuts

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