Version: v1.5.0 Latest Latest

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

Go to latest
Published: Apr 25, 2023 License: Apache-2.0 Imports: 17 Imported by: 77




View Source
const (
	HeaderGlobalTimeout = "x-mosn-global-timeout"
	HeaderTryTimeout    = "x-mosn-try-timeout"
	HeaderOriginalPath  = "x-mosn-original-path"

MOSN Header keys

View Source
const (
	ChannelFullException = "Channel is full"
	CodecException       = "codec exception occurs"
	SerializeException   = "serialize exception occurs"
	DeserializeException = "deserialize exception occurs"

	NoStatusCodeForHijackException = "no status code found for hijack reply"

Error messages

View Source
const (
	GlobalProxyName       = "global"
	GlobalShutdownTimeout = "GlobalShutdownTimeout"

GlobalProxyName represents proxy name for metrics

View Source
const (
	AllHostMetaKey  = "MOSN-Subset-All"
	FallbackMetaKey = "MOSN-Subset-Fallback"
	MetaKeySep      = "->"
View Source
const (
	ErrorSubModuleIO     string = "io."
	ErrorSubModuleProxy         = "proxy."
	ErrorSubModuleAdmin         = "admin."
	ErrorSubModuleCommon        = "common."

sub module name

View Source
const (
	ErrorKeyAdmin        string = ErrorModuleMosn + ErrorSubModuleAdmin + "admin_failed"
	ErrorKeyConfigParse         = ErrorModuleMosn + ErrorSubModuleCommon + "config_parse_error"
	ErrorKeyConfigDump          = ErrorModuleMosn + ErrorSubModuleCommon + "config_dump_failed"
	ErrorKeyReconfigure         = ErrorModuleMosn + ErrorSubModuleCommon + "reconfigure_failed"
	ErrorKeyTLSFallback         = ErrorModuleMosn + ErrorSubModuleCommon + "tls_fallback"
	ErrorKeySdsFailed           = ErrorModuleMosn + ErrorSubModuleCommon + "sds_failed"
	ErrorKeyTLSRead             = ErrorModuleMosn + ErrorSubModuleCommon + "tls_read_error"
	ErrorKeyRouteMatch          = ErrorModuleMosn + ErrorSubModuleProxy + "route_match_failed"
	ErrorKeyClusterGet          = ErrorModuleMosn + ErrorSubModuleProxy + "cluster_get_failed"
	ErrorKeyUpstreamConn        = ErrorModuleMosn + ErrorSubModuleProxy + "upstream_conn_failed"
	ErrorKeyCodec               = ErrorModuleMosn + ErrorSubModuleProxy + "codec_error"
	ErrorKeyHeartBeat           = ErrorModuleMosn + ErrorSubModuleProxy + "heartbeat_unknown"
	ErrorKeyProxyPanic          = ErrorModuleMosn + ErrorSubModuleProxy + "panic"

error keys

View Source
const (
	GlobalTimeout       = 60 * time.Second
	DefaultRouteTimeout = 15 * time.Second
	RPCRouteMatchKey    = "service"
	RouterMetadataKey   = "filter_metadata"
	RouterMetadataKeyLb = "mosn.lb"
View Source
const (
	VarStartTime                      string = "start_time"
	VarRequestReceivedDuration        string = "request_received_duration"
	VarResponseReceivedDuration       string = "response_received_duration"
	VarRequestFinishedDuration        string = "request_finished_duration"
	VarProcessTimeDuration            string = "process_time_duration"
	VarBytesSent                      string = "bytes_sent"
	VarBytesReceived                  string = "bytes_received"
	VarProtocol                       string = "protocol"
	VarResponseCode                   string = "response_code"
	VarDuration                       string = "duration"
	VarResponseFlag                   string = "response_flag"
	VarResponseFlags                  string = "response_flags"
	VarUpstreamLocalAddress           string = "upstream_local_address"
	VarDownstreamLocalAddress         string = "downstream_local_address"
	VarDownstreamRemoteAddress        string = "downstream_remote_address"
	VarUpstreamHost                   string = "upstream_host"
	VarUpstreamTransportFailureReason string = "upstream_transport_failure_reason"
	VarUpstreamCluster                string = "upstream_cluster"
	VarRequestedServerName            string = "requested_server_name"
	VarRouteName                      string = "route_name"
	VarProtocolConfig                 string = "protocol_config"

	// ReqHeaderPrefix is the prefix of request header's formatter
	VarPrefixReqHeader string = "request_header_"
	// RespHeaderPrefix is the prefix of response header's formatter
	VarPrefixRespHeader string = "response_header_"

[Proxy]: the identification of a request info's content

View Source
const (
	VarProxyTryTimeout       string = "proxy_try_timeout"
	VarProxyGlobalTimeout    string = "proxy_global_timeout"
	VarProxyHijackStatus     string = "proxy_hijack_status"
	VarProxyGzipSwitch       string = "proxy_gzip_switch"
	VarProxyIsDirectResponse string = "proxy_direct_response"
	VarProxyDisableRetry     string = "proxy_disable_retry"
	VarDirection             string = "x-mosn-direction"
	VarScheme                string = "x-mosn-scheme"
	VarHost                  string = "x-mosn-host"
	VarPath                  string = "x-mosn-path"
	VarPathOriginal          string = "x-mosn-path-original"
	VarQueryString           string = "x-mosn-querystring"
	VarMethod                string = "x-mosn-method"
	VarIstioHeaderHost       string = "authority"
	VarHeaderStatus          string = "x-mosn-status"
	VarHeaderRPCService      string = "x-mosn-rpc-service"
	VarHeaderRPCMethod       string = "x-mosn-rpc-method"

	// notice: read-only!!! do not modify the raw data!!!
	VarRequestRawData string = "x-mosn-req-raw-data"
	// notice: read-only!!! do not modify the raw data!!!
	VarResponseRawData string = "x-mosn-resp-raw-data"

[Proxy]: internal communication

View Source
const (
	VarProtocolRequestScheme       = "request_scheme"
	VarProtocolRequestMethod       = "request_method"
	VarProtocolRequestLength       = "request_length"
	VarProtocolRequestHeader       = "request_header_"
	VarProtocolCookie              = "cookie_"
	VarProtocolRequestPath         = "request_path"
	VarProtocolRequestPathOriginal = "request_path_original"
	VarProtocolRequestArgPrefix    = "request_arg_"
	VarProtocolRequestArg          = "request_arg"
	VarProtocolRequestUri          = "request_uri"
	VarProtocolRequestUseStream    = "request_use_stream"
	VarProtocolResponseUseStream   = "response_use_stream"

[Protocol]: common

View Source
const (
	VarHttpRequestScheme       = httpProtocolName + "_" + VarProtocolRequestScheme
	VarHttpRequestMethod       = httpProtocolName + "_" + VarProtocolRequestMethod
	VarHttpRequestLength       = httpProtocolName + "_" + VarProtocolRequestLength
	VarHttpRequestUri          = httpProtocolName + "_" + VarProtocolRequestUri
	VarHttpRequestPath         = httpProtocolName + "_" + VarProtocolRequestPath
	VarHttpRequestPathOriginal = httpProtocolName + "_" + VarProtocolRequestPathOriginal
	VarHttpRequestArg          = httpProtocolName + "_" + VarProtocolRequestArg
	VarPrefixHttpHeader        = httpProtocolName + "_" + VarProtocolRequestHeader
	VarPrefixHttpArg           = httpProtocolName + "_" + VarProtocolRequestArgPrefix
	VarPrefixHttpCookie        = httpProtocolName + "_" + VarProtocolCookie

[Protocol]: http1

View Source
const (
	VarHttp2RequestScheme       = http2ProtocolName + "_" + VarProtocolRequestScheme
	VarHttp2RequestMethod       = http2ProtocolName + "_" + VarProtocolRequestMethod
	VarHttp2RequestLength       = http2ProtocolName + "_" + VarProtocolRequestLength
	VarHttp2RequestUri          = http2ProtocolName + "_" + VarProtocolRequestUri
	VarHttp2RequestPath         = http2ProtocolName + "_" + VarProtocolRequestPath
	VarHttp2RequestPathOriginal = http2ProtocolName + "_" + VarProtocolRequestPathOriginal
	VarHttp2RequestArg          = http2ProtocolName + "_" + VarProtocolRequestArg
	VarHttp2RequestUseStream    = http2ProtocolName + "_" + VarProtocolRequestUseStream
	VarHttp2ResponseUseStream   = http2ProtocolName + "_" + VarProtocolResponseUseStream
	VarPrefixHttp2Header        = http2ProtocolName + "_" + VarProtocolRequestHeader
	VarPrefixHttp2Arg           = http2ProtocolName + "_" + VarProtocolRequestArgPrefix
	VarPrefixHttp2Cookie        = http2ProtocolName + "_" + VarProtocolCookie

[Protocol]: http2

View Source
const (
	VarStreamID                    = "stream_id"
	VarConnection                  = "connection"
	VarConnectionID                = "connection_id"
	VarConnectionPoolIndex         = "connection_pool_index"
	VarListenerPort                = "listener_port"
	VarListenerName                = "listener_name"
	VarListenerType                = "listener_type"
	VarConnDefaultReadBufferSize   = "conn_default_read_buffer_size"
	VarNetworkFilterChainFactories = "network_filterchain_factories"
	VarAccessLogs                  = "access_logs"
	VarAcceptChan                  = "accept_chan"
	VarAcceptBuffer                = "accept_buffer"
	VarConnectionFd                = "connection_fd"
	VarTraceSpanKey                = "span_key"
	VarTraceId                     = "trace_id"
	VarProxyGeneralConfig          = "proxy_general_config"
	VarConnectionEventListeners    = "connection_event_listeners"
	VarUpstreamConnectionID        = "upstream_connection_id"
	VarOriRemoteAddr               = "ori_remote_addr"
	VarDownStreamProtocol          = "downstream_protocol"
	VarUpStreamProtocol            = "upstream_protocol"
	VarDownStreamReqHeaders        = "downstream_req_headers"
	VarDownStreamRespHeaders       = "downstream_resp_headers"
	VarTraceSpan                   = "trace_span"

[MOSN]: mosn built-invariables name

View Source
const DefaultAccessLogFormat = "%start_time% %trace_id%  %connection_id% %upstream_connection_id% %request_received_duration% %response_received_duration% %bytes_sent%" + " " +
	"%bytes_received% %protocol% %response_code% %duration% %response_flag% %response_code% %upstream_local_address%" + " " +
	"%downstream_local_address% %downstream_remote_address% %upstream_host%"

DefaultAccessLogFormat provides a pre-defined format

View Source
const DefaultRouteHandler = "default"
View Source
const ErrorModuleMosn string = "mosn."

module name

ResponseFlags sets

View Source
const (
	VarListenerMatchFallbackIP string = "listener_match_fallback_ip"

[server]: common

View Source
const (
	VarRouterMeta string = "x-mosn-router-meta"

Route: internal


View Source
var (
	MosnBasePath = string(os.PathSeparator) + "home" + string(os.PathSeparator) +
		"admin" + string(os.PathSeparator) + "mosn"

	MosnLogBasePath        = MosnBasePath + string(os.PathSeparator) + "logs"
	MosnLogDefaultPath     = MosnLogBasePath + string(os.PathSeparator) + "mosn.log"
	MosnLogProxyPath       = MosnLogBasePath + string(os.PathSeparator) + "proxy.log"
	MosnPidDefaultFileName = MosnLogBasePath + string(os.PathSeparator) + "mosn.pid"

	MosnConfigPath = MosnBasePath + string(os.PathSeparator) + "conf"

	MosnUDSPath                    = MosnConfigPath
	ReconfigureDomainSocket        = MosnUDSPath + string(os.PathSeparator) + "reconfig.sock"
	TransferConnDomainSocket       = MosnUDSPath + string(os.PathSeparator) + "conn.sock"
	TransferStatsDomainSocket      = MosnUDSPath + string(os.PathSeparator) + "stats.sock"
	TransferListenDomainSocket     = MosnUDSPath + string(os.PathSeparator) + "listen.sock"
	TransferMosnconfigDomainSocket = MosnUDSPath + string(os.PathSeparator) + "mosnconfig.sock"
View Source
var (
	ErrChanFull             = errors.New(ChannelFullException)
	ErrCodecException       = errors.New(CodecException)
	ErrSerializeException   = errors.New(SerializeException)
	ErrDeserializeException = errors.New(DeserializeException)

	ErrNoStatusCodeForHijack = errors.New(NoStatusCodeForHijackException)


View Source
var (
	DefaultConnReadTimeout  = 15 * time.Second
	DefaultConnWriteTimeout = 15 * time.Second
	DefaultConnTryTimeout   = 60 * time.Second
	DefaultIdleTimeout      = 90 * time.Second
	DefaultUDPIdleTimeout   = 5 * time.Second
	DefaultUDPReadTimeout   = 1 * time.Second

Default connection arguments

View Source
var (
	ErrConnectionHasClosed    = errors.New("connection has closed")
	ErrWriteTryLockTimeout    = errors.New("write trylock has timeout")
	ErrWriteBufferChanTimeout = errors.New("writeBufferChan has timeout")
View Source
var (
	ErrExit          = errors.New("downstream process completed")
	IsDirectResponse = "true"
	PhaseName        = []string{
		InitPhase:                 "InitPhase",
		DownFilter:                "DownFilter",
		MatchRoute:                "MatchRoute",
		DownFilterAfterRoute:      "DownFilterAfterRoute",
		ChooseHost:                "ChooseHost",
		DownFilterAfterChooseHost: "DownFilterAfterChooseHost",
		DownRecvHeader:            "DownRecvHeader",
		DownRecvData:              "DownRecvData",
		DownRecvTrailer:           "DownRecvTrailer",
		Oneway:                    "Oneway",
		Retry:                     "Retry",
		WaitNotify:                "WaitNotify",
		UpFilter:                  "UpFilter",
		UpRecvHeader:              "UpRecvHeader",
		UpRecvData:                "UpRecvData",
		UpRecvTrailer:             "UpRecvTrailer",
		End:                       "End",
View Source
var (
	VariableStreamID                    = variable.NewVariable(VarStreamID, nil, nil, variable.DefaultSetter, 0)
	VariableConnection                  = variable.NewVariable(VarConnection, nil, nil, variable.DefaultSetter, 0)
	VariableConnectionID                = variable.NewVariable(VarConnectionID, nil, nil, variable.DefaultSetter, 0)
	VariableConnectionPoolIndex         = variable.NewVariable(VarConnectionPoolIndex, nil, nil, variable.DefaultSetter, 0)
	VariableListenerPort                = variable.NewVariable(VarListenerPort, nil, nil, variable.DefaultSetter, 0)
	VariableListenerName                = variable.NewVariable(VarListenerName, nil, nil, variable.DefaultSetter, 0)
	VariableListenerType                = variable.NewVariable(VarListenerType, nil, nil, variable.DefaultSetter, 0)
	VariableConnDefaultReadBufferSize   = variable.NewVariable(VarConnDefaultReadBufferSize, nil, nil, variable.DefaultSetter, 0)
	VariableNetworkFilterChainFactories = variable.NewVariable(VarNetworkFilterChainFactories, nil, nil, variable.DefaultSetter, 0)
	VariableAccessLogs                  = variable.NewVariable(VarAccessLogs, nil, nil, variable.DefaultSetter, 0)
	VariableAcceptChan                  = variable.NewVariable(VarAcceptChan, nil, nil, variable.DefaultSetter, 0)
	VariableAcceptBuffer                = variable.NewVariable(VarAcceptBuffer, nil, nil, variable.DefaultSetter, 0)
	VariableConnectionFd                = variable.NewVariable(VarConnectionFd, nil, nil, variable.DefaultSetter, 0)
	VariableTraceId                     = variable.NewVariable(VarTraceId, nil, nil, variable.DefaultSetter, 0)
	VariableProxyGeneralConfig          = variable.NewVariable(VarProxyGeneralConfig, nil, nil, variable.DefaultSetter, 0)
	VariableConnectionEventListeners    = variable.NewVariable(VarConnectionEventListeners, nil, nil, variable.DefaultSetter, 0)
	VariableUpstreamConnectionID        = variable.NewVariable(VarUpstreamConnectionID, nil, nil, variable.DefaultSetter, 0)
	VariableOriRemoteAddr               = variable.NewVariable(VarOriRemoteAddr, nil, nil, variable.DefaultSetter, 0)
	VariableTraceSpankey                = variable.NewVariable(VarTraceSpanKey, nil, nil, variable.DefaultSetter, 0)
	VariableDownStreamProtocol          = variable.NewVariable(VarDownStreamProtocol, nil, nil, variable.DefaultSetter, 0)
	VariableUpstreamProtocol            = variable.NewVariable(VarUpStreamProtocol, nil, nil, variable.DefaultSetter, 0)
	VariableDownStreamReqHeaders        = variable.NewVariable(VarDownStreamReqHeaders, nil, nil, variable.DefaultSetter, 0)
	VariableDownStreamRespHeaders       = variable.NewVariable(VarDownStreamRespHeaders, nil, nil, variable.DefaultSetter, 0)
	VariableTraceSpan                   = variable.NewVariable(VarTraceSpan, nil, nil, variable.DefaultSetter, 0)


func ConvertReasonToCode added in v0.13.0

func ConvertReasonToCode(reason StreamResetReason) int

ConvertReasonToCode is convert the reason to a spec code.

func InitDefaultPath

func InitDefaultPath(path, UDSDir string)


type ABI added in v0.22.0

type ABI interface {
	// Name returns the name of ABI
	Name() string

	// GetABIImports gets the imports part of the abi
	GetABIImports() interface{}

	// SetImports sets the import part of the abi
	SetABIImports(imports interface{})

	// GetExports returns the export part of the abi
	GetABIExports() interface{}


ABI represents the abi between the host and wasm, which consists of three parts: exports, imports and life-cycle handler *exports* represents the exported elements of the wasm module, i.e., the abilities provided by wasm and exposed to host *imports* represents the imported elements of the wasm module, i.e., the dependencies that required by wasm *life-cycle handler* manages the life-cycle of an abi

type ABIHandler added in v0.22.0

type ABIHandler interface {
	// life-cycle: OnInstanceCreate got called when instantiating the wasm instance
	OnInstanceCreate(instance WasmInstance)

	// life-cycle: OnInstanceStart got called when starting the wasm instance
	OnInstanceStart(instance WasmInstance)

	// life-cycle: OnInstanceDestroy got called when destroying the wasm instance
	OnInstanceDestroy(instance WasmInstance)

type BufferPoolCtx

type BufferPoolCtx interface {
	// Index returns the bufferpool's Index
	Index() int

	// New returns the buffer
	New() interface{}

	// Reset resets the buffer

BufferPoolCtx is the bufferpool's context

type ClientConnection

type ClientConnection interface {

	// connect to server in a async way
	Connect() error

	// set SO_MARK with this client Connection

ClientConnection is a wrapper of Connection

type ClientStreamConnection

type ClientStreamConnection interface {

	// NewStream starts to create a new outgoing request stream and returns a sender to write data
	// responseReceiveListener supplies the response listener on decode event
	// StreamSender supplies the sender to write request data
	NewStream(ctx context.Context, responseReceiveListener StreamReceiveListener) StreamSender

ClientStreamConnection is a client side stream connection.

type Cluster

type Cluster interface {
	// Snapshot returns the cluster snapshot, which contains cluster info, hostset and load balancer
	Snapshot() ClusterSnapshot

	// UpdateHosts updates the host set's hosts

	// Add health check callbacks in health checker
	AddHealthCheckCallbacks(cb HealthCheckCb)

	// Shutdown the healthcheck routine, if exists

Cluster is a group of upstream hosts

type ClusterConfigFactoryCb

type ClusterConfigFactoryCb interface {
	UpdateClusterConfig(configs []v2.Cluster) error

ClusterConfigFactoryCb is a callback interface

type ClusterHostFactoryCb

type ClusterHostFactoryCb interface {
	UpdateClusterHost(cluster string, hosts []v2.Host) error

type ClusterInfo

type ClusterInfo interface {
	// Name returns the cluster name
	Name() string

	// ClusterType returns the cluster type
	ClusterType() v2.ClusterType

	// LbType returns the cluster's load balancer type
	LbType() LoadBalancerType

	// ConnBufferLimitBytes returns the connection buffer limits
	ConnBufferLimitBytes() uint32

	// MaxRequestsPerConn returns a connection's max request
	MaxRequestsPerConn() uint32

	Mark() uint32

	// Stats returns the cluster's stats metrics
	Stats() *ClusterStats

	// ResourceManager returns the ResourceManager
	ResourceManager() ResourceManager

	// TLSMng returns the tls manager
	TLSMng() TLSClientContextManager

	// LbSubsetInfo returns the load balancer subset's config
	LbSubsetInfo() LBSubsetInfo

	// ConnectTimeout returns the connect timeout
	ConnectTimeout() time.Duration

	// IdleTimeout returns the idle timeout
	IdleTimeout() time.Duration

	// LbOriDstInfo returns the load balancer oridst config
	LbOriDstInfo() LBOriDstInfo

	// Optional configuration for the load balancing algorithm selected by
	LbConfig() *v2.LbConfig

	//  Optional configuration for some cluster description
	SubType() string

	// SlowStart returns the slow start configurations
	SlowStart() SlowStart

	// IsClusterPoolEnable returns the cluster pool enable or not
	IsClusterPoolEnable() bool

ClusterInfo defines a cluster's information

type ClusterManager

type ClusterManager interface {
	// Add or update a cluster via API.
	AddOrUpdatePrimaryCluster(cluster v2.Cluster) error

	// AddOrUpdateClusterAndHost
	AddOrUpdateClusterAndHost(cluster v2.Cluster, hosts []v2.Host) error

	// Cluster Update functions, keep AddOrUpdatePrimaryCluster and AddOrUpdateClusterAndHost for compatible
	UpdateCluster(cluster v2.Cluster, clusterHandler ClusterUpdateHandler) error

	// Add Cluster health check callbacks
	AddClusterHealthCheckCallbacks(name string, cb HealthCheckCb) error

	// Get, use to get the snapshot of a cluster
	GetClusterSnapshot(context context.Context, cluster string) ClusterSnapshot

	// Deprecated: PutClusterSnapshot exists for historical compatibility and should not be used.

	// UpdateClusterHosts used to update cluster's hosts
	// temp interface todo: remove it
	UpdateClusterHosts(cluster string, hosts []v2.Host) error

	// AppendClusterHosts used to add cluster's hosts
	AppendClusterHosts(clusterName string, hostConfigs []v2.Host) error

	// Host Update functions, keep UpdateClusterHosts and AppendClusterHosts for compatible
	UpdateHosts(clusterName string, hostConfigs []v2.Host, hostHandler HostUpdateHandler) error

	// Get or Create tcp conn pool for a cluster
	TCPConnForCluster(balancerContext LoadBalancerContext, snapshot ClusterSnapshot) CreateConnectionData

	// Get or Create tcp conn pool for a cluster
	UDPConnForCluster(balancerContext LoadBalancerContext, snapshot ClusterSnapshot) CreateConnectionData

	// ConnPoolForCluster used to get protocol related conn pool
	ConnPoolForCluster(balancerContext LoadBalancerContext, snapshot ClusterSnapshot, protocol api.ProtocolName) (ConnectionPool, Host)

	// RemovePrimaryCluster used to remove cluster from set
	RemovePrimaryCluster(clusters ...string) error

	// ClusterExist, used to check whether 'clusterName' exist or not
	ClusterExist(clusterName string) bool

	// RemoveClusterHosts, remove the host by address string
	RemoveClusterHosts(clusterName string, hosts []string) error

	// TLSManager is used to cluster tls config
	GetTLSManager() TLSClientContextManager
	// UpdateTLSManager updates the tls manager which is used to cluster tls config

	// ShutdownConnectionPool shutdown the connection pool by address and ProtocolName
	// If ProtocolName is not specified, remove the addr's connection pool of all protocols
	ShutdownConnectionPool(proto ProtocolName, addr string)

	// Destroy the cluster manager

ClusterManager manages connection pools and load balancing for upstream clusters.

type ClusterManagerFilter

type ClusterManagerFilter interface {
	OnCreated(cccb ClusterConfigFactoryCb, chcb ClusterHostFactoryCb)

type ClusterSnapshot

type ClusterSnapshot interface {
	// HostSet returns the cluster snapshot's host set
	HostSet() HostSet

	// ClusterInfo returns the cluster snapshot's cluster info
	ClusterInfo() ClusterInfo

	// LoadBalancer returns the cluster snapshot's load balancer
	LoadBalancer() LoadBalancer

	// IsExistsHosts checks whether the metadata's subset contains host or not
	// if metadata is nil, check the cluster snapshot contains host or not
	IsExistsHosts(metadata api.MetadataMatchCriteria) bool

	HostNum(metadata api.MetadataMatchCriteria) int

ClusterSnapshot is a thread-safe cluster snapshot

type ClusterStats

type ClusterStats struct {
	UpstreamConnectionTotal                        metrics.Counter
	UpstreamConnectionClose                        metrics.Counter
	UpstreamConnectionActive                       metrics.Counter
	UpstreamConnectionConFail                      metrics.Counter
	UpstreamConnectionRetry                        metrics.Counter
	UpstreamConnectionLocalClose                   metrics.Counter
	UpstreamConnectionRemoteClose                  metrics.Counter
	UpstreamConnectionLocalCloseWithActiveRequest  metrics.Counter
	UpstreamConnectionRemoteCloseWithActiveRequest metrics.Counter
	UpstreamConnectionCloseNotify                  metrics.Counter
	UpstreamBytesReadTotal                         metrics.Counter
	UpstreamBytesWriteTotal                        metrics.Counter
	UpstreamRequestTotal                           metrics.Counter
	UpstreamRequestActive                          metrics.Counter
	UpstreamRequestLocalReset                      metrics.Counter
	UpstreamRequestRemoteReset                     metrics.Counter
	UpstreamRequestRetry                           metrics.Counter
	UpstreamRequestRetryOverflow                   metrics.Counter
	UpstreamRequestTimeout                         metrics.Counter
	UpstreamRequestFailureEject                    metrics.Counter
	UpstreamRequestPendingOverflow                 metrics.Counter
	UpstreamRequestDuration                        metrics.Histogram
	UpstreamRequestDurationEWMA                    metrics.EWMA
	UpstreamRequestDurationTotal                   metrics.Counter
	UpstreamResponseSuccess                        metrics.Counter
	UpstreamResponseFailed                         metrics.Counter
	LBSubSetsFallBack                              metrics.Counter
	LBSubsetsCreated                               metrics.Gauge

ClusterStats defines a cluster's statistics information

type ClusterUpdateHandler added in v1.1.0

type ClusterUpdateHandler func(oldCluster, newCluster Cluster)

CDS Handler for cluster manager

type ConnectionHandler

type ConnectionHandler interface {
	// AddOrUpdateListener
	// adds a listener into the ConnectionHandler or
	// updates a listener
	AddOrUpdateListener(lc *v2.Listener) (ListenerEventListener, error)

	//StartListeners starts all listeners the ConnectionHandler has
	StartListeners(lctx context.Context)

	// FindListenerByAddress finds and returns a listener by the specified network address
	FindListenerByAddress(addr net.Addr) Listener

	// FindListenerByName finds and returns a listener by the listener name
	FindListenerByName(name string) Listener

	// RemoveListeners finds and removes a listener by listener name.
	RemoveListeners(name string)

	// GracefulStopListener graceful stops a listener by listener name
	// stop accept connections + graceful stop existing connections
	GracefulStopListener(lctx context.Context, name string) error

	// GracefulCloseListener graceful closes a listener by listener name
	// stop accept connections + graceful stop existing connections + close listener
	GracefulCloseListener(lctx context.Context, name string) error

	// GracefulStopListeners stops accept connections from all listeners the ConnectionHandler has.
	// and graceful stop all the existing connections.
	GracefulStopListeners() error

	// CloseListeners closes listeners immediately

	// ListListenersFile reports all listeners' fd
	ListListenersFile(lctx context.Context) []*os.File

	// StopConnection Stop Connection

ConnectionHandler contains the listeners for a mosn server

type ConnectionPool

type ConnectionPool interface {
	Protocol() api.ProtocolName

	NewStream(ctx context.Context, receiver StreamReceiveListener) (Host, StreamSender, PoolFailureReason)

	// check host health and init host
	CheckAndInit(ctx context.Context) bool

	// TLSHashValue returns the TLS Config's HashValue.
	// If HashValue is changed, the connection pool will be changed.
	TLSHashValue() *HashValue

	// Shutdown gracefully shuts down the connection pool without interrupting any active requests


	// Host get host
	Host() Host

ConnectionPool is a connection pool interface to extend various of protocols

type ConnectionStats

type ConnectionStats struct {
	ReadTotal     metrics.Counter
	ReadBuffered  metrics.Gauge
	WriteTotal    metrics.Counter
	WriteBuffered metrics.Gauge

ConnectionStats is a group of connection metrics

type CreateConnectionData

type CreateConnectionData struct {
	Connection ClientConnection
	Host       Host

type FailureType

type FailureType string

FailureType is the type of a failure

const (
	FailureNetwork FailureType = "Network"
	FailurePassive FailureType = "Passive"
	FailureActive  FailureType = "Active"

Failure types

type FallBackPolicy

type FallBackPolicy uint8

FallBackPolicy type

const (
	NoFallBack FallBackPolicy = iota

FallBackPolicy types

type FilterChainFactory

type FilterChainFactory interface {
	CreateNetworkFilterChain(conn api.Connection)

	CreateListenerFilterChain(listener ListenerFilterManager)

type HandlerStatus

type HandlerStatus int

HandlerStatus returns the Handler's available status

const (
	HandlerAvailable HandlerStatus = iota

HandlerStatus enum

type HashValue added in v0.15.0

type HashValue struct {
	// contains filtered or unexported fields

func NewHashValue added in v0.15.0

func NewHashValue(v [sha256.Size]byte) *HashValue

func (*HashValue) Equal added in v0.15.0

func (v *HashValue) Equal(hash *HashValue) bool

func (*HashValue) String added in v0.15.0

func (v *HashValue) String() string

type HeaderFormat

type HeaderFormat interface {
	Format(info api.RequestInfo) string
	Append() bool

type HeaderMap

type HeaderMap = api.HeaderMap

type HeaderMatcher added in v0.21.0

type HeaderMatcher interface {
	// HeaderMatchCriteria returns the route's HeaderMatchCriteria
	HeaderMatchCriteria() api.KeyValueMatchCriteria

	// Matches  check whether the headers specified in the config are present in a request.
	// If all the headers (and values) in the header matcher  are found in the request_headers, return true.
	Matches(ctx context.Context, requestHeaders api.HeaderMap) bool

HeaderMatcher match request's headers

type HealthCheckCb

type HealthCheckCb func(host Host, changedState bool, isHealthy bool)

HealthCheckCb is the health check's callback function

type HealthCheckLog added in v1.4.0

type HealthCheckLog interface {
	Log(host Host, changedState bool, isHealthy bool)

type HealthCheckSession

type HealthCheckSession interface {
	// CheckHealth returns true if session checks the server is ok, or returns false
	CheckHealth() bool
	// OnTimeout is called when a check health does not return after timeout duration

HealthCheckSession is an interface for health check logic The health checker framework support register different session for different protocol. The default session implementation is tcp dial, for all non-registered protocol.

type HealthCheckSessionFactory

type HealthCheckSessionFactory interface {
	NewSession(cfg map[string]interface{}, host Host) HealthCheckSession

HealthCheckSessionFactory creates a HealthCheckSession

type HealthChecker

type HealthChecker interface {
	// Start makes health checker running
	// Stop terminates health checker
	// AddHostCheckCompleteCb adds a new callback for health check
	AddHostCheckCompleteCb(cb HealthCheckCb)
	// SetHealthCheckerHostSet reset the health checker's hostset

HealthChecker is a framework for connection management When NewCluster is called, and the config contains health check related, mosn will create a cluster with health check to make sure load balance always choose the "good" host

type Host

type Host interface {

	// HostStats returns the host stats metrics
	HostStats() *HostStats

	// ClusterInfo returns the cluster info
	ClusterInfo() ClusterInfo
	// SetClusterInfo updates the host's cluster info
	SetClusterInfo(info ClusterInfo)

	// TLSHashValue TLS HashValue effects the host support tls state
	TLSHashValue() *HashValue
	// CreateConnection a connection for this host.
	CreateConnection(context context.Context) CreateConnectionData

	// CreateUDPConnection an udp connection for this host.
	CreateUDPConnection(context context.Context) CreateConnectionData

	// Address returns the host's Addr structure
	Address() net.Addr
	// Config creates a host config by the host attributes
	Config() v2.Host

	// LastHealthCheckPassTime returns the timestamp when host has translated from unhealthy to healthy state
	LastHealthCheckPassTime() time.Time
	// SetLastHealthCheckPassTime updates the timestamp when host has translated from unhealthy to healthy state,
	// or translated from other host
	SetLastHealthCheckPassTime(lastHealthCheckPassTime time.Time)

Host is an upstream host

type HostInfo

type HostInfo = api.HostInfo

type HostPredicate

type HostPredicate func(Host) bool

HostPredicate checks whether the host is matched the metadata

type HostSet

type HostSet interface {
	// Size return len(hosts) in hostSet
	Size() int

	// Get get hosts[i] in hostSet
	// The value range of i should be [0, len(hosts) )
	Get(i int) Host
	// Range iterates each host in hostSet
	Range(func(Host) bool)

HostSet is as set of hosts that contains all the endpoints for a given

type HostStats

type HostStats struct {
	UpstreamConnectionTotal                        metrics.Counter
	UpstreamConnectionClose                        metrics.Counter
	UpstreamConnectionActive                       metrics.Counter
	UpstreamConnectionConFail                      metrics.Counter
	UpstreamConnectionLocalClose                   metrics.Counter
	UpstreamConnectionRemoteClose                  metrics.Counter
	UpstreamConnectionLocalCloseWithActiveRequest  metrics.Counter
	UpstreamConnectionRemoteCloseWithActiveRequest metrics.Counter
	UpstreamConnectionCloseNotify                  metrics.Counter
	UpstreamRequestTotal                           metrics.Counter
	UpstreamRequestActive                          metrics.Counter
	UpstreamRequestLocalReset                      metrics.Counter
	UpstreamRequestRemoteReset                     metrics.Counter
	UpstreamRequestTimeout                         metrics.Counter
	UpstreamRequestFailureEject                    metrics.Counter
	UpstreamRequestPendingOverflow                 metrics.Counter
	UpstreamRequestDuration                        metrics.Histogram
	UpstreamRequestDurationEWMA                    metrics.EWMA
	UpstreamRequestDurationTotal                   metrics.Counter
	UpstreamResponseSuccess                        metrics.Counter
	UpstreamResponseFailed                         metrics.Counter

HostStats defines a host's statistics information

type HostUpdateHandler added in v1.1.0

type HostUpdateHandler func(cluster Cluster, hostConfigs []v2.Host)

EDS Handler for cluster manager

type IoBuffer

type IoBuffer = buffer.IoBuffer

IoBuffer use alias to keep compatible

type KeepAlive

type KeepAlive interface {
	// SendKeepAlive sends a heartbeat request for keepalive
	// StartIdleTimeout starts the idle checker, if there are only heartbeat requests for a while,
	// we will free the idle always connection, stop keeps it alive.
	GetTimeout() time.Duration
	HandleTimeout(id uint64)
	HandleSuccess(id uint64)
	AddCallback(cb KeepAliveCallback)

type KeepAliveCallback

type KeepAliveCallback func(KeepAliveStatus)

KeepAliveCallback is a callback when keep alive handle response/timeout

type KeepAliveStatus

type KeepAliveStatus int
const (
	KeepAliveSuccess KeepAliveStatus = iota

type LBOriDstInfo added in v0.11.0

type LBOriDstInfo interface {
	// Check use host header
	IsEnabled() bool

	// GET header name
	GetHeader() string

	IsReplaceLocal() bool

type LBSubsetEntry

type LBSubsetEntry interface {
	// Initialized returns the entry is initialized or not.
	Initialized() bool

	// Active returns the entry is active or not.
	Active() bool

	// Children returns the next lb subset map
	Children() LbSubsetMap

	CreateLoadBalancer(ClusterInfo, HostSet)

	LoadBalancer() LoadBalancer

	HostNum() int

LBSubsetEntry is a entry that stored in the subset hierarchy.

type LBSubsetInfo

type LBSubsetInfo interface {
	// IsEnabled represents whether the subset load balancer is configured or not
	IsEnabled() bool

	// FallbackPolicy returns the fallback policy
	FallbackPolicy() FallBackPolicy

	// DefaultSubset returns the default subset's metadata configure
	// it takes effects when the fallback policy is default subset
	DefaultSubset() SubsetMetadata

	// SubsetKeys returns the sorted subset keys
	SubsetKeys() []SortedStringSetType

type LbSubsetMap

type LbSubsetMap map[string]ValueSubsetMap

LbSubsetMap is a trie-like structure. Route Metadata requires lexically sorted act as the root.

type Listener

type Listener interface {
	// Return config which initialize this listener
	Config() *v2.Listener

	// Set listener config
	SetConfig(config *v2.Listener)

	// Name returns the listener's name
	Name() string

	// Addr returns the listener's network address.
	Addr() net.Addr

	// Start starts listener with context
	Start(lctx context.Context, restart bool)

	// ListenerTag returns the listener's tag, whichi the listener should use for connection handler tracking.
	ListenerTag() uint64

	// Set listener tag
	SetListenerTag(tag uint64)

	// ListenerFile returns a copy a listener file
	ListenerFile() (*os.File, error)

	// PerConnBufferLimitBytes returns the limit bytes per connection
	PerConnBufferLimitBytes() uint32

	// Set limit bytes per connection
	SetPerConnBufferLimitBytes(limitBytes uint32)

	// Set listener original dst type
	SetOriginalDstType(use v2.OriginalDstType)

	// Get listener original dst type
	GetOriginalDstType() v2.OriginalDstType

	// Get if listener should use original dst
	IsOriginalDst() bool

	// SetListenerCallbacks set a listener event listener
	SetListenerCallbacks(cb ListenerEventListener)

	// GetListenerCallbacks set a listener event listener
	GetListenerCallbacks() ListenerEventListener

	// Shutdown stop accepting new connections and graceful stop the existing connections
	Shutdown() error

	// Close closes listener, not closing connections
	Close(lctx context.Context) error

	// IsBindToPort
	IsBindToPort() bool

Listener is a wrapper of tcp listener

type ListenerEventListener

type ListenerEventListener interface {
	// OnAccept is called on new connection accepted
	OnAccept(rawc net.Conn, useOriginalDst bool, oriRemoteAddr net.Addr, c chan api.Connection, buf []byte, listeners []api.ConnectionEventListener)

	// OnNewConnection is called on new mosn connection created
	OnNewConnection(ctx context.Context, conn api.Connection)

	// OnClose is called on listener close

	// OnShutdown is called for graceful stop existing connections

	// PreStopHook is called on listener quit(but before closed)
	PreStopHook(ctx context.Context) func() error

ListenerEventListener is a Callback invoked by a listener.

type ListenerFilter

type ListenerFilter interface {
	// OnAccept is called when a raw connection is accepted, but before a Connection is created.
	OnAccept(cb ListenerFilterCallbacks) api.FilterStatus

type ListenerFilterCallbacks

type ListenerFilterCallbacks interface {
	// Conn returns the Connection reference used in callback handler
	Conn() net.Conn

	ContinueFilterChain(ctx context.Context, success bool)

	// SetOriginalAddr sets the original ip and port
	SetOriginalAddr(ip string, port int)

ListenerFilterCallbacks is a callback handler called by listener filter to talk to listener

type ListenerFilterManager

type ListenerFilterManager interface {
	AddListenerFilter(lf *ListenerFilter)

ListenerFilterManager manages the listener filter Note: unsupport now

type LoadBalancer

type LoadBalancer interface {
	// ChooseHost chooses a host based on the load balancer context
	ChooseHost(context LoadBalancerContext) Host
	// IsExistsHosts checks the load balancer contains hosts or not
	// It will not be effect the load balancer's index
	IsExistsHosts(api.MetadataMatchCriteria) bool

	HostNum(api.MetadataMatchCriteria) int

LoadBalancer is a upstream load balancer. When a request comes, the LoadBalancer will choose a upstream cluster's host to handle the request.

type LoadBalancerContext

type LoadBalancerContext interface {

	// MetadataMatchCriteria gets metadata match criteria used for selecting a subset of hosts
	MetadataMatchCriteria() api.MetadataMatchCriteria

	// DownstreamConnection returns the downstream connection.
	DownstreamConnection() net.Conn

	// DownstreamHeaders returns the downstream headers map.
	DownstreamHeaders() api.HeaderMap

	// DownstreamContext returns the downstream context
	DownstreamContext() context.Context

	// Downstream cluster info
	DownstreamCluster() ClusterInfo

	// Downstream route info
	DownstreamRoute() api.Route

LoadBalancerContext contains the information for choose a host

type LoadBalancerType

type LoadBalancerType string

LoadBalancerType is the load balancer's type

const (
	RoundRobin            LoadBalancerType = "LB_ROUNDROBIN"
	Random                LoadBalancerType = "LB_RANDOM"
	WeightedRoundRobin    LoadBalancerType = "LB_WEIGHTED_ROUNDROBIN"
	ORIGINAL_DST          LoadBalancerType = "LB_ORIGINAL_DST"
	LeastActiveRequest    LoadBalancerType = "LB_LEAST_REQUEST"
	Maglev                LoadBalancerType = "LB_MAGLEV"
	RequestRoundRobin     LoadBalancerType = "LB_REQUEST_ROUNDROBIN"
	LeastActiveConnection LoadBalancerType = "LB_LEAST_CONNECTION"
	PeakEwma              LoadBalancerType = "LB_PEAK_EWMA"

The load balancer's types

type Metrics

type Metrics = api.Metrics

Metrics is a wrapper interface for go-metrics support Counter, Gauge Histogram

type MetricsSink

type MetricsSink = api.MetricsSink

MetricsSink flush metrics to backend storage

type NewConnPool added in v0.26.0

type NewConnPool func(ctx context.Context, host Host) ConnectionPool

NewConnPool is a function to create ConnectionPool

type Pair

type Pair struct {
	T1 string
	T2 string

Pair is a key-value pair that contains metadata.

type Phase

type Phase int
const (
	InitPhase Phase = iota

type PoolFailureReason

type PoolFailureReason string

PoolFailureReason type

const (
	Overflow          PoolFailureReason = "Overflow"
	ConnectionFailure PoolFailureReason = "ConnectionFailure"

PoolFailureReason types

type ProtocolName added in v0.11.0

type ProtocolName = api.ProtocolName

type ProtocolStreamFactory added in v0.26.0

type ProtocolStreamFactory interface {
	CreateClientStream(context context.Context, connection ClientConnection,
		streamConnCallbacks StreamConnectionEventListener,
		callbacks api.ConnectionEventListener) ClientStreamConnection

	CreateServerStream(context context.Context, connection api.Connection,
		callbacks ServerStreamConnectionEventListener) ServerStreamConnection

	CreateBiDirectStream(context context.Context, connection ClientConnection,
		clientCallbacks StreamConnectionEventListener,
		serverCallbacks ServerStreamConnectionEventListener) ClientStreamConnection

	ProtocolMatch(context context.Context, prot string, magic []byte) error

ProtocolStreamFactory can create protocol stream and check whether the request is matched or not.

type QueryParameterMatcher

type QueryParameterMatcher interface {
	// Matches check whether the query parameters specified in the config are present in a request.
	// If all the query params (and values) in the query parameter matcher are found in the query_params, return true.
	Matches(ctx context.Context, requestQueryParams QueryParams) bool

QueryParameterMatcher match request's query parameter

type QueryParams

type QueryParams map[string]string

QueryParams is a string-string map

type RegisterUpstreamUpdateMethodCb

type RegisterUpstreamUpdateMethodCb interface {
	TriggerClusterUpdate(clusterName string, hosts []v2.Host)
	GetClusterNameByServiceName(serviceName string) string

RegisterUpstreamUpdateMethodCb is a callback interface

type RequestInfo

type RequestInfo = api.RequestInfo

type Resource

type Resource interface {
	CanCreate() bool
	Max() uint64
	Cur() int64

Resource is an interface to statistics information

type ResourceManager

type ResourceManager interface {
	// Connections resource to count connections in pool. Only used by protocol which has a connection pool which has multiple connections.
	Connections() Resource

	// Pending request resource to count pending requests. Only used by protocol which has a connection pool and pending requests to assign to connections.
	PendingRequests() Resource

	// Request resource to count requests
	Requests() Resource

	// Retries resource to count retries
	Retries() Resource

ResourceManager manages different types of Resource

type Route

type Route = api.Route

type RouteHandler

type RouteHandler interface {
	// IsAvailable returns HandlerStatus represents the handler will be used/not used/stop next handler check
	IsAvailable(context.Context, ClusterManager) (ClusterSnapshot, HandlerStatus)
	// Route returns handler's route
	Route() api.Route

RouteHandler is an external check handler for a route

type RouterManager

type RouterManager interface {
	// AddOrUpdateRouters used to add or update router
	AddOrUpdateRouters(routerConfig *v2.RouterConfiguration) error
	// GetRouterWrapperByName returns a router wrapper from manager
	GetRouterWrapperByName(routerConfigName string) RouterWrapper
	// AddRoute adds a single router rule into specified virtualhost(by domain)
	AddRoute(routerConfigName, domain string, route *v2.Router) error
	// RemoveAllRoutes clear all the specified virtualhost's routes
	RemoveAllRoutes(routerConfigName, domain string) error

RouterManager is a manager for all routers' config

type RouterType

type RouterType string

type RouterWrapper

type RouterWrapper interface {
	// GetRouters returns the routers in the wrapper
	GetRouters() Routers
	// GetRoutersConfig returns the routers config in the wrapper
	GetRoutersConfig() v2.RouterConfiguration

type Routers

type Routers interface {
	// MatchRoute return first route with headers
	MatchRoute(ctx context.Context, headers api.HeaderMap) api.Route
	// MatchAllRoutes returns all routes with headers
	MatchAllRoutes(ctx context.Context, headers api.HeaderMap) []api.Route
	// MatchRouteFromHeaderKV is used to quickly locate and obtain routes in certain scenarios
	// header is used to find virtual host
	MatchRouteFromHeaderKV(ctx context.Context, headers api.HeaderMap, key, value string) api.Route
	// AddRoute adds a route into virtual host, find virtual host by domain
	// returns the virtualhost index, -1 means no virtual host found
	AddRoute(domain string, route *v2.Router) int
	// RemoveAllRoutes will clear all the routes in the virtual host, find virtual host by domain
	RemoveAllRoutes(domain string) int

Routers defines and manages all router

type SdsClient

type SdsClient interface {
	// AddUpdateCallback will send a sds request to get secret and handle the
	// response by the SdsUpdateCallbackFunc
	AddUpdateCallback(name string, callback SdsUpdateCallbackFunc) error
	DeleteUpdateCallback(name string) error
	// RequireSecret will send a sds request to get secret, the response will be
	// handled by the SdsUpdateCallbackFunc that added by AddUpdateCallback
	RequireSecret(name string)
	// FetchSecret will send a sds request to get secret and wait the response
	// the response will not be handled by the callback functions
	FetchSecret(ctx context.Context, name string) (*SdsSecret, error)

type SdsSecret

type SdsSecret struct {
	Name           string
	CertificatePEM string
	PrivateKeyPEM  string
	ValidationPEM  string

type SdsUpdateCallbackFunc

type SdsUpdateCallbackFunc func(name string, secret *SdsSecret)

type SecretProvider

type SecretProvider interface {
	SetSecret(name string, secret *SdsSecret)
	AckResponse(resp interface{})

type ServerStreamConnection

type ServerStreamConnection interface {

ServerStreamConnection is a server side stream connection.

type ServerStreamConnectionEventListener

type ServerStreamConnectionEventListener interface {

	// NewStreamDetect returns stream event receiver
	NewStreamDetect(context context.Context, sender StreamSender, span api.Span) StreamReceiveListener

ServerStreamConnectionEventListener is a stream connection event listener for server connection

type SimpleCluster

type SimpleCluster interface {
	UpdateHosts(newHosts []Host)

SimpleCluster is a simple cluster in memory

type SlowStart added in v1.5.0

type SlowStart struct {
	Mode              SlowStartMode
	SlowStartDuration time.Duration
	Aggression        float64
	MinWeightPercent  float64

type SlowStartMode added in v1.5.0

type SlowStartMode string
const (
	ModeDuration SlowStartMode = "duration"

type SortedHosts

type SortedHosts []Host

SortedHosts is an implementation of sort.Interface a slice of host can be sorted as address string

func (SortedHosts) Len

func (s SortedHosts) Len() int

func (SortedHosts) Less

func (s SortedHosts) Less(i, j int) bool

func (SortedHosts) Swap

func (s SortedHosts) Swap(i, j int)

type SortedStringSetType

type SortedStringSetType struct {
	// contains filtered or unexported fields

SortedStringSetType is a sorted key collection with no duplicate

func InitSet

func InitSet(input []string) SortedStringSetType

InitSet returns a SortedStringSetType The input key will be sorted and deduplicated

func (*SortedStringSetType) Keys

func (ss *SortedStringSetType) Keys() []string

Keys is the keys in the collection

func (*SortedStringSetType) Len

func (ss *SortedStringSetType) Len() int

Len is the number of elements in the collection.

func (*SortedStringSetType) Less

func (ss *SortedStringSetType) Less(i, j int) bool

Less reports whether the element with index i should sort before the element with index j.

func (*SortedStringSetType) Swap

func (ss *SortedStringSetType) Swap(i, j int)

Swap swaps the elements with indexes i and j.

type Stream

type Stream interface {
	// ID returns unique stream id during one connection life-cycle
	ID() uint64

	// AddEventListener adds stream event listener
	AddEventListener(streamEventListener StreamEventListener)

	// RemoveEventListener removes stream event listener
	RemoveEventListener(streamEventListener StreamEventListener)

	// ResetStream rests and destroys stream, called on exception cases like connection close.
	// Any registered StreamEventListener.OnResetStream and OnDestroyStream will be called.
	ResetStream(reason StreamResetReason)

	// DestroyStream destroys stream, called after stream process in client/server cases.
	// Any registered StreamEventListener.OnDestroyStream will be called.

Stream is a generic protocol stream, it is the core model in stream layer

type StreamConnection

type StreamConnection interface {
	// Dispatch incoming data
	// On data read scenario, it connects connection and stream by dispatching read buffer to stream,
	// stream uses protocol decode data, and popup event to controller
	Dispatch(buffer buffer.IoBuffer)

	// Protocol on the connection
	Protocol() api.ProtocolName

	// EnableWorkerPool means enable worker pool on downstream OnReceive
	EnableWorkerPool() bool

	// Active streams count
	ActiveStreamsNum() int

	// GoAway sends go away to remote for graceful shutdown

	// Reset underlying streams
	Reset(reason StreamResetReason)

	//Check reason
	CheckReasonError(connected bool, event api.ConnectionEvent) (StreamResetReason, bool)

StreamConnection is a connection runs multiple streams

type StreamConnectionEventListener

type StreamConnectionEventListener interface {
	// OnGoAway is called on remote sends 'go away'

StreamConnectionEventListener is a stream connection event listener

type StreamEventListener

type StreamEventListener interface {
	// OnResetStream is called on a stream is been reset
	OnResetStream(reason StreamResetReason)

	// OnDestroyStream is called on stream destroy

StreamEventListener is a stream event listener

type StreamReceiveListener

type StreamReceiveListener interface {
	// OnReceive is called with decoded request/response
	OnReceive(ctx context.Context, headers api.HeaderMap, data buffer.IoBuffer, trailers api.HeaderMap)

	// OnDecodeError is called with when exception occurs
	OnDecodeError(ctx context.Context, err error, headers api.HeaderMap)

StreamReceiveListener is called on data received and decoded On server scenario, StreamReceiveListener is called to handle request On client scenario, StreamReceiveListener is called to handle response

type StreamResetReason

type StreamResetReason = string

StreamResetReason defines the reason why stream reset

const (
	StreamConnectionTermination StreamResetReason = "ConnectionTermination"
	StreamConnectionFailed      StreamResetReason = "ConnectionFailed"
	StreamConnectionSuccessed   StreamResetReason = "ConnectionSuccessed"
	StreamLocalReset            StreamResetReason = "StreamLocalReset"
	StreamOverflow              StreamResetReason = "StreamOverflow"
	StreamRemoteReset           StreamResetReason = "StreamRemoteReset"
	UpstreamReset               StreamResetReason = "UpstreamReset"
	UpstreamGlobalTimeout       StreamResetReason = "UpstreamGlobalTimeout"
	UpstreamPerTryTimeout       StreamResetReason = "UpstreamPerTryTimeout"

Group of stream reset reasons

type StreamSender

type StreamSender interface {
	// Append headers
	// endStream supplies whether this is a header only request/response
	AppendHeaders(ctx context.Context, headers api.HeaderMap, endStream bool) error

	// Append data
	// endStream supplies whether this is the last data frame
	AppendData(ctx context.Context, data buffer.IoBuffer, endStream bool) error

	// Append trailers, implicitly ends the stream.
	AppendTrailers(ctx context.Context, trailers api.HeaderMap) error

	// Get related stream
	GetStream() Stream

StreamSender encodes and sends protocol stream On server scenario, StreamSender sends response On client scenario, StreamSender sends request

type SubsetLoadBalancer added in v1.1.0

type SubsetLoadBalancer interface {
	// LoadBalancers returns all load balancers in
	// the subset load balancer, include load balancers
	// in subset tree and fallback load balancers.
	// the key is metadata information string
	LoadBalancers() map[string]LoadBalancer

SubsetLoadBalancer is a special LoadBalancer consisting of a set of LoadBalancers

type SubsetMetadata

type SubsetMetadata []Pair

SubsetMetadata is a vector of key-values

type TLSClientContextManager added in v0.18.0

type TLSClientContextManager interface {
	// HashValue returns the tls context manager's config hash value
	// If tls enabled is false, the hash value returns nil.
	HashValue() *HashValue
	// Fallback represents the config fallback
	Fallback() bool

TLSClientContextManager manages the cluster tls config

type TLSConfigContext added in v0.15.0

type TLSConfigContext struct {
	// contains filtered or unexported fields

TLSConfigContext contains a tls.Config and a HashValue represents the tls.Config

func NewTLSConfigContext added in v0.15.0

func NewTLSConfigContext(cfg *tls.Config, f func(cfg *tls.Config) *HashValue) *TLSConfigContext

func (*TLSConfigContext) Config added in v0.15.0

func (ctx *TLSConfigContext) Config() *tls.Config

Config returns a tls.Config's copy in config context

func (*TLSConfigContext) HashValue added in v0.15.0

func (ctx *TLSConfigContext) HashValue() *HashValue

HashValue returns a hash value's copy in config context

type TLSContextManager

type TLSContextManager interface {
	// Conn handles the connection, makes a connection as tls connection
	// or keep it as a non-tls connection
	Conn(net.Conn) (net.Conn, error)
	// Enabled returns true means the context manager can make a connection as tls connection
	Enabled() bool

TLSContextManager manages the listener tls config

type TLSProvider

type TLSProvider interface {
	// GetTLSConfigContext returns the configcontext used in connection
	// if client is true, return the client mode config, or returns the server mode config
	GetTLSConfigContext(client bool) *TLSConfigContext
	// MatchedServerName checks whether the server name is matched the stored tls certificate
	MatchedServerName(sn string) bool
	// MatchedALPN checks whether the ALPN is matched the stored tls certificate
	MatchedALPN(protos []string) bool
	// Ready checks whether the provider is inited.
	// the static provider should be always ready.
	Ready() bool
	// Empty represent whether the provider contains a certificate or not.
	// A Ready Provider maybe empty too.
	// the sds provider should be always not empty.
	Empty() bool

TLSProvider provides a tls config for connection the matched function is used for check whether the connection should use this provider

type ValueSubsetMap

type ValueSubsetMap map[string]LBSubsetEntry

ValueSubsetMap is a LBSubsetEntry map.

type VirtualHost

type VirtualHost = api.VirtualHost

type WasmFunction added in v0.22.0

type WasmFunction = common.WasmFunction

type WasmInstance added in v0.22.0

type WasmInstance = common.WasmInstance

type WasmManager added in v0.22.0

type WasmManager interface {
	// AddOrUpdateWasm add or update wasm plugin config
	AddOrUpdateWasm(wasmConfig v2.WasmPluginConfig) error

	// GetWasmPluginWrapperByName returns wasm plugin by name
	GetWasmPluginWrapperByName(pluginName string) WasmPluginWrapper

	// UninstallWasmPluginByName remove wasm plugin by name
	UninstallWasmPluginByName(pluginName string) error

WasmManager managers all wasm configs

type WasmModule added in v0.22.0

type WasmModule = common.WasmModule

type WasmPlugin added in v0.22.0

type WasmPlugin interface {
	// PluginName returns the name of wasm plugin
	PluginName() string

	// GetPluginConfig returns the config of wasm plugin
	GetPluginConfig() v2.WasmPluginConfig

	// GetVmConfig returns the vm config of wasm plugin
	GetVmConfig() v2.WasmVmConfig

	// EnsureInstanceNum tries to expand/shrink the num of instance to 'num'
	// and returns the actual instance num
	EnsureInstanceNum(num int) int

	// InstanceNum returns the current number of wasm instance
	InstanceNum() int

	// GetInstance returns one plugin instance of the plugin
	GetInstance() WasmInstance

	// ReleaseInstance releases the instance to the plugin
	ReleaseInstance(instance WasmInstance)

	// Exec execute the f for each instance
	Exec(f func(instance WasmInstance) bool)

	// SetCpuLimit set cpu limit of the plugin, not supported currently
	SetCpuLimit(cpu int)

	// SetMemLimit set cpu limit of the plugin, not supported currently
	SetMemLimit(mem int)

	// Clear got called when the plugin is destroyed

WasmPlugin manages the collection of wasm plugin instances

type WasmPluginHandler added in v0.22.0

type WasmPluginHandler interface {
	// OnConfigUpdate got called when updating the config of the wasm plugin
	OnConfigUpdate(config v2.WasmPluginConfig)

	// OnPluginStart got called when starting the wasm plugin
	OnPluginStart(plugin WasmPlugin)

	// OnPluginDestroy got called when destroying the wasm plugin
	OnPluginDestroy(plugin WasmPlugin)

WasmPluginHandler provides callbacks to manager the life cycle of the wasm plugin

type WasmPluginWrapper added in v0.22.0

type WasmPluginWrapper interface {
	// GetPlugin returns the wasm plugin
	GetPlugin() WasmPlugin

	// GetConfig returns the config of wasm plugin
	GetConfig() v2.WasmPluginConfig

	// RegisterPluginHandler registers a plugin handler for the wasm plugin
	RegisterPluginHandler(pluginHandler WasmPluginHandler)

	// Update updates the plugin
	Update(config v2.WasmPluginConfig, plugin WasmPlugin)

WasmPluginWrapper wraps wasm plugin with its config and plugin handler

type WasmVM added in v0.22.0

type WasmVM = common.WasmVM

Jump to

Keyboard shortcuts

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