日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

阿里 双11 同款,流量防卫兵 Sentinel go 源码解读

發布時間:2025/3/20 编程问答 16 豆豆
生活随笔 收集整理的這篇文章主要介紹了 阿里 双11 同款,流量防卫兵 Sentinel go 源码解读 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

作者 | 于雨? apache/dubbo-go 項目負責人

本文作者系 apache/dubbo-go 項目負責人,目前在 dubbogo 項目中已內置可用 sentinel-go,如果想單獨使用可參考 在 dubbo-go 中使用 sentinel 一文,若有其他疑問可進 dubbogo社區【釘釘群 23331795】進行溝通。

導讀:本文主要分析阿里巴巴集團開源的流量控制中間件 Sentinel,其原生支持了 Java/Go/C++ 等多種語言,本文僅僅分析其 Go 語言實現。下文如無特殊說明,sentinel 指代 Sentinel-Go。

1 基本概念 Resource ?和 Rule

1.1 Resource

// ResourceType represents classification of the resourcestype ResourceType int32const (ResTypeCommon ResourceType = iotaResTypeWebResTypeRPC)// TrafficType describes the traffic type: Inbound or Outboundtype TrafficType int32const (// Inbound represents the inbound traffic (e.g. provider)Inbound TrafficType = iota// Outbound represents the outbound traffic (e.g. consumer)Outbound)// ResourceWrapper represents the invocationtype ResourceWrapper struct {// global unique resource namename string// resource classificationclassification ResourceType// Inbound or OutboundflowType TrafficType}

Resource(ResourceWrapper) 存儲了應用場景 ResourceType,以及目標流控的方向 FlowType(TrafficType)。

1.2 Entry

// EntryOptions represents the options of a Sentinel resource entry.type EntryOptions struct {resourceType base.ResourceTypeentryType base.TrafficTypeacquireCount uint32slotChain *base.SlotChain}type EntryContext struct {entry *SentinelEntry// Use to calculate RTstartTime uint64Resource *ResourceWrapperStatNode StatNodeInput *SentinelInput// the result of rule slots checkRuleCheckResult *TokenResult}type SentinelEntry struct {res *ResourceWrapper// one entry bounds with one contextctx *EntryContextsc *SlotChain}

Entry 實體 SentinelEntry 關聯了 Resource(ResourceWrapper) 以及其流控規則集合 SlotChain。每個 Entry 實體有一個上下文環境 EntryContext,存儲每個 Rule 檢測時用到的一些流控參數和流控判定結果。

值得注意的是,SentinelEntry.sc 值來自于 EntryOptions.slotChain,EntryOptions.slotChain 存儲了全局 SlotChain 對象 api/slot_chain.go:globalSlotChain。

至于何為 SlotChain,就是 sentinel 提供的所有的流控組件的集合,可以簡單地認為每個流控組件就是一個 Slot,其詳細分析見[3.5 SlotChain]。

sentinel 一些變量和函數命名的可讀性較差,如 EntryOptions.acquireCount 實在無法讓人望文生義,看過函數 core/api.go:WithAcquireCount() 的注釋才明白:EntryOptions.acquireCount 是批量動作執行次數。如有的一次 RPC 請求中調用了服務端的一個服務接口,則取值 1【也是 EntryOptions.acquireCount 的默認取值】,如果調用了服務端的 3 個服務接口,則取值 3。所以建議改名為 EntryOptions.batchCount 比較好,考慮到最小改動原則,可以在保留 core/api.go:WithAcquireCount() 的同時增加一個同樣功能的 core/api.go:WithBatchCount() 接口。相關改進已經提交到 ?pr 263。

1.3 Rule

type TokenCalculateStrategy int32const (Direct TokenCalculateStrategy = iotaWarmUp)type ControlBehavior int32const (Reject ControlBehavior = iotaThrottling)// Rule describes the strategy of flow control, the flow control strategy is based on QPS statistic metrictype Rule struct {// Resource represents the resource name.Resource string `json:"resource"`ControlBehavior ControlBehavior `json:"controlBehavior"`// Threshold means the threshold during StatIntervalInMs// If StatIntervalInMs is 1000(1 second), Threshold means QPSThreshold float64 `json:"threshold"`MaxQueueingTimeMs uint32 `json:"maxQueueingTimeMs"`// StatIntervalInMs indicates the statistic interval and it's the optional setting for flow Rule.// If user doesn't set StatIntervalInMs, that means using default metric statistic of resource.// If the StatIntervalInMs user specifies can not reuse the global statistic of resource,// sentinel will generate independent statistic structure for this rule.StatIntervalInMs uint32 `json:"statIntervalInMs"`}

Rule 記錄了某 Resource 的限流判定閾值 Threshold、限流時間窗口計時長度 StatIntervalInMs 以及 觸發限流后的判罰動作 ControlBehavior。

上面核心是 Rule 的接口 RuleCheckSlot,至于 StatSlot 則用于統計 sentinel 自身的運行 metrics。

1.4 Flow

當前章節主要分析流控中的限流(core/flow),根據流控的處理流程梳理 sentinel 整體骨架。

1.4.1 TrafficShapingController

所謂 TrafficShapingController,顧名思義,就是 流量塑形控制器,是流控的具體實施者。

// core/flow/traffic_shaping.go// TrafficShapingCalculator calculates the actual traffic shaping threshold// based on the threshold of rule and the traffic shaping strategy.type TrafficShapingCalculator interface {CalculateAllowedTokens(acquireCount uint32, flag int32) float64}type DirectTrafficShapingCalculator struct {threshold float64}func (d *DirectTrafficShapingCalculator) CalculateAllowedTokens(uint32, int32) float64 {return d.threshold}

TrafficShapingCalculator 接口用于計算限流的上限,如果不使用 warm-up 功能,可以不去深究其實現,其實體之一 DirectTrafficShapingCalculator 返回 Rule.Threshold【用戶設定的限流上限】。

// TrafficShapingChecker performs checking according to current metrics and the traffic// shaping strategy, then yield the token result.type TrafficShapingChecker interface {DoCheck(resStat base.StatNode, acquireCount uint32, threshold float64) *base.TokenResult}type RejectTrafficShapingChecker struct {rule *Rule}func (d *RejectTrafficShapingChecker) DoCheck(resStat base.StatNode, acquireCount uint32, threshold float64) *base.TokenResult {metricReadonlyStat := d.BoundOwner().boundStat.readOnlyMetricif metricReadonlyStat == nil {return nil}curCount := float64(metricReadonlyStat.GetSum(base.MetricEventPass))if curCount+float64(acquireCount) > threshold {return base.NewTokenResultBlockedWithCause(base.BlockTypeFlow, "", d.rule, curCount)}return nil}

RejectTrafficShapingChecker 依據 Rule.Threshold 判定 Resource 在當前時間窗口是否超限,其限流結果 TokenResultStatus 只可能是 Pass 或者 Blocked。

sentinel flow 還有一個勻速限流 ThrottlingChecker,它的目的是讓請求勻速被執行,把一個時間窗口【譬如 1s】根據 threshold 再細分為更細的微時間窗口,在每個微時間窗口最多執行一次請求,其限流結果 TokenResultStatus 只可能是 Pass 或者 Blocked 或者 Wait,其相關意義分別為:

  • Pass:在微時間窗口內無超限,請求通過;
  • Wait:在微時間窗口內超限,被滯后若干時間窗口執行,在這段時間內請求需要等待;
  • Blocked:在微時間窗口內超限,且等待時間超過用戶設定的最大愿意等待時間長度【Rule.MaxQueueingTimeMs】,請求被拒絕。
type TrafficShapingController struct {flowCalculator TrafficShapingCalculatorflowChecker TrafficShapingCheckerrule *Rule// boundStat is the statistic of current TrafficShapingControllerboundStat standaloneStatistic}func (t *TrafficShapingController) PerformChecking(acquireCount uint32, flag int32) *base.TokenResult {allowedTokens := t.flowCalculator.CalculateAllowedTokens(acquireCount, flag)return t.flowChecker.DoCheck(resStat, acquireCount, allowedTokens)}

在 Direct + Reject 限流的場景下,這三個接口其實并無多大意義,其核心函數 TrafficShapingController.PerformChecking() 的主要流程是:

  • 1 ?從 TrafficShapingController.boundStat 中獲取當前 Resource 的 metrics 值【curCount】;
  • 2 如果 curCount + batchNum(acquireCount) > Rule.Threshold,則 pass,否則就 reject。

在限流場景下, TrafficShapingController 四個成員的意義如下:

  • flowCalculator 計算限流上限;
  • flowChecker 執行限流 Check 動作;
  • rule 存儲限流規則;
  • boundStat 存儲限流的 Check 結果和時間窗口參數,作為下次限流 Check 動作判定的依據。

1.4.2 TrafficControllerMap

在執行限流判定時,需要根據 Resource 名稱獲取其對應的 TrafficShapingController。

// TrafficControllerMap represents the map storage for TrafficShapingController.type TrafficControllerMap map[string][]*TrafficShapingController// core/flow/rule_manager.gotcMap = make(TrafficControllerMap)

package 級別全局私有變量 tcMap 存儲了所有的 Rule,其 key 為 Resource 名稱,value 則是與 Resource 對應的 TrafficShapingController。

用戶級別接口函數 core/flow/rule_manager.go:LoadRules() 會根據用戶定義的 Rule 構造其對應的 TrafficShapingController 存入 tcMap,這個接口調用函數 generateStatFor(*Rule) 構造 TrafficShapingController.boundStat。

限流場景下,函數 generateStatFor(*Rule) 的核心代碼如下:

func generateStatFor(rule *Rule) (*standaloneStatistic, error) {resNode = stat.GetOrCreateResourceNode(rule.Resource, base.ResTypeCommon)// default case, use the resource's default statisticreadStat := resNode.DefaultMetric()retStat.reuseResourceStat = trueretStat.readOnlyMetric = readStatretStat.writeOnlyMetric = nilreturn &retStat, nil}

2 Metrics

Resource 的指標 Metrics 是進行 Rule 判定的基礎。

2.1 原子時間輪 AtomicBucketWrapArray

Sentinel 庫功能豐富,但無論是限流還是熔斷,其存儲基礎都是滑動時間窗口。其間包含了眾多優化:如無鎖定長時間輪。

滑動窗口實現有很多種,時間輪算法是其中一種比較簡單的實現,在時間輪算法之上可以實現多種限流方法。時間輪整體框圖如下:

1 BucketWrap

時間輪的最基本單元是一個桶【時間窗口】。

// BucketWrap represent a slot to record metrics// In order to reduce the usage of memory, BucketWrap don't hold length of BucketWrap// The length of BucketWrap could be seen in LeapArray.// The scope of time is [startTime, startTime+bucketLength)// The size of BucketWrap is 24(8+16) bytestype BucketWrap struct {// The start timestamp of this statistic bucket wrapper.BucketStart uint64// The actual data structure to record the metrics (e.g. MetricBucket).Value atomic.Value}

補充:這里之所以用指針,是因為以 BucketWrap 為基礎的 AtomicBucketWrapArray 會被多個 sentinel 流控組件使用,每個組件的流控參數不一,例如:

  • 1 core/circuitbreaker/circuit_breaker.go:slowRtCircuitBreaker 使用的 slowRequestLeapArray 的底層參數 slowRequestCounter
// core/circuitbreaker/circuit_breaker.gotype slowRequestCounter struct {slowCount uint64totalCount uint64}
  • 2 core/circuitbreaker/circuit_breaker.go:errorRatioCircuitBreaker 使用的 errorCounterLeapArray 的底層參數 errorCounter
// core/circuitbreaker/circuit_breaker.gotype errorCounter struct {errorCount uint64totalCount uint64}

1.1 MetricBucket

BucketWrap 可以認作是一種 時間桶模板,具體的桶的實體是 MetricsBucket,其定義如下:

// MetricBucket represents the entity to record metrics per minimum time unit (i.e. the bucket time span).// Note that all operations of the MetricBucket are required to be thread-safe.type MetricBucket struct {// Value of statisticcounter [base.MetricEventTotal]int64minRt int64}

MetricBucket 存儲了五種類型的 metric:

// There are five events to record// pass + block == Totalconst (// sentinel rules check passMetricEventPass MetricEvent = iota// sentinel rules check blockMetricEventBlockMetricEventComplete// Biz error, used for circuit breakerMetricEventError// request execute rt, unit is millisecondMetricEventRt// hack for the number of eventMetricEventTotal)

2 AtomicBucketWrapArray

每個桶只記錄了其起始時間和 metric 值,至于每個桶的時間窗口長度這種公共值則統一記錄在 AtomicBucketWrapArray 內,AtomicBucketWrapArray 定義如下:

// atomic BucketWrap array to resolve race condition// AtomicBucketWrapArray can not append or delete element after initializingtype AtomicBucketWrapArray struct {// The base address for real data arraybase unsafe.Pointer// The length of slice(array), it can not be modified.length intdata []*BucketWrap}

AtomicBucketWrapArray.base 的值是 AtomicBucketWrapArray.data slice 的 data 區域的首指針。因為 AtomicBucketWrapArray.data 是一個固定長度的 slice,所以 AtomicBucketWrapArray.base 直接存儲數據內存區域的首地址,以加速訪問速度。

其次,AtomicBucketWrapArray.data 中存儲的是 BucketWrap 的指針,而不是 BucketWrap。

NewAtomicBucketWrapArrayWithTime() 函數會預熱一下,把所有的時間桶都生成出來。

2.2 時間輪

1 leapArray

// Give a diagram to illustrate// Suppose current time is 888, bucketLengthInMs is 200ms,// intervalInMs is 1000ms, LeapArray will build the below windows// B0 B1 B2 B3 B4// |_______|_______|_______|_______|_______|// 1000 1200 1400 1600 800 (1000)// ^// time=888type LeapArray struct {bucketLengthInMs uint32sampleCount uint32intervalInMs uint32array *AtomicBucketWrapArray// update lockupdateLock mutex}

LeapArray 各個成員解析:

  • bucketLengthInMs 是漏桶長度,以毫秒為單位;
  • sampleCount 則是時間漏桶個數;
  • intervalInMs 是時間窗口長度,以毫秒為單位。

其注釋中的 ASCII 圖很好地解釋了每個字段的含義。

LeapArray 核心函數是 LeapArray.currentBucketOfTime(),其作用是根據某個時間點獲取其做對應的時間桶 BucketWrap,代碼如下:

func (la *LeapArray) currentBucketOfTime(now uint64, bg BucketGenerator) (*BucketWrap, error) {if now <= 0 {return nil, errors.New("Current time is less than 0.")}idx := la.calculateTimeIdx(now)bucketStart := calculateStartTime(now, la.bucketLengthInMs)for { //spin to get the current BucketWrapold := la.array.get(idx)if old == nil {// because la.array.data had initiated when new la.array// theoretically, here is not reachablenewWrap := &BucketWrap{BucketStart: bucketStart,Value: atomic.Value{},}newWrap.Value.Store(bg.NewEmptyBucket())if la.array.compareAndSet(idx, nil, newWrap) {return newWrap, nil} else {runtime.Gosched()}} else if bucketStart == atomic.LoadUint64(&old.BucketStart) {return old, nil} else if bucketStart > atomic.LoadUint64(&old.BucketStart) {// current time has been next cycle of LeapArray and LeapArray dont't count in last cycle.// reset BucketWrapif la.updateLock.TryLock() {old = bg.ResetBucketTo(old, bucketStart)la.updateLock.Unlock()return old, nil} else {runtime.Gosched()}} else if bucketStart < atomic.LoadUint64(&old.BucketStart) {// TODO: reserve for some special case (e.g. when occupying "future" buckets).return nil, errors.New(fmt.Sprintf("Provided time timeMillis=%d is already behind old.BucketStart=%d.", bucketStart, old.BucketStart))}}}

其 for-loop 核心邏輯是:

  • 1 獲取時間點對應的時間桶 old;
  • 2 如果 old 為空,則新建一個時間桶,以原子操作的方式嘗試存入時間窗口的時間輪中,存入失敗則重新嘗試;
  • 3 如果 old 就是當前時間點所在的時間桶,則返回;
  • 4 如果 old 的時間起點小于當前時間,則通過樂觀鎖嘗試 reset 桶的起始時間等參數值,加鎖更新成功則返回;
  • 5 如果 old 的時間起點大于當前時間,則系統發生了時間扭曲,返回錯誤。

2 BucketLeapArray

leapArray 實現了滑動時間窗口的所有主體,其對外使用接口則是 BucketLeapArray:

// The implementation of sliding window based on LeapArray (as the sliding window infrastructure)// and MetricBucket (as the data type). The MetricBucket is used to record statistic// metrics per minimum time unit (i.e. the bucket time span).type BucketLeapArray struct {data LeapArraydataType string}

從這個 struct 的注釋可見,其時間窗口 BucketWrap 的實體是 MetricBucket。

2.3 Metric 數據讀寫

SlidingWindowMetric

// SlidingWindowMetric represents the sliding window metric wrapper.// It does not store any data and is the wrapper of BucketLeapArray to adapt to different internal bucket// SlidingWindowMetric is used for SentinelRules and BucketLeapArray is used for monitor// BucketLeapArray is per resource, and SlidingWindowMetric support only read operation.type SlidingWindowMetric struct {bucketLengthInMs uint32sampleCount uint32intervalInMs uint32real *BucketLeapArray}

SlidingWindowMetric 是對 BucketLeapArray 的一個封裝,只提供了只讀接口。

ResourceNode

type BaseStatNode struct {sampleCount uint32intervalMs uint32goroutineNum int32arr *sbase.BucketLeapArraymetric *sbase.SlidingWindowMetric}type ResourceNode struct {BaseStatNoderesourceName stringresourceType base.ResourceType}// core/stat/node_storage.gotype ResourceNodeMap map[string]*ResourceNodevar (inboundNode = NewResourceNode(base.TotalInBoundResourceName, base.ResTypeCommon)resNodeMap = make(ResourceNodeMap)rnsMux = new(sync.RWMutex))

BaseStatNode 對外提供了讀寫接口,其數據寫入 BaseStatNode.arr,讀取接口則依賴 BaseStatNode.metric。BaseStatNode.arr 是在 NewBaseStatNode() 中創建的,指針 SlidingWindowMetric.real 也指向它。

ResourceNode 則顧名思義,其代表了某資源和它的 Metrics 存儲 ?ResourceNode.BaseStatNode。

全局變量 resNodeMap 存儲了所有資源的 Metrics 指標數據。

3 限流流程

本節只分析 Sentinel 庫提供的最基礎的流量整形功能 – 限流,限流算法多種多樣,可以使用其內置的算法,用戶自己也可以進行擴展。

限流過程有三步步驟:

  • 1 針對特定 Resource 構造其 EntryContext,存儲其 Metrics、限流開始時間等,Sentinel 稱之為 StatPrepareSlot;
  • 2 依據 Resource 的限流算法判定其是否應該進行限流,并給出限流判定結果,Sentinel 稱之為 RuleCheckSlot;
    • 補充:這個限流算法是一系列判斷方法的合集(SlotChain);
  • 3 判定之后,除了用戶自身根據判定結果執行相應的 action,Sentinel 也需要根據判定結果執行自身的 Action,以及把整個判定流程所使用的的時間 RT 等指標存儲下來,Sentinel 稱之為 StatSlot。

整體流程如下圖所示:

3.1 Slot

針對 Check 三個步驟,有三個對應的 Slot 分別定義如下:

// StatPrepareSlot is responsible for some preparation before statistic// For example: init structure and so ontype StatPrepareSlot interface {// 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)}// RuleCheckSlot is rule based checking strategy// All checking rule must implement this interface.type RuleCheckSlot interface {// 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}// StatSlot is responsible for counting all custom biz metrics.// StatSlot would not handle any panic, and pass up all panic to slot chaintype StatSlot interface {// OnEntryPass function will be invoked when StatPrepareSlots and RuleCheckSlots execute pass// StatSlots will do some statistic logic, such as QPS、log、etcOnEntryPassed(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 detailOnEntryBlocked(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 functionOnCompleted(ctx *EntryContext)}

拋卻 Prepare 和 Stat,可以簡單的認為:所謂的 slot,就是 sentinel 提供的某個流控組件。

值得注意的是,根據注釋 StatSlot.OnCompleted 只有在 RuleCheckSlot.Check 通過才會執行,用于計算從請求開始到結束所使用的 RT 等 Metrics。

3.2 Prepare

// core/base/slot_chain.go// StatPrepareSlot is responsible for some preparation before statistic// For example: init structure and so ontype StatPrepareSlot interface {// 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)}// core/stat/stat_prepare_slot.gotype ResourceNodePrepareSlot struct {}func (s *ResourceNodePrepareSlot) Prepare(ctx *base.EntryContext) {node := GetOrCreateResourceNode(ctx.Resource.Name(), ctx.Resource.Classification())// Set the resource node to the context.ctx.StatNode = node}

如前面解釋,Prepare 主要是構造存儲 Resource Metrics 所使用的 ResourceNode。所有 Resource 的 StatNode 都會存儲在 package 級別的全局變量 core/stat/node_storage.go:resNodeMap [type: map[string]*ResourceNode] 中,函數 GetOrCreateResourceNode 用于根據 Resource Name 從 resNodeMap 中獲取其對應的 StatNode,如果不存在則創建一個 StatNode 并存入 resNodeMap。

3.3 Check

RuleCheckSlot.Check() 執行流程:

  • 1 根據 Resource 名稱獲取其所有的 Rule 集合;
  • 2 遍歷 Rule 集合,對 Resource 依次執行 Check,任何一個 Rule 判定 Resource 需要進行限流【Blocked】則返回,否則放行。
type Slot struct {}func (s *Slot) Check(ctx *base.EntryContext) *base.TokenResult {res := ctx.Resource.Name()tcs := getTrafficControllerListFor(res)result := ctx.RuleCheckResult// Check rules in orderfor _, tc := range tcs {r := canPassCheck(tc, ctx.StatNode, ctx.Input.AcquireCount)if r == nil {// nil means passcontinue}if r.Status() == base.ResultStatusBlocked {return r}if r.Status() == base.ResultStatusShouldWait {if waitMs := r.WaitMs(); waitMs > 0 {// Handle waiting action.time.Sleep(time.Duration(waitMs) * time.Millisecond)}continue}}return result}func canPassCheck(tc *TrafficShapingController, node base.StatNode, acquireCount uint32) *base.TokenResult {return canPassCheckWithFlag(tc, node, acquireCount, 0)}func canPassCheckWithFlag(tc *TrafficShapingController, node base.StatNode, acquireCount uint32, flag int32) *base.TokenResult {return checkInLocal(tc, node, acquireCount, flag)}func checkInLocal(tc *TrafficShapingController, resStat base.StatNode, acquireCount uint32, flag int32) *base.TokenResult {return tc.PerformChecking(resStat, acquireCount, flag)}

3.4 Exit

sentinel 對 Resource 進行 Check 后,其后續邏輯執行順序是:

  • 1 如果 RuleCheckSlot.Check() 判定 pass 通過則執行 StatSlot.OnEntryPassed(),否則 RuleCheckSlot.Check() 判定 reject 則執行 StatSlot.OnEntryBlocked();
  • 2 如果 RuleCheckSlot.Check() 判定 pass 通過,則執行本次 Action;
  • 3 如果 RuleCheckSlot.Check() 判定 pass 通過,則執行 SentinelEntry.Exit() --> SlotChain.ext() --> StatSlot.OnCompleted() 。

第三步驟的調用鏈路如下:

StatSlot.OnCompleted()

// core/flow/standalone_stat_slot.gotype StandaloneStatSlot struct {}func (s StandaloneStatSlot) OnEntryPassed(ctx *base.EntryContext) {res := ctx.Resource.Name()for _, tc := range getTrafficControllerListFor(res) {if !tc.boundStat.reuseResourceStat {if tc.boundStat.writeOnlyMetric != nil {tc.boundStat.writeOnlyMetric.AddCount(base.MetricEventPass, int64(ctx.Input.AcquireCount))}}}}func (s StandaloneStatSlot) OnEntryBlocked(ctx *base.EntryContext, blockError *base.BlockError) {// Do nothing}func (s StandaloneStatSlot) OnCompleted(ctx *base.EntryContext) {// Do nothing}

SlotChain.exit()

// core/base/slot_chain.gotype SlotChain struct {}func (sc *SlotChain) exit(ctx *EntryContext) {// The OnCompleted is called only when entry passedif ctx.IsBlocked() {return}for _, s := range sc.stats {s.OnCompleted(ctx)}}

SentinelEntry.Exit()

// core/base/entry.gotype SentinelEntry struct {sc *SlotChainexitCtl sync.Once}func (e *SentinelEntry) Exit() {e.exitCtl.Do(func() {if e.sc != nil {e.sc.exit(ctx)}})}

從上面執行可見,StatSlot.OnCompleted() 是在 Action 【如一次 RPC 的請求-響應 Invokation】完成之后調用的。如果有的組件需要計算一次 Action 的時間耗費 ?RT,就在其對應的 StatSlot.OnCompleted() 中依據 EntryContext.startTime 完成時間耗費計算。

3.5 SlotChain

Sentinel 本質是一個流控包,不僅提供了限流功能,還提供了眾多其他諸如自適應流量保護、熔斷降級、冷啟動、全局流量 Metrics 結果等功能流控組件,Sentinel-Go 包定義了一個 SlotChain 實體存儲其所有的流控組件。

// core/base/slot_chain.go// SlotChain hold all system slots and customized slot.// SlotChain support plug-in slots developed by developer.type SlotChain struct {statPres []StatPrepareSlotruleChecks []RuleCheckSlotstats []StatSlot}// The entrance of slot chain// Return the TokenResult and nil if internal panic.func (sc *SlotChain) Entry(ctx *EntryContext) *TokenResult {// execute prepare slotsps := sc.statPresif len(sps) > 0 {for _, s := range sps {s.Prepare(ctx)}}// execute rule based checking slotrcs := sc.ruleChecksvar ruleCheckRet *TokenResultif len(rcs) > 0 {for _, s := range rcs {sr := s.Check(ctx)if sr == nil {// nil equals to check passcontinue}// check slot resultif sr.IsBlocked() {ruleCheckRet = srbreak}}}if ruleCheckRet == nil {ctx.RuleCheckResult.ResetToPass()} else {ctx.RuleCheckResult = ruleCheckRet}// execute statistic slotss := sc.statsruleCheckRet = ctx.RuleCheckResultif len(ss) > 0 {for _, s := range ss {// indicate the result of rule based checking slot.if !ruleCheckRet.IsBlocked() {s.OnEntryPassed(ctx)} else {// The block error should not be nil.s.OnEntryBlocked(ctx, ruleCheckRet.blockErr)}}}return ruleCheckRet}func (sc *SlotChain) exit(ctx *EntryContext) {if ctx == nil || ctx.Entry() == nil {logging.Error(errors.New("nil EntryContext or SentinelEntry"), "")return}// The OnCompleted is called only when entry passedif ctx.IsBlocked() {return}for _, s := range sc.stats {s.OnCompleted(ctx)}// relieve the context here}

建議:Sentinel 包針對某個 Resource 無法確知其使用了那個組件,在運行時會針對某個 Resource 的 EntryContext 依次執行所有的組件的 Rule。Sentinel-golang 為何不給用戶相關用戶提供一個接口讓其設置使用的流控組件集合,以減少下面函數 SlotChain.Entry() 中執行 RuleCheckSlot.Check() 執行次數?相關改進已經提交到 pr 264【補充,代碼已合并,據負責人壓測后回復 sentinel-go 效率整體提升 15%】。

globalSlotChain

Sentinel-Go 定義了一個 SlotChain 的 package 級別的全局私有變量 globalSlotChain 用于存儲其所有的流控組件對象。相關代碼示例如下。因本文只關注限流組件,所以下面只給出了限流組件的注冊代碼。

// api/slot_chain.gofunc BuildDefaultSlotChain() *base.SlotChain {sc := base.NewSlotChain()sc.AddStatPrepareSlotLast(&stat.ResourceNodePrepareSlot{})sc.AddRuleCheckSlotLast(&flow.Slot{})sc.AddStatSlotLast(&flow.StandaloneStatSlot{})return sc}var globalSlotChain = BuildDefaultSlotChain()

Entry

在 Sentinel-Go 對外的最重要的入口函數 api/api.go:Entry() 中,globalSlotChain 會作為 EntryOptions 的 SlotChain 參數被使用。

// api/api.go// Entry is the basic API of Sentinel.func Entry(resource string, opts ...EntryOption) (*base.SentinelEntry, *base.BlockError) {options := entryOptsPool.Get().(*EntryOptions)options.slotChain = globalSlotChainreturn entry(resource, options)}

Sentinel 的演進離不開社區的貢獻。Sentinel Go 1.0 GA 版本即將在近期發布,帶來更多云原生相關的特性。我們非常歡迎感興趣的開發者參與貢獻,一起來主導未來版本的演進。我們鼓勵任何形式的貢獻,包括但不限于:

? bug fix
? new features/improvements
? dashboard
? document/website
? test cases

開發者可以在 GitHub 上面的 good first issue 列表上挑選感興趣的 issue 來參與討論和貢獻。我們會重點關注積極參與貢獻的開發者,核心貢獻者會提名為 Committer,一起主導社區的發展。我們也歡迎大家有任何問題和建議,都可以通過 GitHub issue、Gitter 或釘釘群(群號:30150716)等渠道進行交流。Now start hacking!

? Sentinel Go repo: https://github.com/alibaba/sentinel-golang
? 企業用戶歡迎進行登記:https://github.com/alibaba/Sentinel/issues/18

作者簡介

于雨(github @AlexStocks),apache/dubbo-go 項目負責人,一個有十多年服務端基礎架構研發一線工作經驗的程序員,目前在螞蟻金服可信原生部從事容器編排和 service mesh 工作。熱愛開源,從 2015 年給 Redis 貢獻代碼開始,陸續改進過 Muduo/Pika/Dubbo/Dubbo-go 等知名項目。

“阿里巴巴云原生關注微服務、Serverless、容器、Service Mesh 等技術領域、聚焦云原生流行技術趨勢、云原生大規模的落地實踐,做最懂云原生開發者的公眾號。”

總結

以上是生活随笔為你收集整理的阿里 双11 同款,流量防卫兵 Sentinel go 源码解读的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。