Sentinel的dashboard交互流程

查看入口

image.png

代碼為

@GetMapping("/rules")
    @AuthAction(PrivilegeType.READ_RULE)
    public Result<List<FlowRuleEntity>> apiQueryMachineRules(@RequestParam String app,
                                                             @RequestParam String ip,
                                                             @RequestParam Integer port) {

        if (StringUtil.isEmpty(app)) {
            return Result.ofFail(-1, "app can't be null or empty");
        }
        if (StringUtil.isEmpty(ip)) {
            return Result.ofFail(-1, "ip can't be null or empty");
        }
        if (port == null) {
            return Result.ofFail(-1, "port can't be null");
        }
        try {
            List<FlowRuleEntity> rules = sentinelApiClient.fetchFlowRuleOfMachine(app, ip, port);
            rules = repository.saveAll(rules);
            return Result.ofSuccess(rules);
        } catch (Throwable throwable) {
            logger.error("Error when querying flow rules", throwable);
            return Result.ofThrowable(-1, throwable);
        }
    }

fetchFlowRuleOfMachine

public List<FlowRuleEntity> fetchFlowRuleOfMachine(String app, String ip, int port) {
        List<FlowRule> rules = fetchRules(ip, port, FLOW_RULE_TYPE, FlowRule.class);
        if (rules != null) {
            return rules.stream().map(rule -> FlowRuleEntity.fromFlowRule(app, ip, port, rule))
                .collect(Collectors.toList());
        } else {
            return null;
        }
    }

調(diào)用鏈路為

com.alibaba.csp.sentinel.dashboard.client.SentinelApiClient#fetchRules
  ->com.alibaba.csp.sentinel.dashboard.client.SentinelApiClient#fetchItems
   ->com.alibaba.csp.sentinel.dashboard.client.SentinelApiClient#fetchItemsAsync
    ->com.alibaba.csp.sentinel.dashboard.client.SentinelApiClient#executeCommand()
private CompletableFuture<String> executeCommand(HttpUriRequest request) {
        CompletableFuture<String> future = new CompletableFuture<>();
        httpClient.execute(request, new FutureCallback<HttpResponse>() {
            @Override
            public void completed(final HttpResponse response) {
                int statusCode = response.getStatusLine().getStatusCode();
                try {
                    String value = getBody(response);
                    if (isSuccess(statusCode)) {
                        future.complete(value);
                    } else {
                        if (isCommandNotFound(statusCode, value)) {
                            future.completeExceptionally(new CommandNotFoundException(request.getURI().getPath()));
                        } else {
                            future.completeExceptionally(new CommandFailedException(value));
                        }
                    }

                } catch (Exception ex) {
                    future.completeExceptionally(ex);
                    logger.error("HTTP request failed: {}", request.getURI().toString(), ex);
                }
            }

            @Override
            public void failed(final Exception ex) {
                future.completeExceptionally(ex);
                logger.error("HTTP request failed: {}", request.getURI().toString(), ex);
            }

            @Override
            public void cancelled() {
                future.complete(null);
            }
        });
        return future;
    }

從代碼中可以看到,是通過一個(gè)異步的 httpClient 再結(jié)合 CountDownLatch 等待 5 秒的超時(shí)時(shí)間去獲取結(jié)果的。

獲取數(shù)據(jù)的請(qǐng)求從 dashboard 中發(fā)出去了正压,那 sentinel-core 中是怎么進(jìn)行相應(yīng)處理的呢崇猫?

sentinel-core 在啟動(dòng)的時(shí)候买猖,執(zhí)行了一個(gè) InitExecutor.init 的方法婆赠,該方法會(huì)觸發(fā)所有 InitFunc 實(shí)現(xiàn)類的 init 方法,其中就包括兩個(gè)最重要的實(shí)現(xiàn)類:

  • HeartbeatSenderInitFunc
  • CommandCenterInitFunc

CommandCenterInitFunc 則會(huì)啟動(dòng)一個(gè) CommandCenter 對(duì)外提供 sentinel-core 的數(shù)據(jù)服務(wù)渊迁,而這些數(shù)據(jù)服務(wù)是通過一個(gè)一個(gè)的 CommandHandler 來提供的,如下圖所示:


image.png

Sentinel-core的啟動(dòng)流程

com.alibaba.csp.sentinel.SphU#entry()
 ->com.alibaba.csp.sentinel.Env#sph
 ->com.alibaba.csp.sentinel.init.InitExecutor#doInit
  ->com.alibaba.csp.sentinel.transport.init.HeartbeatSenderInitFunc#init
  ->com.alibaba.csp.sentinel.transport.init.CommandCenterInitFunc#init

CommandCenterInitFunc的初始化

public void init() throws Exception {
        CommandCenter commandCenter = CommandCenterProvider.getCommandCenter();

        if (commandCenter == null) {
            RecordLog.warn("[CommandCenterInitFunc] Cannot resolve CommandCenter");
            return;
        }

        commandCenter.beforeStart();
        commandCenter.start();
        RecordLog.info("[CommandCenterInit] Starting command center: "
                + commandCenter.getClass().getCanonicalName());
    }
com.alibaba.csp.sentinel.transport.command.SimpleHttpCommandCenter#start
 ->com.alibaba.csp.sentinel.transport.command.SimpleHttpCommandCenter.ServerThread#run
  ->com.alibaba.csp.sentinel.transport.command.http.HttpEventTask#run
   ->com.alibaba.csp.sentinel.transport.command.SimpleHttpCommandCenter#getHandler
   

關(guān)鍵代碼為

// Find the matching command handler.
            CommandHandler<?> commandHandler = SimpleHttpCommandCenter.getHandler(commandName);
            if (commandHandler != null) {
                CommandResponse<?> response = commandHandler.handle(request);
                handleResponse(response, printWriter);
            } else {
                // No matching command handler.
                writeResponse(printWriter, StatusCode.BAD_REQUEST, "Unknown command `" + commandName + '`');
            }

心跳發(fā)送流程

HeartbeatSenderInitFunc 會(huì)啟動(dòng)一個(gè) HeartbeatSender 來定時(shí)的向 dashboard 發(fā)送自己的心跳包

public void init() {
        HeartbeatSender sender = HeartbeatSenderProvider.getHeartbeatSender();
        if (sender == null) {
            RecordLog.warn("[HeartbeatSenderInitFunc] WARN: No HeartbeatSender loaded");
            return;
        }

        initSchedulerIfNeeded();
        long interval = retrieveInterval(sender);
        setIntervalIfNotExists(interval);
        scheduleHeartbeatTask(sender, interval);
    }

scheduleHeartbeatTask

private void scheduleHeartbeatTask(/*@NonNull*/ final HeartbeatSender sender, /*@Valid*/ long interval) {
        pool.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                try {
                    sender.sendHeartbeat();
                } catch (Throwable e) {
                    RecordLog.warn("[HeartbeatSender] Send heartbeat error", e);
                }
            }
        }, 5000, interval, TimeUnit.MILLISECONDS);
        RecordLog.info("[HeartbeatSenderInit] HeartbeatSender started: "
            + sender.getClass().getCanonicalName());
    }

com.alibaba.csp.sentinel.transport.heartbeat.SimpleHttpHeartbeatSender#sendHeartbeat

public boolean sendHeartbeat() throws Exception {
        if (TransportConfig.getRuntimePort() <= 0) {
            RecordLog.info("[SimpleHttpHeartbeatSender] Command server port not initialized, won't send heartbeat");
            return false;
        }
        Endpoint addrInfo = getAvailableAddress();
        if (addrInfo == null) {
            return false;
        }

        SimpleHttpRequest request = new SimpleHttpRequest(addrInfo, TransportConfig.getHeartbeatApiPath());
        request.setParams(heartBeat.generateCurrentMessage());
        try {
            SimpleHttpResponse response = httpClient.post(request);
            if (response.getStatusCode() == OK_STATUS) {
                return true;
            } else if (clientErrorCode(response.getStatusCode()) || serverErrorCode(response.getStatusCode())) {
                RecordLog.warn("[SimpleHttpHeartbeatSender] Failed to send heartbeat to " + addrInfo
                    + ", http status code: " + response.getStatusCode());
            }
        } catch (Exception e) {
            RecordLog.warn("[SimpleHttpHeartbeatSender] Failed to send heartbeat to " + addrInfo, e);
        }
        return false;
    }

繼續(xù)深入

com.alibaba.csp.sentinel.transport.heartbeat.SimpleHttpHeartbeatSender#sendHeartbeat
 ->com.alibaba.csp.sentinel.transport.heartbeat.SimpleHttpHeartbeatSender#getAvailableAddress
  ->com.alibaba.csp.sentinel.transport.heartbeat.SimpleHttpHeartbeatSender#SimpleHttpHeartbeatSender
   -> com.alibaba.csp.sentinel.transport.config.TransportConfig#getConsoleServerList
image.png

com.alibaba.csp.sentinel.dashboard.controller.MachineRegistryController#receiveHeartBeat代碼如下

@ResponseBody
    @RequestMapping("/machine")
    public Result<?> receiveHeartBeat(String app, @RequestParam(value = "app_type", required = false, defaultValue = "0") Integer appType, Long version, String v, String hostname, String ip, Integer port) {
        if (app == null) {
            app = MachineDiscovery.UNKNOWN_APP_NAME;
        }
        if (ip == null) {
            return Result.ofFail(-1, "ip can't be null");
        }
        if (port == null) {
            return Result.ofFail(-1, "port can't be null");
        }
        if (port == -1) {
            logger.info("Receive heartbeat from " + ip + " but port not set yet");
            return Result.ofFail(-1, "your port not set yet");
        }
        String sentinelVersion = StringUtil.isEmpty(v) ? "unknown" : v;
        version = version == null ? System.currentTimeMillis() : version;
        try {
            MachineInfo machineInfo = new MachineInfo();
            machineInfo.setApp(app);
            machineInfo.setAppType(appType);
            machineInfo.setHostname(hostname);
            machineInfo.setIp(ip);
            machineInfo.setPort(port);
            machineInfo.setHeartbeatVersion(version);
            machineInfo.setLastHeartbeat(System.currentTimeMillis());
            machineInfo.setVersion(sentinelVersion);
            appManagement.addMachine(machineInfo);
            return Result.ofSuccessMsg("success");
        } catch (Exception e) {
            logger.error("Receive heartbeat error", e);
            return Result.ofFail(-1, e.getMessage());
        }
    }

小結(jié)

  1. sentinel-core 在初始化的時(shí)候灶挟,通過 JVM 參數(shù)中指定的 dashboard 的 ip 和 port琉朽,會(huì)主動(dòng)向 dashboard 發(fā)起連接的請(qǐng)求,該請(qǐng)求是通過 HeartbeatSender 接口以心跳的方式發(fā)送的稚铣,并將自己的 ip 和 port 告知 dashboard箱叁。這里 sentinel-core 上報(bào)給 dashboard 的端口是 sentinel 對(duì)外暴露的自己的 CommandCenter 的端口。
  2. dashboard 在接收到 sentinel-core 的連接之后惕医,就會(huì)與 sentinel-core 建立連接耕漱,并將 sentinel-core 上報(bào)的 ip 和 port 的信息包裝成一個(gè) MachineInfo 對(duì)象,然后通過 SimpleMachineDiscovery 將該對(duì)象保存在一個(gè) map 中抬伺,如下圖所示:


    image.png

dashboard 獲取到實(shí)時(shí)數(shù)據(jù)完整流程

  1. 首先 sentinel-core 向 dashboard 發(fā)送心跳包

  2. dashboard 將 sentinel-core 的機(jī)器信息保存在內(nèi)存中

  3. dashboard 根據(jù) sentinel-core 的機(jī)器信息通過 httpClient 獲取實(shí)時(shí)的數(shù)據(jù)

  4. sentinel-core 接收到請(qǐng)求之后螟够,會(huì)找到具體的 CommandHandler 來處理

  5. sentinel-core 將處理好的結(jié)果返回給 dashboard

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市峡钓,隨后出現(xiàn)的幾起案子妓笙,更是在濱河造成了極大的恐慌,老刑警劉巖能岩,帶你破解...
    沈念sama閱讀 217,277評(píng)論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件寞宫,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡拉鹃,警方通過查閱死者的電腦和手機(jī)淆九,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,689評(píng)論 3 393
  • 文/潘曉璐 我一進(jìn)店門统锤,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人炭庙,你說我怎么就攤上這事饲窿。” “怎么了焕蹄?”我有些...
    開封第一講書人閱讀 163,624評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵逾雄,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我腻脏,道長(zhǎng)鸦泳,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,356評(píng)論 1 293
  • 正文 為了忘掉前任永品,我火速辦了婚禮做鹰,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘鼎姐。我一直安慰自己钾麸,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,402評(píng)論 6 392
  • 文/花漫 我一把揭開白布炕桨。 她就那樣靜靜地躺著饭尝,像睡著了一般。 火紅的嫁衣襯著肌膚如雪献宫。 梳的紋絲不亂的頭發(fā)上钥平,一...
    開封第一講書人閱讀 51,292評(píng)論 1 301
  • 那天,我揣著相機(jī)與錄音姊途,去河邊找鬼涉瘾。 笑死,一個(gè)胖子當(dāng)著我的面吹牛捷兰,可吹牛的內(nèi)容都是我干的立叛。 我是一名探鬼主播,決...
    沈念sama閱讀 40,135評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼寂殉,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼囚巴!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起友扰,我...
    開封第一講書人閱讀 38,992評(píng)論 0 275
  • 序言:老撾萬榮一對(duì)情侶失蹤彤叉,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后村怪,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體秽浇,經(jīng)...
    沈念sama閱讀 45,429評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,636評(píng)論 3 334
  • 正文 我和宋清朗相戀三年甚负,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了柬焕。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片审残。...
    茶點(diǎn)故事閱讀 39,785評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖斑举,靈堂內(nèi)的尸體忽然破棺而出搅轿,到底是詐尸還是另有隱情,我是刑警寧澤富玷,帶...
    沈念sama閱讀 35,492評(píng)論 5 345
  • 正文 年R本政府宣布璧坟,位于F島的核電站,受9級(jí)特大地震影響赎懦,放射性物質(zhì)發(fā)生泄漏雀鹃。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,092評(píng)論 3 328
  • 文/蒙蒙 一励两、第九天 我趴在偏房一處隱蔽的房頂上張望黎茎。 院中可真熱鬧,春花似錦当悔、人聲如沸傅瞻。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,723評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)俭正。三九已至奸鬓,卻和暖如春焙畔,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背串远。 一陣腳步聲響...
    開封第一講書人閱讀 32,858評(píng)論 1 269
  • 我被黑心中介騙來泰國(guó)打工宏多, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人澡罚。 一個(gè)月前我還...
    沈念sama閱讀 47,891評(píng)論 2 370
  • 正文 我出身青樓伸但,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親留搔。 傳聞我的和親對(duì)象是個(gè)殘疾皇子更胖,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,713評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容