base

package
v1.10.4 Latest Latest
Warning

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

Go to latest
Published: Jan 6, 2023 License: Apache-2.0 Imports: 10 Imported by: 8

Documentation

Index

Constants

View Source
const (
	TotalInBoundResourceName = "__total_inbound_traffic__"

	DefaultMaxResourceAmount uint32 = 10000

	DefaultSampleCount uint32 = 2
	DefaultIntervalMs  uint32 = 1000

	// default 10*1000/500 = 20
	DefaultSampleCountTotal uint32 = 20
	// default 10s (total length)
	DefaultIntervalMsTotal uint32 = 10000

	DefaultStatisticMaxRt = int64(60000)
)

global variable

Variables

View Source
var (
	IllegalGlobalStatisticParamsError = errors.New("Invalid parameters, sampleCount or interval, for resource's global statistic")
	IllegalStatisticParamsError       = errors.New("Invalid parameters, sampleCount or interval, for metric statistic")
	GlobalStatisticNonReusableError   = errors.New("The parameters, sampleCount and interval, mismatch for reusing between resource's global statistic and readonly metric statistic.")
)

Functions

func CheckValidityForReuseStatistic

func CheckValidityForReuseStatistic(sampleCount, intervalInMs uint32, parentSampleCount, parentIntervalInMs uint32) error

CheckValidityForReuseStatistic check the compliance whether readonly metric statistic can be built based on resource's global statistic The parameters, sampleCount and intervalInMs, are the parameters of the metric statistic you want to build The parameters, parentSampleCount and parentIntervalInMs, are the parameters of the resource's global statistic If compliance passes, return nil, if not returns specific error

func CheckValidityForStatistic

func CheckValidityForStatistic(sampleCount, intervalInMs uint32) error

func NopReadStat

func NopReadStat() *nopReadStat

func NopWriteStat

func NopWriteStat() *nopWriteStat

func RegistryBlockType

func RegistryBlockType(blockType BlockType, desc string) error

RegistryBlockType adds block type and corresponding description in order.

Types

type BaseSlot

type BaseSlot interface {
	// Order returns the sort value of the slot.
	// SlotChain will sort all it's slots by ascending sort value in each bucket
	// (StatPrepareSlot bucket、RuleCheckSlot bucket and StatSlot bucket)
	Order() uint32
}

type BlockError

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

BlockError indicates the request was blocked by Sentinel.

func NewBlockError

func NewBlockError(opts ...BlockErrorOption) *BlockError

func NewBlockErrorFromDeepCopy

func NewBlockErrorFromDeepCopy(from *BlockError) *BlockError

func NewBlockErrorWithCause

func NewBlockErrorWithCause(blockType BlockType, blockMsg string, rule SentinelRule, snapshot interface{}) *BlockError

func NewBlockErrorWithMessage

func NewBlockErrorWithMessage(blockType BlockType, message string) *BlockError

func (*BlockError) BlockMsg

func (e *BlockError) BlockMsg() string

func (*BlockError) BlockType

func (e *BlockError) BlockType() BlockType

func (*BlockError) Error

func (e *BlockError) Error() string

func (*BlockError) ResetBlockError

func (e *BlockError) ResetBlockError(opts ...BlockErrorOption)

func (*BlockError) TriggeredRule

func (e *BlockError) TriggeredRule() SentinelRule

func (*BlockError) TriggeredValue

func (e *BlockError) TriggeredValue() interface{}

type BlockErrorOption

type BlockErrorOption func(*BlockError)

func WithBlockMsg

func WithBlockMsg(blockMsg string) BlockErrorOption

func WithBlockType

func WithBlockType(blockType BlockType) BlockErrorOption

func WithRule

func WithRule(rule SentinelRule) BlockErrorOption

func WithSnapshotValue

func WithSnapshotValue(snapshotValue interface{}) BlockErrorOption

type BlockType

type BlockType uint8
const (
	BlockTypeUnknown BlockType = iota
	BlockTypeFlow
	BlockTypeIsolation
	BlockTypeCircuitBreaking
	BlockTypeSystemFlow
	BlockTypeHotSpotParamFlow
)

func (BlockType) String

func (t BlockType) String() string

type ConcurrencyStat

type ConcurrencyStat interface {
	CurrentConcurrency() int32
	IncreaseConcurrency()
	DecreaseConcurrency()
}

type EntryContext

type EntryContext struct {
	Resource *ResourceWrapper
	StatNode StatNode

	Input *SentinelInput
	// the result of rule slots check
	RuleCheckResult *TokenResult
	// reserve for storing some intermediate data from the Entry execution process
	Data map[interface{}]interface{}
	// contains filtered or unexported fields
}

func NewEmptyEntryContext

func NewEmptyEntryContext() *EntryContext

func (*EntryContext) Entry

func (ctx *EntryContext) Entry() *SentinelEntry

func (*EntryContext) Err

func (ctx *EntryContext) Err() error

func (*EntryContext) IsBlocked

func (ctx *EntryContext) IsBlocked() bool

func (*EntryContext) PutRt

func (ctx *EntryContext) PutRt(rt uint64)

func (*EntryContext) Reset

func (ctx *EntryContext) Reset()

Reset init EntryContext,

func (*EntryContext) Rt

func (ctx *EntryContext) Rt() uint64

func (*EntryContext) SetEntry

func (ctx *EntryContext) SetEntry(entry *SentinelEntry)

func (*EntryContext) SetError

func (ctx *EntryContext) SetError(err error)

func (*EntryContext) StartTime

func (ctx *EntryContext) StartTime() uint64

type ExitHandler

type ExitHandler func(entry *SentinelEntry, ctx *EntryContext) error

type ExitOption

type ExitOption func(*ExitOptions)

func WithError

func WithError(err error) ExitOption

type ExitOptions

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

type MetricEvent

type MetricEvent int8
const (
	// sentinel rules check pass
	MetricEventPass MetricEvent = iota
	// sentinel rules check block
	MetricEventBlock

	MetricEventComplete
	// Biz error, used for circuit breaker
	MetricEventError
	// request execute rt, unit is millisecond
	MetricEventRt
	// hack for the number of event
	MetricEventTotal
)

There are five events to record pass + block == Total

type MetricItem

type MetricItem struct {
	Resource       string
	Classification int32
	Timestamp      uint64

	PassQps         uint64
	BlockQps        uint64
	CompleteQps     uint64
	ErrorQps        uint64
	AvgRt           uint64
	OccupiedPassQps uint64
	Concurrency     uint32
}

MetricItem represents the data of metric log per line.

func MetricItemFromFatString

func MetricItemFromFatString(line string) (*MetricItem, error)

func (*MetricItem) ToFatString

func (m *MetricItem) ToFatString() (string, error)

func (*MetricItem) ToThinString

func (m *MetricItem) ToThinString() (string, error)

type MetricItemRetriever

type MetricItemRetriever interface {
	MetricsOnCondition(predicate TimePredicate) []*MetricItem
}

type ReadStat

type ReadStat interface {
	GetQPS(event MetricEvent) float64
	GetPreviousQPS(event MetricEvent) float64
	GetSum(event MetricEvent) int64

	MinRT() float64
	AvgRT() float64
}

type ResourceType

type ResourceType int32

ResourceType represents classification of the resources

const (
	ResTypeCommon ResourceType = iota
	ResTypeWeb
	ResTypeRPC
	ResTypeAPIGateway
	ResTypeDBSQL
	ResTypeCache
	ResTypeMQ
)

type ResourceWrapper

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

ResourceWrapper represents the invocation

func NewResourceWrapper

func NewResourceWrapper(name string, classification ResourceType, flowType TrafficType) *ResourceWrapper

func (*ResourceWrapper) Classification

func (r *ResourceWrapper) Classification() ResourceType

func (*ResourceWrapper) FlowType

func (r *ResourceWrapper) FlowType() TrafficType

func (*ResourceWrapper) Name

func (r *ResourceWrapper) Name() string

func (*ResourceWrapper) String

func (r *ResourceWrapper) String() string

type RuleCheckSlot

type RuleCheckSlot interface {
	BaseSlot
	// Check function do some validation
	// It can break off the slot pipeline
	// Each TokenResult will return check result
	// The upper logic will control pipeline according to SlotResult.
	Check(ctx *EntryContext) *TokenResult
}

RuleCheckSlot is rule based checking strategy All checking rule must implement this interface.

type SentinelEntry

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

func NewSentinelEntry

func NewSentinelEntry(ctx *EntryContext, rw *ResourceWrapper, sc *SlotChain) *SentinelEntry

func (*SentinelEntry) Context

func (e *SentinelEntry) Context() *EntryContext

func (*SentinelEntry) Exit

func (e *SentinelEntry) Exit(exitOps ...ExitOption)

func (*SentinelEntry) Resource

func (e *SentinelEntry) Resource() *ResourceWrapper

func (*SentinelEntry) SetError

func (e *SentinelEntry) SetError(err error)

func (*SentinelEntry) WhenExit

func (e *SentinelEntry) WhenExit(exitHandler ExitHandler)

type SentinelInput

type SentinelInput struct {
	BatchCount uint32
	Flag       int32
	Args       []interface{}
	// store some values in this context when calling context in slot.
	Attachments map[interface{}]interface{}
}

The input data of sentinel

type SentinelRule

type SentinelRule interface {
	fmt.Stringer

	ResourceName() string
}

type SlotChain

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

SlotChain hold all system slots and customized slot. SlotChain support plug-in slots developed by developer.

func NewSlotChain

func NewSlotChain() *SlotChain

func (*SlotChain) AddRuleCheckSlot

func (sc *SlotChain) AddRuleCheckSlot(s RuleCheckSlot)

AddRuleCheckSlot adds the RuleCheckSlot to the RuleCheckSlot list of the SlotChain. All RuleCheckSlot in the list will be sorted according to RuleCheckSlot.Order() in ascending order. AddRuleCheckSlot is non-thread safe, In concurrency scenario, AddRuleCheckSlot must be guarded by SlotChain.RWMutex#Lock

func (*SlotChain) AddStatPrepareSlot

func (sc *SlotChain) AddStatPrepareSlot(s StatPrepareSlot)

AddStatPrepareSlot adds the StatPrepareSlot slot to the StatPrepareSlot list of the SlotChain. All StatPrepareSlot in the list will be sorted according to StatPrepareSlot.Order() in ascending order. AddStatPrepareSlot is non-thread safe, In concurrency scenario, AddStatPrepareSlot must be guarded by SlotChain.RWMutex#Lock

func (*SlotChain) AddStatSlot

func (sc *SlotChain) AddStatSlot(s StatSlot)

AddStatSlot adds the StatSlot to the StatSlot list of the SlotChain. All StatSlot in the list will be sorted according to StatSlot.Order() in ascending order. AddStatSlot is non-thread safe, In concurrency scenario, AddStatSlot must be guarded by SlotChain.RWMutex#Lock

func (*SlotChain) Entry

func (sc *SlotChain) Entry(ctx *EntryContext) *TokenResult

The entrance of slot chain Return the TokenResult and nil if internal panic.

func (*SlotChain) GetPooledContext

func (sc *SlotChain) GetPooledContext() *EntryContext

Get a EntryContext from EntryContext ctxPool, if ctxPool doesn't have enough EntryContext then new one.

func (*SlotChain) RefurbishContext

func (sc *SlotChain) RefurbishContext(c *EntryContext)

type StatNode

type StatNode interface {
	MetricItemRetriever

	ReadStat
	WriteStat
	ConcurrencyStat

	// GenerateReadStat generates the readonly metric statistic based on resource level global statistic
	// If parameters, sampleCount and intervalInMs, are not suitable for resource level global statistic, return (nil, error)
	GenerateReadStat(sampleCount uint32, intervalInMs uint32) (ReadStat, error)
}

StatNode holds real-time statistics for resources.

type StatPrepareSlot

type StatPrepareSlot interface {
	BaseSlot
	// Prepare function do some initialization
	// Such as: init statistic structure、node and etc
	// The result of preparing would store in EntryContext
	// All StatPrepareSlots execute in sequence
	// Prepare function should not throw panic.
	Prepare(ctx *EntryContext)
}

StatPrepareSlot is responsible for some preparation before statistic For example: init structure and so on

type StatSlot

type StatSlot interface {
	BaseSlot
	// OnEntryPass function will be invoked when StatPrepareSlots and RuleCheckSlots execute pass
	// StatSlots will do some statistic logic, such as QPS、log、etc
	OnEntryPassed(ctx *EntryContext)
	// OnEntryBlocked function will be invoked when StatPrepareSlots and RuleCheckSlots fail to execute
	// It may be inbound flow control or outbound cir
	// StatSlots will do some statistic logic, such as QPS、log、etc
	// blockError introduce the block detail
	OnEntryBlocked(ctx *EntryContext, blockError *BlockError)
	// OnCompleted function will be invoked when chain exits.
	// The semantics of OnCompleted is the entry passed and completed
	// Note: blocked entry will not call this function
	OnCompleted(ctx *EntryContext)
}

StatSlot is responsible for counting all custom biz metrics. StatSlot would not handle any panic, and pass up all panic to slot chain

type TimePredicate

type TimePredicate func(uint64) bool

type TokenResult

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

func NewTokenResult

func NewTokenResult(status TokenResultStatus, blockErrOpts ...BlockErrorOption) *TokenResult

func NewTokenResultBlocked

func NewTokenResultBlocked(blockType BlockType) *TokenResult

func NewTokenResultBlockedWithCause

func NewTokenResultBlockedWithCause(blockType BlockType, blockMsg string, rule SentinelRule, snapshot interface{}) *TokenResult

func NewTokenResultBlockedWithMessage

func NewTokenResultBlockedWithMessage(blockType BlockType, blockMsg string) *TokenResult

func NewTokenResultPass

func NewTokenResultPass() *TokenResult

func NewTokenResultShouldWait

func NewTokenResultShouldWait(waitNs time.Duration) *TokenResult

func (*TokenResult) BlockError

func (r *TokenResult) BlockError() *BlockError

func (*TokenResult) DeepCopyFrom

func (r *TokenResult) DeepCopyFrom(newResult *TokenResult)

func (*TokenResult) IsBlocked

func (r *TokenResult) IsBlocked() bool

func (*TokenResult) IsPass

func (r *TokenResult) IsPass() bool

func (*TokenResult) NanosToWait

func (r *TokenResult) NanosToWait() time.Duration

func (*TokenResult) ResetToBlocked

func (r *TokenResult) ResetToBlocked(blockType BlockType)

func (*TokenResult) ResetToBlockedWith

func (r *TokenResult) ResetToBlockedWith(opts ...BlockErrorOption)

func (*TokenResult) ResetToBlockedWithCause

func (r *TokenResult) ResetToBlockedWithCause(blockType BlockType, blockMsg string, rule SentinelRule, snapshot interface{})

func (*TokenResult) ResetToBlockedWithMessage

func (r *TokenResult) ResetToBlockedWithMessage(blockType BlockType, blockMsg string)

func (*TokenResult) ResetToPass

func (r *TokenResult) ResetToPass()

func (*TokenResult) Status

func (r *TokenResult) Status() TokenResultStatus

func (*TokenResult) String

func (r *TokenResult) String() string

type TokenResultStatus

type TokenResultStatus uint8
const (
	ResultStatusPass TokenResultStatus = iota
	ResultStatusBlocked
	ResultStatusShouldWait
)

func (TokenResultStatus) String

func (s TokenResultStatus) String() string

type TrafficType

type TrafficType int32

TrafficType describes the traffic type: Inbound or Outbound

const (
	// Inbound represents the inbound traffic (e.g. provider)
	Inbound TrafficType = iota
	// Outbound represents the outbound traffic (e.g. consumer)
	Outbound
)

func (TrafficType) String

func (t TrafficType) String() string

type WriteStat

type WriteStat interface {
	AddCount(event MetricEvent, count int64)
}

Jump to

Keyboard shortcuts

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