Alibaba Sentinel 骨架源碼分析

Sentinel 的核心骨架,將不同的 Slot 按照順序串在一起(責(zé)任鏈模式),從而將不同的功能(限流、降級、系統(tǒng)保護(hù))組合在一起。slot chain 其實(shí)可以分為兩部分:統(tǒng)計數(shù)據(jù)構(gòu)建部分(statistic)和判斷部分(rule checking)。核心結(jié)構(gòu):

image.png

業(yè)務(wù)埋點(diǎn)示例

// 資源的唯一標(biāo)識
String resourceName = "testSentinel";
Entry entry = null;
String retVal;
try {
    entry = SphU.entry(resourceName, EntryType.IN);
    // TODO 業(yè)務(wù)邏輯 
    retVal = "passed";
} catch (BlockException e) {
    // TODO 降級邏輯
    retVal = "blocked";
} catch (Exception e) {
    // 異常數(shù)統(tǒng)計埋點(diǎn)
    Tracer.trace(e);
    throw new RuntimeException(e);
} finally {
    if (entry != null) {
        entry.exit();
    }
}

這段代碼是Sentinel業(yè)務(wù)埋點(diǎn)示例,通過示例我們可以看出Sentinel對資源的控制入口是SphU.entry(resourceName, EntryType.IN);,源碼如下:

public static Entry entry(String name, EntryType type) throws BlockException {
    return Env.sph.entry(name, type, 1, OBJECTS0);
}

這里第一個參數(shù)是受保護(hù)資源的唯一名稱;第二個參數(shù)表示流量類型:

  • EntryType.IN:是指進(jìn)入我們系統(tǒng)的入口流量,比如 http 請求或者是其他的 rpc 之類的請求,設(shè)置為IN主要是為了保護(hù)自己系統(tǒng)。
  • EntryType.OUT:是指我們系統(tǒng)調(diào)用其他第三方服務(wù)的出口流量,設(shè)置為OUT是為了保護(hù)第三方系統(tǒng)。

這段代碼沒什么邏輯,只是轉(zhuǎn)發(fā)了下,跟進(jìn)源碼可以發(fā)現(xiàn)最終邏輯實(shí)在CtSph#entryWithPriority(ResourceWrapper, int, boolean, Object...)方法中。

Sentinel 骨架代碼

Sentinel的核心是資源,這里的資源可以是任何東西,服務(wù),服務(wù)里的方法,甚至是一段代碼。而SphU.entry(resourceName);這段代碼的主要作用是 :

  1. 定義一個Sentinel資源
  2. 檢驗(yàn)資源所對應(yīng)的規(guī)則是否生效

核心代碼如下:

private Entry entryWithPriority(ResourceWrapper resourceWrapper, int count, boolean prioritized, Object... args)
    throws BlockException {
    // 獲取當(dāng)前線程上下文,Context是通過ThreadLocal維護(hù),每一個Context都會有一個EntranceNode實(shí)例,它是dashboard【簇點(diǎn)鏈路】中的根節(jié)點(diǎn),主要是用來區(qū)分調(diào)用鏈路的
    Context context = ContextUtil.getContext();
    if (context instanceof NullContext) {
        // 如果是 NullContext,表示 Context 個數(shù)超過了閾值,這個時候 Sentinel 不會應(yīng)用規(guī)則,即不會觸發(fā)限流降級等規(guī)則,也不會觸發(fā)QPS等數(shù)據(jù)統(tǒng)計。
        // 閾值大小 =Constants.MAX_CONTEXT_NAME_SIZE = 2000,具體可以查看 ContextUtil#trueEnter。
        return new CtEntry(resourceWrapper, null, context);
    }

    if (context == null) {
        // 如果沒有設(shè)置上下文,即使用默認(rèn)上下文,默認(rèn)上下文的名稱是  sentinel_default_context
        context = InternalContextUtil.internalEnter(Constants.CONTEXT_DEFAULT_NAME);
    }

    if (!Constants.ON) {
        // Sentinel 的全局控制開關(guān),一旦關(guān)閉則不進(jìn)行任何檢查
        return new CtEntry(resourceWrapper, null, context);
    }

    // 通過Sentinel的官方文檔我們可以知道,Sentinel的核心功能是基于一系列的功能插槽來實(shí)現(xiàn)的,而組織這些功能插槽使用的是責(zé)任鏈模式。
    // 這里是通過資源(每個資源是唯一的),獲取第一個功能插,即該資源對應(yīng)的規(guī)則入口。
    ProcessorSlot<Object> chain = lookProcessChain(resourceWrapper);

    /*
     * Means amount of resources (slot chain) exceeds {@link Constants.MAX_SLOT_CHAIN_SIZE},
     * so no rule checking will be done.
     */
    // 如果一個服務(wù)中,資源數(shù)量操過閾值(最大的插槽鏈),則返回null,即不會再應(yīng)用規(guī)則,直接返回。
    // 閾值大小 = Constants.MAX_SLOT_CHAIN_SIZE = 6000
    if (chain == null) {
        return new CtEntry(resourceWrapper, null, context);
    }

    // 構(gòu)建Sentinel調(diào)用鏈入口
    Entry e = new CtEntry(resourceWrapper, chain, context);
    try {
        // 開始執(zhí)行插槽鏈,如果某個插槽匹配上了某個規(guī)則,如限流規(guī)則,就會拋出BlockException異常,這時表示請求被拒絕了。
        // 業(yè)務(wù)層面會去捕獲這個異常,然后做熔斷,降級操作。
        chain.entry(context, resourceWrapper, null, count, prioritized, args);
    } catch (BlockException e1) {
        e.exit(count, args);
        throw e1;
    } catch (Throwable e1) {
        // Sentinel內(nèi)部異常
        RecordLog.info("Sentinel unexpected exception", e1);
    }
    return e;
}

核心邏輯如下:

  1. 通過當(dāng)前線程的上下文,獲取到當(dāng)前線程的【簇點(diǎn)鏈路】入口。
  2. 判斷全局開關(guān)是否關(guān)閉。
  3. 通過唯一的資源標(biāo)識獲取到對應(yīng)的功能插槽鏈(ProcessorSlot)的第一個插槽。
  4. 構(gòu)建Sentinel調(diào)用鏈入口,并執(zhí)行調(diào)用鏈
  5. 如果拋出BlockException表示觸發(fā)了資源限制規(guī)則,需要進(jìn)行熔斷降級。

這里有兩個需要注意的地方:

  1. 【簇點(diǎn)鏈路】入口Context的數(shù)量是有限制的,最大2000個,通常情況下,我們都不需要顯示設(shè)置 context,使用默認(rèn)的就好了,這樣Context數(shù)量限制基本上不會觸發(fā)。
  2. SphU.entry(resourceName, EntryType.IN),這里的資源的唯一標(biāo)識resourceName也是有限制的,最大是6000。當(dāng)Sentinel與 Servlet 的整合后,CommonFilter會將所有的對外接口定義成Sentinel的資源,資源名稱就是接口地址,所以要控制好服務(wù)接口數(shù)量。
image.png

ContextUtil#enter

ContextUtil#enter(String name, String origin)的主要作用就是創(chuàng)建當(dāng)前線程的上下文Context,每個上下文會對應(yīng)一個EntranceNode(入口節(jié)點(diǎn))實(shí)例,通常情況下我們不需要顯示調(diào)用該方法。

  • name:上下文的唯一標(biāo)識,也是入口節(jié)點(diǎn)的資源名稱。
  • orgin:表示來源,通常是服務(wù)消費(fèi)者或調(diào)用者的應(yīng)用名稱,當(dāng)我們需要對不同來源的消費(fèi)者或調(diào)用者進(jìn)行限制時就會用到這個參數(shù)。

源碼如下:

public static Context enter(String name, String origin) {
    if (Constants.CONTEXT_DEFAULT_NAME.equals(name)) {
        throw new ContextNameDefineException(
            "The " + Constants.CONTEXT_DEFAULT_NAME + " can't be permit to defined!");
    }
    return trueEnter(name, origin);
}

protected static Context trueEnter(String name, String origin) {
    // 通過ThreadLocal獲取當(dāng)前線程的上下文
    Context context = contextHolder.get();
    // 如果沒獲取到需要新創(chuàng)建一個上下文
    if (context == null) {
        Map<String, DefaultNode> localCacheNameMap = contextNameNodeMap;
        // 根據(jù)上下文名稱獲取入口節(jié)點(diǎn)
        DefaultNode node = localCacheNameMap.get(name);
        // 入口節(jié)點(diǎn)節(jié)點(diǎn)也為空需要新創(chuàng)建入口節(jié)點(diǎn)
        if (node == null) {
            // 判斷是否超過最大長度限制(樂觀鎖機(jī)制)
            if (localCacheNameMap.size() > Constants.MAX_CONTEXT_NAME_SIZE) {
                setNullContext();
                return NULL_CONTEXT;
            } else {
                try {
                    LOCK.lock();
                    // 雙重判斷
                    node = contextNameNodeMap.get(name);
                    if (node == null) {
                        if (contextNameNodeMap.size() > Constants.MAX_CONTEXT_NAME_SIZE) {
                            setNullContext();
                            return NULL_CONTEXT;
                        } else {
                            // 新建入口節(jié)點(diǎn)
                            node = new EntranceNode(new StringResourceWrapper(name, EntryType.IN), null);
                            // 將入口節(jié)點(diǎn)添加到全局根節(jié)點(diǎn)下(machine-root)
                            Constants.ROOT.addChild(node);
                            // 類似寫復(fù)制容器機(jī)制
                            Map<String, DefaultNode> newMap = new HashMap<>(contextNameNodeMap.size() + 1);
                            newMap.putAll(contextNameNodeMap);
                            newMap.put(name, node);
                            contextNameNodeMap = newMap;
                        }
                    }
                } finally {
                    LOCK.unlock();
                }
            }
        }
        context = new Context(node, name);
        context.setOrigin(origin);
        contextHolder.set(context);
    }

    return context;
}

如果我們再代碼中顯示調(diào)用這個方法:

ContextUtil.enter("context1", "service-1"); 
...
ContextUtil.exit();

ContextUtil.enter("context2", "service-1"); 
...
ContextUtil.exit();

那么會創(chuàng)建如下一個樹結(jié)構(gòu)圖:

image.png

這里有兩點(diǎn)需要注意:

  1. 也就是上面說的數(shù)量限制,2000。
  2. ContextUtil是通過ThreadLocal來維護(hù)當(dāng)前線程的上下文的,所以當(dāng)遇到異步線程時需要手動調(diào)用ContextUtil.runOnContext(context, f)方法來完成父線程和子線程的上下文切換。

文檔中的Demo:

public void someAsync() {
    try {
        AsyncEntry entry = SphU.asyncEntry(resourceName);

        // Asynchronous invocation.
        doAsync(userId, result -> {
            // 在異步回調(diào)中進(jìn)行上下文變換,通過 AsyncEntry 的 getAsyncContext 方法獲取異步 Context
            ContextUtil.runOnContext(entry.getAsyncContext(), () -> {
                try {
                    // 此處嵌套正常的資源調(diào)用.
                    handleResult(result);
                } finally {
                    entry.exit();
                }
            });
        });
    } catch (BlockException ex) {
        // Request blocked.
        // Handle the exception (e.g. retry or fallback).
    }
}

lookProcessChain

Sentinel的核心功能是使用的是責(zé)任鏈模式實(shí)現(xiàn),lookProcessChain(resourceWrapper)的主要作用就是用來構(gòu)造責(zé)任鏈,源碼如下:

ProcessorSlot<Object> lookProcessChain(ResourceWrapper resourceWrapper) {
    // 根據(jù)資源的唯一標(biāo)識來做本地緩存
    ProcessorSlotChain chain = chainMap.get(resourceWrapper);
    if (chain == null) {
        synchronized (LOCK) {
            chain = chainMap.get(resourceWrapper);
            if (chain == null) {
                // 限制資源資對應(yīng)調(diào)用鏈的總數(shù),一個資源對應(yīng)一條調(diào)用鏈
                if (chainMap.size() >= Constants.MAX_SLOT_CHAIN_SIZE) {
                    return null;
                }
                // 構(gòu)建一個新的插槽鏈
                chain = SlotChainProvider.newSlotChain();
                // 寫復(fù)制容器做法
                Map<ResourceWrapper, ProcessorSlotChain> newMap = new HashMap<ResourceWrapper, ProcessorSlotChain>(
                    chainMap.size() + 1);
                newMap.putAll(chainMap);
                newMap.put(resourceWrapper, chain);
                chainMap = newMap;
            }
        }
    }
    return chain;
}

進(jìn)一步跟進(jìn)方法會發(fā)現(xiàn),責(zé)任鏈?zhǔn)怯?code>SlotChainBuilder#build()````去構(gòu)建的,默認(rèn)實(shí)現(xiàn)類是DefaultSlotChainBuilder```,源碼如下:

public class DefaultSlotChainBuilder implements SlotChainBuilder {

    @Override
    public ProcessorSlotChain build() {
        ProcessorSlotChain chain = new DefaultProcessorSlotChain();

        // 找到ProcessorSlot所有的實(shí)現(xiàn)類,并排序
        List<ProcessorSlot> sortedSlotList = SpiLoader.loadPrototypeInstanceListSorted(ProcessorSlot.class);
        for (ProcessorSlot slot : sortedSlotList) {
            if (!(slot instanceof AbstractLinkedProcessorSlot)) {
                RecordLog.warn("The ProcessorSlot(" + slot.getClass().getCanonicalName() + ") is not an instance of AbstractLinkedProcessorSlot, can't be added into ProcessorSlotChain");
                continue;
            }
            // 將功能槽放到責(zé)任鏈最后
            chain.addLast((AbstractLinkedProcessorSlot<?>) slot);
        }

        return chain;
    }
}

老版本直接是硬編碼方式:

public class DefaultSlotChainBuilder implements SlotChainBuilder {

    @Override
    public ProcessorSlotChain build() {
        ProcessorSlotChain chain = new DefaultProcessorSlotChain();
        chain.addLast(new NodeSelectorSlot());
        chain.addLast(new ClusterBuilderSlot());
        chain.addLast(new LogSlot());
        chain.addLast(new StatisticSlot());
        chain.addLast(new AuthoritySlot());
        chain.addLast(new SystemSlot());
        chain.addLast(new FlowSlot());
        chain.addLast(new DegradeSlot());

        return chain;
    }
}

以下內(nèi)容來自文檔

  • NodeSelectorSlot: 負(fù)責(zé)收集資源的路徑,并將這些資源的調(diào)用路徑,以樹狀結(jié)構(gòu)存儲起來,用于根據(jù)調(diào)用路徑來限流降級;
  • ClusterBuilderSlot: 則用于存儲資源的統(tǒng)計信息以及調(diào)用者信息,例如該資源的 RT, QPS, thread count 等等,這些信息將用作為多維度限流,降級的依據(jù);
  • StatisticSlot: 則用于記錄、統(tǒng)計不同緯度的 runtime 指標(biāo)監(jiān)控信息;
  • FlowSlot: 則用于根據(jù)預(yù)設(shè)的限流規(guī)則以及前面 slot 統(tǒng)計的狀態(tài),來進(jìn)行流量控制;
  • AuthoritySlot: 則根據(jù)配置的黑白名單和調(diào)用來源信息,來做黑白名單控制;
  • DegradeSlot: 則通過統(tǒng)計信息以及預(yù)設(shè)的規(guī)則,來做熔斷降級;
  • SystemSlot: 則通過系統(tǒng)的狀態(tài),例如 load1 等,來控制總的入口流量;

總結(jié)

  1. Sentinel 通過責(zé)任鏈模式,將各功能塊隔離,即清晰劃分出了各功能塊的職責(zé)邊界,也非常方便擴(kuò)展。新增功能直接新增功能插槽就行了,不需要改以前代碼。
  2. Sentinel 的本地緩存使用的是HashMap,通過加鎖和寫復(fù)制的思想來解決HashMap的線程安全性問題,在讀遠(yuǎn)大于寫的場景這種方式非常非常值得借鑒。

參考

https://github.com/alibaba/Sentinel/wiki/Sentinel-%E6%A0%B8%E5%BF%83%E7%B1%BB%E8%A7%A3%E6%9E%90

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容