nifi學(xué)習(xí)筆記--Remote ProcessGroup源碼解析

由于nifi cluster的數(shù)據(jù)分發(fā)只能使用Remote ProcessGroup沛豌,然后通過(guò)site-to-site協(xié)議來(lái)分發(fā)數(shù)據(jù)到各個(gè)nifi instance。所以看了Remote ProcessGroup的源碼着绊,現(xiàn)將理解記錄下來(lái)。

RemoteProcessGroup

org.apache.nifi.groups.RemoteProcessGroup是Remote ProcessGroup的接口熟尉,主要函數(shù)為:


/**

* Initiates communications between this instance and the remote instance.

*/

void startTransmitting();

/**

* Immediately terminates communications between this instance and the

* remote instance.

*/

void stopTransmitting();

org.apache.nifi.remote.StandardRemoteProcessGroup實(shí)現(xiàn)了RemoteProcessGroup接口归露,在函數(shù)startTransmitting()中啟動(dòng)了綁定給它的StandardRemoteGroupPort。

StandardRemoteGroupPort

org.apache.nifi.remote.StandardRemoteGroupPort由RemoteProcessGroup啟動(dòng)斤儿,是實(shí)現(xiàn)數(shù)據(jù)傳輸?shù)闹饕惥绨饕獙?duì)象是SiteToSiteClient,主要函數(shù)由onSchedulingStart()和onTrigger()往果。


public void onSchedulingStart() {
        super.onSchedulingStart();

        final long penalizationMillis = FormatUtils.getTimeDuration(remoteGroup.getYieldDuration(), TimeUnit.MILLISECONDS);

        final SiteToSiteClient client = new SiteToSiteClient.Builder()
                .url(remoteGroup.getTargetUri().toString())
                .portIdentifier(getIdentifier())
                .sslContext(sslContext)
                .useCompression(isUseCompression())
                .eventReporter(remoteGroup.getEventReporter())
                .peerPersistenceFile(getPeerPersistenceFile(getIdentifier(), nifiProperties))
                .nodePenalizationPeriod(penalizationMillis, TimeUnit.MILLISECONDS)
                .timeout(remoteGroup.getCommunicationsTimeout(TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS)
                .transportProtocol(remoteGroup.getTransportProtocol())
                .httpProxy(new HttpProxy(remoteGroup.getProxyHost(), remoteGroup.getProxyPort(), remoteGroup.getProxyUser(), remoteGroup.getProxyPassword()))
                .build();
        clientRef.set(client);
    }

onSchedulingStart()函數(shù)創(chuàng)建SiteToSiteClient疆液,這是site-to-site協(xié)議的主要client接口。

  @Override
    public void onTrigger(final ProcessContext context, final ProcessSession session) {
        ...
        final SiteToSiteClient client = getSiteToSiteClient();
        final Transaction transaction;
        transaction = client.createTransaction(transferDirection);
        ...
                transferFlowFiles(transaction, context, session, firstFlowFile);
         ....
        }
    }

onTrigger()函數(shù)用來(lái)傳輸數(shù)據(jù)到另外的nifi instance陕贮,此處用到了Transaction來(lái)傳輸數(shù)據(jù)堕油。
SiteToSiteClient
===========
SiteToSiteClient是site-to-site協(xié)議的接口,分為兩種實(shí)現(xiàn)SocketClient和HttpClient兩種,具體對(duì)應(yīng)Remote ProcessGroup界面配置中的兩種協(xié)議掉缺,這里主要討論SocketClient的實(shí)現(xiàn)卜录。

org.apache.nifi.remote.client.socket.SocketClient通過(guò)createTransaction()函數(shù)來(lái)創(chuàng)建SocketClientTransaction。


    @Override
    public Transaction createTransaction(final TransferDirection direction) throws IOException {
       ...

        final EndpointConnection connectionState = pool.getEndpointConnection(direction, getConfig());
        if (connectionState == null) {
            return null;
        }

        final Transaction transaction;
        try {
            transaction = connectionState.getSocketClientProtocol().startTransaction(
                    connectionState.getPeer(), connectionState.getCodec(), direction);
        } catch (final Throwable t) {
            pool.terminate(connectionState);
            throw new IOException("Unable to create Transaction to communicate with " + connectionState.getPeer(), t);
        }

      ...
    }

EndpointConnectionPool

此處的pool為EndpointConnectionPool眶明,它是一個(gè)EndpointConnection池艰毒,保存了EndpointConnection的map。

private final ConcurrentMap<PeerDescription, BlockingQueue<EndpointConnection>> connectionQueueMap = new ConcurrentHashMap<>();

另外搜囱,它保存了一個(gè)遠(yuǎn)端鏈接信息PeerStatus的選擇器PeerSelector.

private final PeerSelector peerSelector;

EndpointConnection

EndpointConnection就是實(shí)際上與遠(yuǎn)端nifi instance的鏈接,它保存了與遠(yuǎn)端的數(shù)據(jù)通道Peer和handshake工具對(duì)象SocketClientProtocol丑瞧。
PeerSelector


它提供了獲得下一個(gè)PeerStatus函數(shù)getNextPeerStatus()跟新鏈接信息的函數(shù)refreshPeers()。

 /**
     * Return status of a peer that will be used for the next communication.
     * The peer with less workload will be selected with higher probability.
     * @param direction the amount of workload is calculated based on transaction direction,
     *                  for SEND, a peer with less flow files is preferred,
     *                  for RECEIVE, a peer with more flow files is preferred
     * @return a selected peer, if there is no available peer or all peers are penalized, then return null
     */
    public PeerStatus getNextPeerStatus(final TransferDirection direction) {
       List<PeerStatus> peerList = peerStatuses;
        if (isPeerRefreshNeeded(peerList)) {
            peerRefreshLock.lock();
            try {
                // now that we have the lock, check again that we need to refresh (because another thread
                // could have been refreshing while we were waiting for the lock).
                peerList = peerStatuses;
                if (isPeerRefreshNeeded(peerList)) {
                    try {
                        peerList = createPeerStatusList(direction);
                    } catch (final Exception e) {
                        final String message = String.format("%s Failed to update list of peers due to %s", this, e.toString());
                        warn(logger, eventReporter, message);
                        if (logger.isDebugEnabled()) {
                            logger.warn("", e);
                        }
                    }

                    this.peerStatuses = peerList;
                    peerRefreshTime = systemTime.currentTimeMillis();
                }
            } finally {
                peerRefreshLock.unlock();
            }
        }

        if (peerList == null || peerList.isEmpty()) {
            return null;
        }
    }

這里的createPeerStatusList會(huì)根據(jù)遠(yuǎn)端nifi instance上端口接收或者發(fā)送的flowfiles的數(shù)量和direction對(duì)peer排序蜀肘。當(dāng)是在發(fā)送數(shù)據(jù)的時(shí)候嗦篱,選取目前需要接收的數(shù)據(jù)最少的nifi instance對(duì)應(yīng)的peer來(lái)發(fā)送數(shù)據(jù)。當(dāng)是在接收數(shù)據(jù)時(shí)幌缝,選取目前需要發(fā)送的數(shù)據(jù)量最大的nifi instance對(duì)應(yīng)的peer來(lái)接收數(shù)據(jù)。通過(guò)這個(gè)機(jī)制來(lái)達(dá)到cluster的負(fù)載均衡诫欠。

private Set<PeerStatus> fetchRemotePeerStatuses() throws IOException {
        final Set<PeerDescription> peersToRequestClusterInfoFrom = new HashSet<>();

        // Look at all of the peers that we fetched last time.
        final Set<PeerStatus> lastFetched = lastFetchedQueryablePeers;
        if (lastFetched != null && !lastFetched.isEmpty()) {
            lastFetched.stream().map(peer -> peer.getPeerDescription())
                    .forEach(desc -> peersToRequestClusterInfoFrom.add(desc));
        }

        // Always add the configured node info to the list of peers to communicate with
        peersToRequestClusterInfoFrom.add(peerStatusProvider.getBootstrapPeerDescription());

        logger.debug("Fetching remote peer statuses from: {}", peersToRequestClusterInfoFrom);
        Exception lastFailure = null;
        for (final PeerDescription peerDescription : peersToRequestClusterInfoFrom) {
            try {
                final Set<PeerStatus> statuses = peerStatusProvider.fetchRemotePeerStatuses(peerDescription);
                lastFetchedQueryablePeers = statuses.stream()
                        .filter(p -> p.isQueryForPeers())
                        .collect(Collectors.toSet());

                return statuses;
            } catch (final Exception e) {
                logger.warn("Could not communicate with {}:{} to determine which nodes exist in the remote NiFi cluster, due to {}",
                        peerDescription.getHostname(), peerDescription.getPort(), e.toString());
                lastFailure = e;
            }
        }

        final IOException ioe = new IOException("Unable to communicate with remote NiFi cluster in order to determine which nodes exist in the remote cluster");
        if (lastFailure != null) {
            ioe.addSuppressed(lastFailure);
        }

        throw ioe;
    }

refreshPeers函數(shù)調(diào)用了fetchRemotePeerStatuses()函數(shù),這個(gè)函數(shù)中對(duì)于每一個(gè)之前記錄過(guò)的peer都會(huì)去訪問(wèn)以跟新整個(gè)集群狀態(tài)涵卵,所以只要第一次啟動(dòng)的時(shí)候配置的url nifi instance是有效的,以后就算它掛了荒叼,理論上也是不影響其他節(jié)點(diǎn)數(shù)據(jù)的正常發(fā)送和接收的轿偎。

而且refreshPeers()函數(shù)是在EndpointConnectionPool構(gòu)造的時(shí)候,去不斷調(diào)用的被廓,所以site-to-site協(xié)議會(huì)不斷的跟新cluster中節(jié)點(diǎn)的狀態(tài)坏晦,保證數(shù)據(jù)的可靠性。

 taskExecutor.scheduleWithFixedDelay(new Runnable() {
            @Override
            public void run() {
                peerSelector.refreshPeers();
            }
        }, 0, 5, TimeUnit.SECONDS);
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末嫁乘,一起剝皮案震驚了整個(gè)濱河市昆婿,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌蜓斧,老刑警劉巖仓蛆,帶你破解...
    沈念sama閱讀 218,546評(píng)論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異挎春,居然都是意外死亡看疙,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,224評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門(mén)直奋,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)能庆,“玉大人,你說(shuō)我怎么就攤上這事脚线「榈ǎ” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 164,911評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)丰涉。 經(jīng)常有香客問(wèn)我拓巧,道長(zhǎng),這世上最難降的妖魔是什么一死? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,737評(píng)論 1 294
  • 正文 為了忘掉前任肛度,我火速辦了婚禮,結(jié)果婚禮上投慈,老公的妹妹穿的比我還像新娘承耿。我一直安慰自己,他們只是感情好伪煤,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,753評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布加袋。 她就那樣靜靜地躺著,像睡著了一般抱既。 火紅的嫁衣襯著肌膚如雪职烧。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 51,598評(píng)論 1 305
  • 那天防泵,我揣著相機(jī)與錄音蚀之,去河邊找鬼。 笑死捷泞,一個(gè)胖子當(dāng)著我的面吹牛足删,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播锁右,決...
    沈念sama閱讀 40,338評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼失受,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了咏瑟?” 一聲冷哼從身側(cè)響起拂到,我...
    開(kāi)封第一講書(shū)人閱讀 39,249評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎码泞,沒(méi)想到半個(gè)月后谆焊,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,696評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡浦夷,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,888評(píng)論 3 336
  • 正文 我和宋清朗相戀三年辖试,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片劈狐。...
    茶點(diǎn)故事閱讀 40,013評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡罐孝,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出肥缔,到底是詐尸還是另有隱情莲兢,我是刑警寧澤,帶...
    沈念sama閱讀 35,731評(píng)論 5 346
  • 正文 年R本政府宣布,位于F島的核電站改艇,受9級(jí)特大地震影響收班,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜谒兄,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,348評(píng)論 3 330
  • 文/蒙蒙 一摔桦、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧承疲,春花似錦邻耕、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,929評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至啊研,卻和暖如春御滩,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背党远。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,048評(píng)論 1 270
  • 我被黑心中介騙來(lái)泰國(guó)打工艾恼, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人麸锉。 一個(gè)月前我還...
    沈念sama閱讀 48,203評(píng)論 3 370
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像舆声,于是被迫代替她去往敵國(guó)和親花沉。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,960評(píng)論 2 355

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

  • Spring Cloud為開(kāi)發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理媳握,服務(wù)發(fā)現(xiàn)碱屁,斷路器,智...
    卡卡羅2017閱讀 134,657評(píng)論 18 139
  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語(yǔ)法蛾找,類相關(guān)的語(yǔ)法娩脾,內(nèi)部類的語(yǔ)法,繼承相關(guān)的語(yǔ)法打毛,異常的語(yǔ)法柿赊,線程的語(yǔ)...
    子非魚(yú)_t_閱讀 31,634評(píng)論 18 399
  • 從三月份找實(shí)習(xí)到現(xiàn)在,面了一些公司幻枉,掛了不少碰声,但最終還是拿到小米、百度熬甫、阿里胰挑、京東、新浪、CVTE瞻颂、樂(lè)視家的研發(fā)崗...
    時(shí)芥藍(lán)閱讀 42,251評(píng)論 11 349
  • 北京時(shí)間2015年6月28日贡这,SpaceX發(fā)射了一枚火箭茬末,在升空148秒后爆炸。具體原因目前還不知道藕坯。 看到這個(gè)新...
    如意羊故事坊閱讀 708評(píng)論 0 1
  • 1. 我厚著臉皮求南陽(yáng)和我和好了炼彪。 他和我和好只是因?yàn)槭懿涣宋业乃览p爛打吐根。 而我求他和我和好,是因?yàn)榉恚疫€愛(ài)他拷橘。 ...
    H二多閱讀 375評(píng)論 8 4