Documentation ¶
Index ¶
- Constants
- Variables
- func InitDefaultPath(path string)
- func InitXdsFlags(serviceCluster, serviceNode string, serviceMeta []string)
- func RegisterConnPoolFactory(protocol api.Protocol, registered bool)
- type Addresses
- type BufferPoolCtx
- type ClientConnection
- type ClientStreamConnection
- type Cluster
- type ClusterConfigFactoryCb
- type ClusterHostFactoryCb
- type ClusterInfo
- type ClusterManager
- type ClusterManagerFilter
- type ClusterSnapshot
- type ClusterStats
- type ConfigUtility
- type ConnectionHandler
- type ConnectionPool
- type ConnectionStats
- type ContextKey
- type CreateConnectionData
- type Decoder
- type Driver
- type Encoder
- type FailureType
- type FallBackPolicy
- type FilterChainFactory
- type HandlerStatus
- type HeaderData
- type HeaderFormat
- type HeaderMap
- type HealthCheckCb
- type HealthCheckSession
- type HealthCheckSessionFactory
- type HealthChecker
- type HealthFlag
- type Host
- type HostInfo
- type HostPredicate
- type HostSet
- type HostStats
- type IoBuffer
- type KeepAlive
- type KeepAliveCallback
- type KeepAliveStatus
- type LBSubsetEntry
- type LBSubsetInfo
- type LbSubsetMap
- type Listener
- type ListenerEventListener
- type ListenerFilter
- type ListenerFilterCallbacks
- type ListenerFilterManager
- type LoadBalancer
- type LoadBalancerContext
- type LoadBalancerType
- type LowerCaseString
- type Metrics
- type MetricsSink
- type Pair
- type Phase
- type PoolEventListener
- type PoolFailureReason
- type Protocol
- type ProtocolEngine
- type QueryParameterMatcher
- type QueryParams
- type RegisterUpstreamUpdateMethodCb
- type RequestInfo
- type Resource
- type ResourceManager
- type Route
- type RouteHandler
- type RouterManager
- type RouterType
- type RouterWrapper
- type Routers
- type SdsClient
- type SdsSecret
- type SdsUpdateCallbackFunc
- type SecretProvider
- type ServerStreamConnection
- type ServerStreamConnectionEventListener
- type SimpleCluster
- type SortedHosts
- type SortedStringSetType
- type Span
- type Stream
- type StreamConnection
- type StreamConnectionEventListener
- type StreamEventListener
- type StreamReceiveListener
- type StreamResetReason
- type StreamSender
- type SubsetMetadata
- type TLSContextManager
- type TLSProvider
- type Tracer
- type TracerBuilder
- type ValueSubsetMap
- type VirtualHost
- type XdsInfo
Constants ¶
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" HeaderXprotocolSubProtocol = "x-mosn-xprotocol-sub-protocol" HeaderXprotocolStreamId = "x-mosn-xprotocol-stream-id" HeaderXprotocolRespStatus = "x-mosn-xprotocol-resp-status" HeaderXprotocolRespIsException = "x-mosn-xprotocol-resp-is-exception" HeaderXprotocolHeartbeat = "x-protocol-heartbeat" )
Header key types
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
const ( CodecExceptionCode = 0 UnknownCode = 2 DeserialExceptionCode = 3 SuccessCode = 200 PermissionDeniedCode = 403 NoHealthUpstreamCode = 502 UpstreamOverFlowCode = 503 TimeoutExceptionCode = 504 LimitExceededCode = 509 )
Error codes, used by top level logic code(like proxy logic).
const ( ErrorSubModuleIO string = "io." ErrorSubModuleProxy = "proxy." ErrorSubModuleAdmin = "admin." ErrorSubModuleCommon = "common." )
sub module name
const ( ErrorKeyAdmin string = 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
const ( DefaultConnReadTimeout = 15 * time.Second DefaultConnWriteTimeout = 15 * time.Second DefaultConnTryTimeout = 60 * time.Second )
Default connection arguments
const ( GlobalTimeout = 60 * time.Second DefaultRouteTimeout = 15 * time.Second SofaRouteMatchKey = "service" RouterMetadataKey = "filter_metadata" RouterMetadataKeyLb = "mosn.lb" SofaRouterType RouterType = "sofa" )
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
const ErrorModuleMosn string = "mosn."
module name
const (
GlobalProxyName = "global"
)
GlobalProxyName represents proxy name for metrics
Variables ¶
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" )
var ( ErrChanFull = errors.New(ChannelFullException) ErrCodecException = errors.New(CodecException) ErrSerializeException = errors.New(SerializeException) ErrDeserializeException = errors.New(DeserializeException) ErrNoStatusCodeForHijack = errors.New(NoStatusCodeForHijackException) )
Errors
var ( ErrConnectionHasClosed = errors.New("connection has closed") ErrWriteTryLockTimeout = errors.New("write trylock has timeout") )
var ConnPoolFactories map[api.Protocol]bool
var (
ErrExit = errors.New("downstream process completed")
)
Functions ¶
func InitDefaultPath ¶
func InitDefaultPath(path string)
func InitXdsFlags ¶
InitXdsFlags init globalXdsInfo
func RegisterConnPoolFactory ¶
Types ¶
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 { api.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) // Shutdown the healthcheck routine, if exists StopHealthChecking() }
Cluster is a group of upstream hosts
type ClusterConfigFactoryCb ¶
ClusterConfigFactoryCb is a callback interface
type ClusterHostFactoryCb ¶
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 api.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 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 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 ConnectionHandler ¶
type ConnectionHandler interface { // AddOrUpdateListener // adds a listener into the ConnectionHandler or // update a listener AddOrUpdateListener(lc *v2.Listener, networkFiltersFactories []api.NetworkFilterChainFactory, streamFiltersFactories []api.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() api.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 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 Host Host }
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 buffer.IoBuffer) (interface{}, error) }
Decoder is a decoder interface to extend various of protocols
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{}) (buffer.IoBuffer, error) }
Encoder is a encoder interface to extend various of protocols
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 api.Connection) CreateListenerFilterChain(listener ListenerFilterManager) }
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 api.RequestInfo) string Append() bool }
type HealthCheckCb ¶
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 { api.HostInfo // HostStats returns the host stats metrics HostStats() HostStats // ClusterInfo returns the cluster info ClusterInfo() ClusterInfo // 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 // Config creates a host config by the host attributes Config() v2.Host }
Host is an upstream host
type HostPredicate ¶
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 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 api.Connection, buf []byte) // OnNewConnection is called on new mosn connection created OnNewConnection(ctx context.Context, conn api.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) 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 }
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 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 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 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 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 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 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 { // 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 api.HeaderMap, randomValue uint64) api.Route // MatchAllRoutes returns all routes with headers MatchAllRoutes(headers api.HeaderMap, randomValue uint64) []api.Route // MatchRouteFromHeaderKV is used to quickly locate and obtain routes in certain scenarios // header is used to find virtual host MatchRouteFromHeaderKV(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(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 ¶
type SdsUpdateCallbackFunc ¶
type SecretProvider ¶
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 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 api.RequestInfo) Tag(key uint64) string FinishSpan() InjectContext(requestHeaders api.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 buffer.IoBuffer) // Protocol on the connection Protocol() api.Protocol // Active streams count ActiveStreamsNum() int // GoAway sends go away to remote for graceful shutdown GoAway() // 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'
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 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 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 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 api.HeaderMap, randomValue uint64) api.Route // GetAllRoutesFromEntries returns all Route matched the condition GetAllRoutesFromEntries(headers api.HeaderMap, randomValue uint64) []api.Route // GetRouteFromHeaderKV is used to quickly locate and obtain routes in certain scenarios GetRouteFromHeaderKV(key, value string) api.Route // AddRoute adds a new route into virtual host AddRoute(route *v2.Router) error // RemoveAllRoutes clear all the routes in the virtual host RemoveAllRoutes() }