types

package
v0.0.0-...-78a648b Latest Latest
Warning

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

Go to latest
Published: Feb 6, 2020 License: Apache-2.0 Imports: 16 Imported by: 0

Documentation

Index

Constants

View Source
const (
	HeaderStatus        = "x-mosn-status"
	HeaderMethod        = "x-mosn-method"
	HeaderHost          = "x-mosn-host"
	HeaderPath          = "x-mosn-path"
	HeaderQueryString   = "x-mosn-querystring"
	HeaderStreamID      = "x-mosn-streamid"
	HeaderGlobalTimeout = "x-mosn-global-timeout"
	HeaderTryTimeout    = "x-mosn-try-timeout"
	HeaderException     = "x-mosn-exception"
	HeaderStremEnd      = "x-mosn-endstream"
	HeaderRPCService    = "x-mosn-rpc-service"
	HeaderRPCMethod     = "x-mosn-rpc-method"
)

Header key types

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 (
	CodecExceptionCode    = 0
	UnknownCode           = 2
	DeserialExceptionCode = 3
	SuccessCode           = 200
	PermissionDeniedCode  = 403
	RouterUnavailableCode = 404
	NoHealthUpstreamCode  = 502
	UpstreamOverFlowCode  = 503
	TimeoutExceptionCode  = 504
	LimitExceededCode     = 509
)

Error codes, used by top level logic code(like proxy logic).

View Source
const (
	ErrorSubModuleIO     ErrorKey = "io."
	ErrorSubModuleProxy           = "proxy."
	ErrorSubModuleAdmin           = "admin."
	ErrorSubModuleCommon          = "common."
)

sub module name

View Source
const (
	ErrorKeyAdmin        ErrorKey = ErrorModuleMosn + ErrorSubModuleAdmin + "admin_failed"
	ErrorKeyConfigDump            = ErrorModuleMosn + ErrorSubModuleCommon + "config_dump_failed"
	ErrorKeyReconfigure           = ErrorModuleMosn + ErrorSubModuleCommon + "reconfigure_failed"
	ErrorKeyTLSFallback           = ErrorModuleMosn + ErrorSubModuleCommon + "tls_fallback"
	ErrorKeyAppendHeader          = ErrorModuleMosn + ErrorSubModuleProxy + "append_header_failed"
	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"
)

error keys

View Source
const (
	DefaultConnReadTimeout  = 15 * time.Second
	DefaultConnWriteTimeout = 15 * time.Second
)

Default connection arguments

View Source
const (
	GlobalTimeout                  = 60 * time.Second
	DefaultRouteTimeout            = 15 * time.Second
	SofaRouteMatchKey              = "service"
	RouterMetadataKey              = "filter_metadata"
	RouterMetadataKeyLb            = "mosn.lb"
	SofaRouterType      RouterType = "sofa"
)
View Source
const DefaultAccessLogFormat = "%start_time% %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 (
	GlobalProxyName = "global"
)

GlobalProxyName represents proxy name for metrics

Variables

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"

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

	ErrNoStatusCodeForHijack = errors.New(NoStatusCodeForHijackException)
)

Errors

View Source
var ConnPoolFactories map[Protocol]bool
View Source
var (
	ErrConnectionHasClosed = errors.New("connection has closed")
)
View Source
var (
	ErrExit = errors.New("downstream process completed")
)

Functions

func InitDefaultPath

func InitDefaultPath(path string)

func RegisterConnPoolFactory

func RegisterConnPoolFactory(protocol Protocol, registered bool)

Types

type AccessLog

type AccessLog interface {
	// Log write the access info.
	Log(ctx context.Context, reqHeaders HeaderMap, respHeaders HeaderMap, requestInfo RequestInfo)
}

AccessLog is a log object that used to log the access info.

type Addresses

type Addresses []net.Addr

Addresses defines a group of network address

func (Addresses) Contains

func (as Addresses) Contains(addr net.Addr) bool

Contains reports whether the specified network address is in the group.

type BufferPoolCtx

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

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

	// Reset resets the buffer
	Reset(interface{})
}

BufferPoolCtx is the bufferpool's context

type ClientConnection

type ClientConnection interface {
	Connection

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

ClientConnection is a wrapper of Connection

type ClientStreamConnection

type ClientStreamConnection interface {
	StreamConnection

	// 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
	UpdateHosts([]Host)

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

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

	// 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

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

	// ResourceManager returns the ResourceManager
	ResourceManager() ResourceManager

	// TLSMng returns the tls manager
	TLSMng() TLSContextManager

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

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

ClusterInfo defines a cluster's information

type ClusterManager

type ClusterManager interface {
	// Add or update a cluster via API.
	AddOrUpdatePrimaryCluster(cluster v2.Cluster) 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.
	PutClusterSnapshot(ClusterSnapshot)

	// 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

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

	// ConnPoolForCluster used to get protocol related conn pool
	ConnPoolForCluster(balancerContext LoadBalancerContext, snapshot ClusterSnapshot, protocol Protocol) ConnectionPool

	// 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

	// Destroy the cluster manager
	Destroy()
}

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 MetadataMatchCriteria) bool

	HostNum(metadata 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
	UpstreamRequestDurationTotal                   metrics.Counter
	UpstreamResponseSuccess                        metrics.Counter
	UpstreamResponseFailed                         metrics.Counter
	LBSubSetsFallBack                              metrics.Counter
	LBSubsetsCreated                               metrics.Gauge
}

ClusterStats defines a cluster's statistics information

type ConfigUtility

type ConfigUtility interface {
	// MatchHeaders check whether the headers specified in the config are present in a request.
	// If all the headers (and values) in the config_headers are found in the request_headers, return true.
	MatchHeaders(requestHeaders map[string]string, configHeaders []*HeaderData) bool

	// MatchQueryParams check whether the query parameters specified in the config are present in a request.
	// If all the query params (and values) in the config_params are found in the query_params, return true.
	MatchQueryParams(queryParams QueryParams, configQueryParams []QueryParameterMatcher) bool
}

ConfigUtility is utility routines for loading route configuration and matching runtime request headers.

type ConnState

type ConnState int

Connection status

const (
	ConnInit ConnState = iota
	ConnActive
	ConnClosed
)

Connection statuses

type Connection

type Connection interface {
	// ID returns unique connection id
	ID() uint64

	// Start starts connection with context.
	// See context.go to get available keys in context
	Start(lctx context.Context)

	// Write writes data to the connection.
	// Called by other-side stream connection's read loop. Will loop through stream filters with the buffer if any are installed.
	Write(buf ...IoBuffer) error

	// Close closes connection with connection type and event type.
	// ConnectionCloseType - how to close to connection
	// 	- FlushWrite: connection will be closed after buffer flushed to underlying io
	//	- NoFlush: close connection asap
	// ConnectionEvent - why to close the connection
	// 	- RemoteClose
	//  - LocalClose
	// 	- OnReadErrClose
	//  - OnWriteErrClose
	//  - OnConnect
	//  - Connected:
	//	- ConnectTimeout
	//	- ConnectFailed
	Close(ccType ConnectionCloseType, eventType ConnectionEvent) error

	// LocalAddr returns the local address of the connection.
	// For client connection, this is the origin address
	// For server connection, this is the proxy's address
	// TODO: support get local address in redirected request
	// TODO: support transparent mode
	LocalAddr() net.Addr

	// RemoteAddr returns the remote address of the connection.
	RemoteAddr() net.Addr

	// SetRemoteAddr is used for originaldst we need to replace remoteAddr
	SetRemoteAddr(address net.Addr)

	// AddConnectionEventListener add a listener method will be called when connection event occur.
	AddConnectionEventListener(listener ConnectionEventListener)

	// AddBytesReadListener add a method will be called everytime bytes read
	AddBytesReadListener(listener func(bytesRead uint64))

	// AddBytesSentListener add a method will be called everytime bytes write
	AddBytesSentListener(listener func(bytesSent uint64))

	// NextProtocol returns network level negotiation, such as ALPN. Returns empty string if not supported.
	NextProtocol() string

	// SetNoDelay enable/disable tcp no delay
	SetNoDelay(enable bool)

	// SetReadDisable enable/disable read on the connection.
	// If reads are enabled after disable, connection continues to read and data will be dispatched to read filter chains.
	SetReadDisable(disable bool)

	// ReadEnabled returns whether reading is enabled on the connection.
	ReadEnabled() bool

	// TLS returns a related tls connection.
	TLS() net.Conn

	// SetBufferLimit set the buffer limit.
	SetBufferLimit(limit uint32)

	// BufferLimit returns the buffer limit.
	BufferLimit() uint32

	// SetLocalAddress sets a local address
	SetLocalAddress(localAddress net.Addr, restored bool)

	// SetCollector set read/write mertics collectors
	SetCollector(read, write metrics.Counter)
	// LocalAddressRestored returns whether local address is restored
	// TODO: unsupported now
	LocalAddressRestored() bool

	// GetWriteBuffer is used by network writer filter
	GetWriteBuffer() []IoBuffer

	// GetReadBuffer is used by network read filter
	GetReadBuffer() IoBuffer

	// FilterManager returns the FilterManager
	FilterManager() FilterManager

	// RawConn returns the original connections.
	// Caution: raw conn only used in io-loop disable mode
	// TODO: a better way to provide raw conn
	RawConn() net.Conn

	// SetTransferEventListener set a method will be called when connection transfer occur
	SetTransferEventListener(listener func() bool)

	// SetIdleTimeout sets the timeout that will set the connnection to idle. mosn close idle connection
	// if no idle timeout setted or a zero value for d means no idle connections.
	SetIdleTimeout(d time.Duration)

	// State returns the connection state
	State() ConnState
}

Connection interface

type ConnectionCloseType

type ConnectionCloseType string

ConnectionCloseType represent connection close type

const (
	// FlushWrite means write buffer to underlying io then close connection
	FlushWrite ConnectionCloseType = "FlushWrite"
	// NoFlush means close connection without flushing buffer
	NoFlush ConnectionCloseType = "NoFlush"
)

Connection close types

type ConnectionEvent

type ConnectionEvent string

ConnectionEvent type

const (
	RemoteClose     ConnectionEvent = "RemoteClose"
	LocalClose      ConnectionEvent = "LocalClose"
	OnReadErrClose  ConnectionEvent = "OnReadErrClose"
	OnWriteErrClose ConnectionEvent = "OnWriteErrClose"
	OnConnect       ConnectionEvent = "OnConnect"
	Connected       ConnectionEvent = "ConnectedFlag"
	ConnectTimeout  ConnectionEvent = "ConnectTimeout"
	ConnectFailed   ConnectionEvent = "ConnectFailed"
	OnReadTimeout   ConnectionEvent = "OnReadTimeout"
	OnWriteTimeout  ConnectionEvent = "OnWriteTimeout"
)

ConnectionEvent types

func (ConnectionEvent) ConnectFailure

func (ce ConnectionEvent) ConnectFailure() bool

ConnectFailure represents whether the event is triggered by connection failure

func (ConnectionEvent) IsClose

func (ce ConnectionEvent) IsClose() bool

IsClose represents whether the event is triggered by connection close

type ConnectionEventListener

type ConnectionEventListener interface {
	// OnEvent is called on ConnectionEvent
	OnEvent(event ConnectionEvent)
}

ConnectionEventListener is a network level callbacks that happen on a connection.

type ConnectionHandler

type ConnectionHandler interface {
	// AddOrUpdateListener
	// adds a listener into the ConnectionHandler or
	// update a listener
	AddOrUpdateListener(lc *v2.Listener,
		listenerFiltersFactories []ListenerFilterChainFactory,
		networkFiltersFactories []NetworkFilterChainFactory,
		streamFiltersFactories []StreamFilterChainFactory) (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 find and removes a listener by listener name.
	RemoveListeners(name string)

	// StopListener stops a listener  by listener name
	StopListener(lctx context.Context, name string, stop bool) error

	// StopListeners stops all listeners the ConnectionHandler has.
	// The close indicates whether the listening sockets will be closed.
	StopListeners(lctx context.Context, close bool) error

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

	// StopConnection Stop Connection
	StopConnection()
}

ConnectionHandler contains the listeners for a mosn server

type ConnectionPool

type ConnectionPool interface {
	Protocol() Protocol

	NewStream(ctx context.Context, receiver StreamReceiveListener, listener PoolEventListener)

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

	// SupportTLS represents the connection support tls or not
	SupportTLS() bool

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

	Close()
}

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 ContextKey

type ContextKey int

ContextKey type

const (
	ContextKeyStreamID ContextKey = iota
	ContextKeyConnectionID
	ContextKeyConnection
	ContextKeyListenerPort
	ContextKeyListenerName
	ContextKeyListenerType
	ContextKeyListenerStatsNameSpace
	ContextKeyNetworkFilterChainFactories
	ContextKeyStreamFilterChainFactories
	ContextKeyBufferPoolCtx
	ContextKeyAccessLogs
	ContextOriRemoteAddr
	ContextKeyAcceptChan
	ContextKeyAcceptBuffer
	ContextKeyConnectionFd
	ContextSubProtocol
	ContextKeyTraceSpanKey
	ContextKeyActiveSpan
	ContextKeyTraceId
	ContextKeyVariables
	ContextKeyEnd
)

Context key types(built-in)

type CreateConnectionData

type CreateConnectionData struct {
	Connection ClientConnection
	HostInfo   HostInfo
}

type Decoder

type Decoder interface {
	// Decode decodes binary data to a model
	// pass sub protocol type to identify protocol format
	// return 1. decoded model(nil if no enough data) 2. decode error
	Decode(ctx context.Context, data IoBuffer) (interface{}, error)
}

Decoder is a decoder interface to extend various of protocols

type DirectResponseRule

type DirectResponseRule interface {

	// StatusCode returns the repsonse status code
	StatusCode() int
	// Body returns the response body string
	Body() string
}

DirectResponseRule contains direct response info

type DoRetryCallback

type DoRetryCallback func()

type Driver

type Driver interface {
	Init(config map[string]interface{}) error

	Register(proto Protocol, builder TracerBuilder)

	Get(proto Protocol) Tracer
}

type Encoder

type Encoder interface {
	// Encode encodes a model to binary data
	// return 1. encoded bytes 2. encode error
	Encode(ctx context.Context, model interface{}) (IoBuffer, error)
}

Encoder is a encoder interface to extend various of protocols

type ErrorKey

type ErrorKey string
const ErrorModuleMosn ErrorKey = "sofa-mosn."

module name

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
	AnyEndPoint
	DefaultSubset
)

FallBackPolicy types

type FilterChainFactory

type FilterChainFactory interface {
	CreateNetworkFilterChain(conn Connection)

	CreateListenerFilterChain(listener ListenerFilterManager)
}

type FilterManager

type FilterManager interface {
	// AddReadFilter adds a read filter
	AddReadFilter(rf ReadFilter)

	// AddWriteFilter adds a write filter
	AddWriteFilter(wf WriteFilter)

	// ListReadFilter returns the list of read filters
	ListReadFilter() []ReadFilter

	// ListWriteFilters returns the list of write filters
	ListWriteFilters() []WriteFilter

	// InitializeReadFilters initialize read filters
	InitializeReadFilters() bool

	// OnRead is called on data read
	OnRead()

	// OnWrite is called before data write
	OnWrite(buffer []IoBuffer) FilterStatus
}

FilterManager is a groups of filters

type FilterStatus

type FilterStatus string

FilterStatus type

const (
	Continue FilterStatus = "Continue"
	Stop     FilterStatus = "Stop"
)

FilterStatus types

type HandlerStatus

type HandlerStatus int

HandlerStatus returns the Handler's available status

const (
	HandlerAvailable HandlerStatus = iota
	HandlerNotAvailable
	HandlerStop
)

HandlerStatus enum

type HeaderData

type HeaderData struct {
	Name         LowerCaseString
	Value        string
	IsRegex      bool
	RegexPattern *regexp.Regexp
}

HeaderData defines headers data. An empty header value allows for matching to be only based on header presence. Regex is an opt-in. Unless explicitly mentioned, the header values will be used for exact string matching.

type HeaderFormat

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

type HeaderMap

type HeaderMap interface {
	// Get value of key
	// If multiple values associated with this key, first one will be returned.
	Get(key string) (string, bool)

	// Set key-value pair in header map, the previous pair will be replaced if exists
	Set(key, value string)

	// Add value for given key.
	// Multiple headers with the same key may be added with this function.
	// Use Set for setting a single header for the given key.
	Add(key, value string)

	// Del delete pair of specified key
	Del(key string)

	// Range calls f sequentially for each key and value present in the map.
	// If f returns false, range stops the iteration.
	Range(f func(key, value string) bool)

	// Clone used to deep copy header's map
	Clone() HeaderMap

	// ByteSize return size of HeaderMap
	ByteSize() uint64
}

HeaderMap is a interface to provide operation facade with user-value headers

type HealthCheckCb

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

HealthCheckCb is the health check's callback function

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 returned after timeout duration
	OnTimeout()
}

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
	Start()
	// Stop terminates health checker
	Stop()
	// AddHostCheckCompleteCb adds a new callback for health check
	AddHostCheckCompleteCb(cb HealthCheckCb)
	// SetHealthCheckerHostSet reset the health checker's hostset
	SetHealthCheckerHostSet(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 HealthFlag

type HealthFlag int

HealthFlag type

const (
	// The host is currently failing active health checks.
	FAILED_ACTIVE_HC HealthFlag = 0x1
	// The host is currently considered an outlier and has been ejected.
	FAILED_OUTLIER_CHECK HealthFlag = 0x02
)

type Host

type Host interface {
	HostInfo

	// Create a connection for this host.
	CreateConnection(context context.Context) CreateConnectionData

	// ClearHealthFlag clear the input flag
	ClearHealthFlag(flag HealthFlag)

	// ContainHealthFlag checks whether the heatlhy state contains the flag
	ContainHealthFlag(flag HealthFlag) bool

	// SetHealthFlag set the input flag
	SetHealthFlag(flag HealthFlag)

	// HealthFlag returns the current healthy flag
	HealthFlag() HealthFlag

	// Health checks whether the host is healthy or not
	Health() bool

	// Address returns the host's Addr structure
	Address() net.Addr
}

Host is an upstream host

type HostInfo

type HostInfo interface {
	// Hostname returns the host's name
	Hostname() string

	// Metadata returns the host's meta data
	Metadata() v2.Metadata

	// ClusterInfo returns the cluster info
	ClusterInfo() ClusterInfo

	// AddressString retuens the host's address string
	AddressString() string

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

	// Weight returns the host weight
	Weight() uint32

	// Config creates a host config by the host attributes
	Config() v2.Host

	// SupportTLS returns whether the host support tls connections or not
	// If returns true, means support tls connection
	SupportTLS() bool
}

HostInfo defines a host's basic information

type HostPredicate

type HostPredicate func(Host) bool

HostPredicate checks wether the host is matched the metadata

type HostSet

type HostSet interface {
	// Hosts returns all hosts that make up the set at the current time.
	Hosts() []Host

	// HealthyHosts returns all healthy hosts
	HealthyHosts() []Host
}

HostSet is as set of hosts that contains all of 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
	UpstreamRequestDurationTotal                   metrics.Counter
	UpstreamResponseSuccess                        metrics.Counter
	UpstreamResponseFailed                         metrics.Counter
}

HostStats defines a host's statistics information

type IoBuffer

type IoBuffer interface {
	// Read reads the next len(p) bytes from the buffer or until the buffer
	// is drained. The return value n is the number of bytes read. If the
	// buffer has no data to return, err is io.EOF (unless len(p) is zero);
	// otherwise it is nil.
	Read(p []byte) (n int, err error)

	// ReadOnce make a one-shot read and appends it to the buffer, growing
	// the buffer as needed. The return value n is the number of bytes read. Any
	// error except io.EOF encountered during the read is also returned. If the
	// buffer becomes too large, ReadFrom will panic with ErrTooLarge.
	ReadOnce(r io.Reader) (n int64, err error)

	// ReadFrom reads data from r until EOF and appends it to the buffer, growing
	// the buffer as needed. The return value n is the number of bytes read. Any
	// error except io.EOF encountered during the read is also returned. If the
	// buffer becomes too large, ReadFrom will panic with ErrTooLarge.
	ReadFrom(r io.Reader) (n int64, err error)

	// Write appends the contents of p to the buffer, growing the buffer as
	// needed. The return value n is the length of p; err is always nil. If the
	// buffer becomes too large, Write will panic with ErrTooLarge.
	Write(p []byte) (n int, err error)

	// WriteString appends the string to the buffer, growing the buffer as
	// needed. The return value n is the length of s; err is always nil. If the
	// buffer becomes too large, Write will panic with ErrTooLarge.
	WriteString(s string) (n int, err error)

	// WriteTo writes data to w until the buffer is drained or an error occurs.
	// The return value n is the number of bytes written; it always fits into an
	// int, but it is int64 to match the io.WriterTo interface. Any error
	// encountered during the write is also returned.
	WriteTo(w io.Writer) (n int64, err error)

	// Peek returns n bytes from buffer, without draining any buffered data.
	// If n > readable buffer, nil will be returned.
	// It can be used in codec to check first-n-bytes magic bytes
	// Note: do not change content in return bytes, use write instead
	Peek(n int) []byte

	// Bytes returns all bytes from buffer, without draining any buffered data.
	// It can be used to get fixed-length content, such as headers, body.
	// Note: do not change content in return bytes, use write instead
	Bytes() []byte

	// Drain drains a offset length of bytes in buffer.
	// It can be used with Bytes(), after consuming a fixed-length of data
	Drain(offset int)

	// Len returns the number of bytes of the unread portion of the buffer;
	// b.Len() == len(b.Bytes()).
	Len() int

	// Cap returns the capacity of the buffer's underlying byte slice, that is, the
	// total space allocated for the buffer's data.
	Cap() int

	// Reset resets the buffer to be empty,
	// but it retains the underlying storage for use by future writes.
	Reset()

	// Clone makes a copy of IoBuffer struct
	Clone() IoBuffer

	// String returns the contents of the unread portion of the buffer
	// as a string. If the Buffer is a nil pointer, it returns "<nil>".
	String() string

	// Alloc alloc bytes from BytePoolBuffer
	Alloc(int)

	// Free free bytes to BytePoolBuffer
	Free()

	// Count sets and returns reference count
	Count(int32) int32

	// EOF returns whether Io is EOF on the connection
	EOF() bool

	//SetEOF sets the IoBuffer EOF
	SetEOF(eof bool)
}

type KeepAlive

type KeepAlive interface {
	// SendKeepAlive sends a heartbeat request for keepalive
	SendKeepAlive()
	// 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.
	StartIdleTimeout()
	GetTimeout() time.Duration
	HandleTimeout(id uint64)
	HandleSuccess(id uint64)
	AddCallback(cb KeepAliveCallback)
	Stop()
}

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
	KeepAliveTimeout
)

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(LoadBalancerType, 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)

	// Stop stops listener
	// Accepted connections and listening sockets will not be closed
	Stop() error

	// 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 if listener should use original dst
	SetUseOriginalDst(use bool)

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

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

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

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

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 Connection, buf []byte)

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

	// OnClose is called on listener close
	OnClose()
}

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) 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 ListenerFilterChainFactory

type ListenerFilterChainFactory interface {
	OnConn(context context.Context, conn net.Conn) (stoped bool, err error)
}

ListenerFilterChainFactory adds filter into callbacks

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(MetadataMatchCriteria) bool

	HostNum(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() MetadataMatchCriteria

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

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

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

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"
)

The load balancer's types

type LowerCaseString

type LowerCaseString interface {
	Lower()
	Equal(rhs LowerCaseString) bool
	Get() string
}

LowerCaseString is a string wrapper

type MetadataMatchCriteria

type MetadataMatchCriteria interface {
	// @return: a set of MetadataMatchCriterion(metadata) sorted lexically by name
	// to be matched against upstream endpoints when load balancing
	MetadataMatchCriteria() []MetadataMatchCriterion

	MergeMatchCriteria(metadataMatches map[string]interface{}) MetadataMatchCriteria
}

type MetadataMatchCriterion

type MetadataMatchCriterion interface {
	// the name of the metadata key
	MetadataKeyName() string

	// the value for the metadata key
	MetadataValue() string
}

type Metrics

type Metrics interface {
	// Type returns metrics logical type, e.g. 'downstream'/'upstream', this is more like the Subsystem concept
	Type() string

	// Labels used to distinguish the metrics' owner for same metrics key set, like 'cluster: local_service'
	Labels() map[string]string

	// SortedLabels return keys and vals in stable order
	SortedLabels() (keys, vals []string)

	// Counter creates or returns a go-metrics counter by key
	// if the key is registered by other interface, it will be panic
	Counter(key string) metrics.Counter

	// Gauge creates or returns a go-metrics gauge by key
	// if the key is registered by other interface, it will be panic
	Gauge(key string) metrics.Gauge

	// Histogram creates or returns a go-metrics histogram by key
	// if the key is registered by other interface, it will be panic
	Histogram(key string) metrics.Histogram

	// Each call the given function for each registered metric.
	Each(func(string, interface{}))

	// UnregisterAll unregister all metrics.  (Mostly for testing.)
	UnregisterAll()
}

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

type MetricsSink

type MetricsSink interface {
	// Flush flush given metrics
	Flush(writer io.Writer, metrics []Metrics)
}

MetricsSink flush metrics to backend storage

type NetWorkFilterChainFactoryCallbacks

type NetWorkFilterChainFactoryCallbacks interface {
	AddReadFilter(rf ReadFilter)
	AddWriteFilter(wf WriteFilter)
}

NetWorkFilterChainFactoryCallbacks is a wrapper of FilterManager that called in NetworkFilterChainFactory

type NetworkFilterChainFactory

type NetworkFilterChainFactory interface {
	CreateFilterChain(context context.Context, clusterManager ClusterManager, callbacks NetWorkFilterChainFactoryCallbacks)
}

NetworkFilterChainFactory adds filter into NetWorkFilterChainFactoryCallbacks

type Pair

type Pair struct {
	T1 string
	T2 string
}

Pair is a key-value pair that contains metadata.

type PathMatchCriterion

type PathMatchCriterion interface {
	MatchType() PathMatchType
	Matcher() string
}

type PathMatchType

type PathMatchType uint32

PathMatchType defines the match pattern

const (
	None PathMatchType = iota
	Prefix
	Exact
	Regex
	SofaHeader
)

Path match patterns

type Phase

type Phase int
const (
	InitPhase Phase = iota
	DownFilter
	MatchRoute
	DownFilterAfterRoute
	DownRecvHeader
	DownRecvData
	DownRecvTrailer
	Oneway
	Retry
	WaitNofity
	UpFilter
	UpRecvHeader
	UpRecvData
	UpRecvTrailer
	End
)

type Policy

type Policy interface {
	RetryPolicy() RetryPolicy

	ShadowPolicy() ShadowPolicy
}

Policy defines a group of route policy

type PoolEventListener

type PoolEventListener interface {
	OnFailure(reason PoolFailureReason, host Host)

	OnReady(sender StreamSender, host Host)
}

type PoolFailureReason

type PoolFailureReason string

PoolFailureReason type

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

PoolFailureReason types

type Protocol

type Protocol string

type ProtocolEngine

type ProtocolEngine interface {
	// Encoder is a encoder interface to extend various of protocols
	Encoder
	// Decoder is a decoder interface to extend various of protocols
	Decoder

	// Register encoder and decoder for the specified protocol code
	// TODO: use recognize interface instead of protocol code
	Register(protocolCode byte, encoder Encoder, decoder Decoder) error
}

ProtocolEngine is a protocols' facade used by Stream, it provides auto protocol detection by the first byte recognition(called protocol code)

type QueryParameterMatcher

type QueryParameterMatcher interface {
	// Matches returns true if a match for this QueryParameterMatcher exists in request_query_params.
	Matches(requestQueryParams QueryParams) bool
}

QueryParameterMatcher match request's query parameter

type QueryParams

type QueryParams map[string]string

QueryParams is a string-string map

type ReadFilter

type ReadFilter interface {
	// OnData is called everytime bytes is read from the connection
	OnData(buffer IoBuffer) FilterStatus

	// OnNewConnection is called on new connection is created
	OnNewConnection() FilterStatus

	// InitializeReadFilterCallbacks initials read filter callbacks. It used by init read filter
	InitializeReadFilterCallbacks(cb ReadFilterCallbacks)
}

ReadFilter is a connection binary read filter, registered by FilterManager.AddReadFilter

type ReadFilterCallbacks

type ReadFilterCallbacks interface {
	// Connection returns the connection triggered the callback
	Connection() Connection

	// ContinueReading filter iteration on filter stopped, next filter will be called with current read buffer
	ContinueReading()

	// UpstreamHost returns current selected upstream host.
	UpstreamHost() HostInfo

	// SetUpstreamHost set currently selected upstream host.
	SetUpstreamHost(upstreamHost HostInfo)
}

ReadFilterCallbacks is called by read filter to talk to connection

type RegisterUpstreamUpdateMethodCb

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

RegisterUpstreamUpdateMethodCb is a callback interface

type RequestInfo

type RequestInfo interface {
	// StartTime returns the time that request arriving
	StartTime() time.Time

	// SetStartTime sets StartTime
	SetStartTime()

	// RequestReceivedDuration returns duration between request arriving and request forwarding to upstream
	RequestReceivedDuration() time.Duration

	// SetRequestReceivedDuration sets duration between request arriving and request forwarding to upstream
	SetRequestReceivedDuration(time time.Time)

	// ResponseReceivedDuration gets duration between request arriving and response received
	ResponseReceivedDuration() time.Duration

	// SetResponseReceivedDuration sets duration between request arriving and response received
	SetResponseReceivedDuration(time time.Time)

	// RequestFinishedDuration returns duration between request arriving and request finished
	RequestFinishedDuration() time.Duration

	// SetRequestFinishedDuration sets uration between request arriving and request finished
	SetRequestFinishedDuration(time time.Time)

	// BytesSent reports the bytes sent
	BytesSent() uint64

	// SetBytesSent sets the bytes sent
	SetBytesSent(bytesSent uint64)

	// BytesReceived reports the bytes received
	BytesReceived() uint64

	// SetBytesReceived sets the bytes received
	SetBytesReceived(bytesReceived uint64)

	// Protocol returns the request's protocol type
	Protocol() Protocol

	// ResponseCode reports the request's response code
	// The code is http standard status code.
	ResponseCode() int

	// SetResponseCode set request's response code
	// Mosn use http standard status code for log, if a protocol have different status code
	// we will try to mapping it to http status code, and log it
	SetResponseCode(code int)

	// Duration reports the duration since request's starting time
	Duration() time.Duration

	// GetResponseFlag gets request's response flag
	GetResponseFlag(flag ResponseFlag) bool

	// SetResponseFlag sets request's response flag
	SetResponseFlag(flag ResponseFlag)

	//UpstreamHost reports  the selected upstream's host information
	UpstreamHost() HostInfo

	// OnUpstreamHostSelected sets the selected upstream's host information
	OnUpstreamHostSelected(host HostInfo)

	// UpstreamLocalAddress reports the upstream's local network address
	UpstreamLocalAddress() string

	// SetUpstreamLocalAddress sets upstream's local network address
	SetUpstreamLocalAddress(localAddress string)

	// IsHealthCheck checks whether the request is health.
	IsHealthCheck() bool

	// SetHealthCheck sets the request's health state.
	SetHealthCheck(isHc bool)

	// DownstreamLocalAddress reports the downstream's local network address.
	DownstreamLocalAddress() net.Addr

	// SetDownstreamLocalAddress sets the downstream's local network address.
	SetDownstreamLocalAddress(addr net.Addr)

	// DownstreamRemoteAddress reports the downstream's remote network address.
	DownstreamRemoteAddress() net.Addr

	// SetDownstreamRemoteAddress sets the downstream's remote network address.
	SetDownstreamRemoteAddress(addr net.Addr)

	// RouteEntry reports the route rule
	RouteEntry() RouteRule

	// SetRouteEntry sets the route rule
	SetRouteEntry(routerRule RouteRule)
}

RequestInfo has information for a request, include the basic information, the request's downstream information, ,the request's upstream information and the router information.

type Resource

type Resource interface {
	CanCreate() bool
	Increase()
	Decrease()
	Max() uint64
}

Resource is a 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 ResponseFlag

type ResponseFlag int

ResponseFlag type

const (
	// no healthy upstream found
	NoHealthyUpstream ResponseFlag = 0x2
	// Upstream Request timeout
	UpstreamRequestTimeout ResponseFlag = 0x4
	// local reset
	UpstreamLocalReset ResponseFlag = 0x8
	// upstream reset
	UpstreamRemoteReset ResponseFlag = 0x10
	// connect upstream failure
	UpstreamConnectionFailure ResponseFlag = 0x20
	// upstream terminate connection
	UpstreamConnectionTermination ResponseFlag = 0x40
	// upstream's connection overflow
	UpstreamOverflow ResponseFlag = 0x80
	// no route found
	NoRouteFound ResponseFlag = 0x100
	// inject delay
	DelayInjected ResponseFlag = 0x200
	// inject fault
	FaultInjected ResponseFlag = 0x400
	// rate limited
	RateLimited ResponseFlag = 0x800
	// payload limit
	ReqEntityTooLarge ResponseFlag = 0x1000
)

Some Response Flags

type RetryCheckStatus

type RetryCheckStatus int

RetryCheckStatus type

const (
	ShouldRetry   RetryCheckStatus = 0
	NoRetry       RetryCheckStatus = -1
	RetryOverflow RetryCheckStatus = -2
)

RetryCheckStatus types

type RetryPolicy

type RetryPolicy interface {
	RetryOn() bool

	TryTimeout() time.Duration

	NumRetries() uint32
}

RetryPolicy is a type of Policy

type RetryState

type RetryState interface {
	Enabled() bool

	ShouldRetry(respHeaders map[string]string, resetReson string, doRetryCb DoRetryCallback) bool
}

type Route

type Route interface {
	// RouteRule returns the route rule
	RouteRule() RouteRule

	// DirectResponseRule returns direct response rile
	DirectResponseRule() DirectResponseRule
}

Route is a route instance

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() Route
}

RouteHandler is an external check handler for a route

type RouteRule

type RouteRule interface {
	// ClusterName returns the route's cluster name
	ClusterName() string

	// UpstreamProtocol returns the protocol that route's cluster supported
	// If it is configured, the protocol will replace the proxy config's upstream protocol
	UpstreamProtocol() string

	// GlobalTimeout returns the global timeout
	GlobalTimeout() time.Duration

	// VirtualHost returns the route's virtual host
	VirtualHost() VirtualHost

	// Policy returns the route's route policy
	Policy() Policy

	// MetadataMatchCriteria returns the metadata that a subset load balancer should match when selecting an upstream host
	// as we may use weighted cluster's metadata, so need to input cluster's name
	MetadataMatchCriteria(clusterName string) MetadataMatchCriteria

	// PerFilterConfig returns per filter config from xds
	PerFilterConfig() map[string]interface{}

	// FinalizeRequestHeaders do potentially destructive header transforms on request headers prior to forwarding
	FinalizeRequestHeaders(headers HeaderMap, requestInfo RequestInfo)

	// FinalizeResponseHeaders do potentially destructive header transforms on response headers prior to forwarding
	FinalizeResponseHeaders(headers HeaderMap, requestInfo RequestInfo)

	// PathMatchCriterion returns the route's PathMatchCriterion
	PathMatchCriterion() PathMatchCriterion
}

RouteRule defines parameters for a route

type RouterManager

type RouterManager interface {
	// AddRoutersSet adds router config when generated
	AddOrUpdateRouters(routerConfig *v2.RouterConfiguration) error

	GetRouterWrapperByName(routerConfigName string) RouterWrapper

	AddRoute(routerConfigName, domain string, route *v2.Router) error

	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(headers HeaderMap, randomValue uint64) Route
	// MatchAllRoutes returns all routes with headers
	MatchAllRoutes(headers HeaderMap, randomValue uint64) []Route
	// MatchRouteFromHeaderKV is used to quickly locate and obtain routes in certain scenarios
	// header is used to find virtual host
	MatchRouteFromHeaderKV(headers HeaderMap, key, value string) 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(sdsConfig *auth.SdsSecretConfig, callback SdsUpdateCallbackFunc) error
	DeleteUpdateCallback(sdsConfig *auth.SdsSecretConfig) error
	SetSecret(name string, secret *auth.Secret)
}

type SdsSecret

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

func SecretConvert

func SecretConvert(raw *auth.Secret) *SdsSecret

type SdsUpdateCallbackFunc

type SdsUpdateCallbackFunc func(name string, secret *SdsSecret)

type SecretProvider

type SecretProvider interface {
	SetSecret(name string, secret *auth.Secret)
}

type ServerStreamConnection

type ServerStreamConnection interface {
	StreamConnection
}

ServerStreamConnection is a server side stream connection.

type ServerStreamConnectionEventListener

type ServerStreamConnectionEventListener interface {
	StreamConnectionEventListener

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

ServerStreamConnectionEventListener is a stream connection event listener for server connection

type ShadowPolicy

type ShadowPolicy interface {
	ClusterName() string

	RuntimeKey() string
}

ShadowPolicy is a type of Policy

type SimpleCluster

type SimpleCluster interface {
	UpdateHosts(newHosts []Host)
}

SimpleCluster is a simple cluster in memory

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 Span

type Span interface {
	TraceId() string

	SpanId() string

	ParentSpanId() string

	SetOperation(operation string)

	SetTag(key uint64, value string)

	SetRequestInfo(requestInfo RequestInfo)

	Tag(key uint64) string

	FinishSpan()

	InjectContext(requestHeaders HeaderMap)

	SpawnChild(operationName string, startTime time.Time) Span
}

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.
	DestroyStream()
}

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 IoBuffer)

	// Protocol on the connection
	Protocol() Protocol

	// Active streams count
	ActiveStreamsNum() int

	// GoAway sends go away to remote for graceful shutdown
	GoAway()

	// Reset underlying streams
	Reset(reason StreamResetReason)
}

StreamConnection is a connection runs multiple streams

type StreamConnectionEventListener

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

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
	OnDestroyStream()
}

StreamEventListener is a stream event listener

type StreamFilterBase

type StreamFilterBase interface {
	OnDestroy()
}

type StreamFilterChainFactory

type StreamFilterChainFactory interface {
	CreateFilterChain(context context.Context, callbacks StreamFilterChainFactoryCallbacks)
}

StreamFilterChainFactory adds filter into callbacks

type StreamFilterChainFactoryCallbacks

type StreamFilterChainFactoryCallbacks interface {
	AddStreamSenderFilter(filter StreamSenderFilter)

	AddStreamReceiverFilter(filter StreamReceiverFilter, p Phase)

	// add access log per stream
	AddStreamAccessLog(accessLog AccessLog)
}

StreamFilterChainFactoryCallbacks is called in StreamFilterChainFactory

type StreamFilterHandler

type StreamFilterHandler interface {
	// Route returns a route for current stream
	Route() Route

	// RequestInfo returns request info related to the stream
	RequestInfo() RequestInfo

	// Connection returns the originating connection
	Connection() Connection
}

StreamFilterHandler is called by stream filter to interact with underlying stream

type StreamFilterStatus

type StreamFilterStatus string
const (
	// Continue filter chain iteration.
	StreamFilterContinue StreamFilterStatus = "Continue"
	// Do not iterate to next iterator.
	StreamFilterStop StreamFilterStatus = "Stop"

	StreamFilterReMatchRoute StreamFilterStatus = "Retry Match Route"
)

StreamFilterStatus types

type StreamReceiveListener

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

	// OnDecodeError is called with when exception occurs
	OnDecodeError(ctx context.Context, err error, headers 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 StreamReceiverFilter

type StreamReceiverFilter interface {
	StreamFilterBase

	// OnReceive is called with decoded request/response
	OnReceive(ctx context.Context, headers HeaderMap, buf IoBuffer, trailers HeaderMap) StreamFilterStatus

	// SetReceiveFilterHandler sets decoder filter callbacks
	SetReceiveFilterHandler(handler StreamReceiverFilterHandler)
}

StreamReceiverFilter is a StreamFilterBase wrapper

type StreamReceiverFilterHandler

type StreamReceiverFilterHandler interface {
	StreamFilterHandler

	// AppendHeaders is called with headers to be encoded, optionally indicating end of stream
	// Filter uses this function to send out request/response headers of the stream
	// endStream supplies whether this is a header only request/response
	AppendHeaders(headers HeaderMap, endStream bool)

	// AppendData is called with data to be encoded, optionally indicating end of stream.
	// Filter uses this function to send out request/response data of the stream
	// endStream supplies whether this is the last data
	AppendData(buf IoBuffer, endStream bool)

	// AppendTrailers is called with trailers to be encoded, implicitly ends the stream.
	// Filter uses this function to send out request/response trailers of the stream
	AppendTrailers(trailers HeaderMap)

	// SendHijackReply is called when the filter will response directly
	SendHijackReply(code int, headers HeaderMap)

	// SendDirectRespoonse is call when the filter will response directly
	SendDirectResponse(headers HeaderMap, buf IoBuffer, trailers HeaderMap)

	// TODO: remove all of the following when proxy changed to single request @lieyuan
	// StreamFilters will modified headers/data/trailer in different steps
	// for example, maybe modify headers in on receive data
	GetRequestHeaders() HeaderMap
	SetRequestHeaders(headers HeaderMap)

	GetRequestData() IoBuffer
	SetRequestData(buf IoBuffer)

	GetRequestTrailers() HeaderMap
	SetRequestTrailers(trailers HeaderMap)

	SetConvert(on bool)
}

StreamReceiverFilterHandler add additional callbacks that allow a decoding filter to restart decoding if they decide to hold data

type StreamResetReason

type StreamResetReason string

StreamResetReason defines the reason why stream reset

const (
	StreamConnectionTermination StreamResetReason = "ConnectionTermination"
	StreamConnectionFailed      StreamResetReason = "ConnectionFailed"
	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 HeaderMap, endStream bool) error

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

	// Append trailers, implicitly ends the stream.
	AppendTrailers(ctx context.Context, trailers 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 StreamSenderFilter

type StreamSenderFilter interface {
	StreamFilterBase

	// Append encodes request/response
	Append(ctx context.Context, headers HeaderMap, buf IoBuffer, trailers HeaderMap) StreamFilterStatus

	// SetSenderFilterHandler sets the StreamSenderFilterHandler
	SetSenderFilterHandler(handler StreamSenderFilterHandler)
}

StreamSenderFilter is a stream sender filter

type StreamSenderFilterHandler

type StreamSenderFilterHandler interface {
	StreamFilterHandler

	// TODO :remove all of the following when proxy changed to single request @lieyuan
	// StreamFilters will modified headers/data/trailer in different steps
	// for example, maybe modify headers in AppendData
	GetResponseHeaders() HeaderMap
	SetResponseHeaders(headers HeaderMap)

	GetResponseData() IoBuffer
	SetResponseData(buf IoBuffer)

	GetResponseTrailers() HeaderMap
	SetResponseTrailers(trailers HeaderMap)
}

StreamSenderFilterHandler is a StreamFilterHandler wrapper

type SubsetMetadata

type SubsetMetadata []Pair

SubsetMetadata is a vector of key-values

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/cluster's tls config

type TLSProvider

type TLSProvider interface {
	// GetTLSConfig returns the tls config used in connection
	// if client is true, return the client mode config, or returns the server mode config
	GetTLSConfig(client bool) *tls.Config
	// 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 Tracer

type Tracer interface {
	Start(ctx context.Context, request interface{}, startTime time.Time) Span
}

type TracerBuilder

type TracerBuilder func(config map[string]interface{}) (Tracer, error)

factory

type ValueSubsetMap

type ValueSubsetMap map[string]LBSubsetEntry

ValueSubsetMap is a LBSubsetEntry map.

type VirtualHost

type VirtualHost interface {
	Name() string

	// GetRouteFromEntries returns a Route matched the condition
	GetRouteFromEntries(headers HeaderMap, randomValue uint64) Route
	// GetAllRoutesFromEntries returns all Route matched the condition
	GetAllRoutesFromEntries(headers HeaderMap, randomValue uint64) []Route
	// GetRouteFromHeaderKV is used to quickly locate and obtain routes in certain scenarios
	GetRouteFromHeaderKV(key, value string) Route
	// AddRoute adds a new route into virtual host
	AddRoute(route *v2.Router) error
	// RemoveAllRoutes clear all the routes in the virtual host
	RemoveAllRoutes()
}

type WriteFilter

type WriteFilter interface {
	// OnWrite is called before data write to raw connection
	OnWrite(buffer []IoBuffer) FilterStatus
}

WriteFilter is a connection binary write filter, only called by conn accept loop

type XdsInfo

type XdsInfo struct {
	ServiceCluster string
	ServiceNode    string
	Metadata       *types.Struct
}

The xds start parameters

func GetGlobalXdsInfo

func GetGlobalXdsInfo() *XdsInfo

GetGlobalXdsInfo returns pointer of globalXdsInfo

Jump to

Keyboard shortcuts

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