免費(fèi)做網(wǎng)站bz3399西安百度公司
PartitionLeaderSelector
通過(guò)對(duì)前面的分析可知,PartitionMachine將Leader副本選舉、確定ISR集合的工作委托給了PartitionLeaderSelector接口實(shí)現(xiàn),PartitionMachine可以專注于管理分區(qū)狀態(tài)。這是策略模式的一種典型的應(yīng)用場(chǎng)景。
圖展示了PartitionLeaderSelector的實(shí)現(xiàn)類,這五個(gè)不同的實(shí)現(xiàn)提供了不同的策略。PartitionLeaderSelector接口的定義如下:
NoOpLeaderSelector是其中最簡(jiǎn)單的實(shí)現(xiàn),它并沒(méi)有進(jìn)行Leader選舉,而是將currentLeaderAndlsr直接返回,需要接收LeaderAndIsrRequest的Broker則是分區(qū)的AR集合。代碼就不貼出來(lái)了。
OfflinePartitionLeaderSelector會(huì)根據(jù)currentLeaderAndlsr選舉新的Leader和ISR集合,策略如下:
- 如果在ISR集合中存在至少一個(gè)可用的副本,則從ISR集合中選擇新的Leader副本,當(dāng)前ISR集合為新ISR集合。
- 如果ISR集合中沒(méi)有可用的副本且“Unclean leader election”配置被禁用,那么就拋出異常。
- 如果“Unclean leader election”被開(kāi)啟,則從AR集合中選擇新的Leader副本和ISR集合。
- 如果AR集合中沒(méi)有可用的副本,拋出異常。
對(duì)于剩余的PartitionLeaderSelector實(shí)現(xiàn),這里只介紹其策略。
PreferredReplicaPartitionLeaderSelector的策略是:如果“優(yōu)先副本”可用且在ISR集合中,則選取其為L(zhǎng)eader副本,當(dāng)前的ISR集合為新的ISR集合,并向AR集合中所有可用副本發(fā)送LeaderAndIsrRequest,否則會(huì)拋出異常。
ReassignedPartitionLeaderSelector涉及到副本的重新分配,副本重新分配的相關(guān)概念后面詳細(xì)分析,這里先簡(jiǎn)單了解ReassignedPartitionLeaderSelector的策略:選取的新Leader副本必須在新指定的AR集合中且同時(shí)在當(dāng)前ISR集合中,當(dāng)前ISR集合為新ISR集合,接收LeaderAndIsrRequest的副本是新指定的AR集合中的副本。
ControlledShutdownLeaderSelector的策略是:從當(dāng)前ISR集合中排除正在關(guān)閉的副本后作為新的ISR集合,從新ISR集合中選擇新的Leader,需要向AR集合中可用的副本發(fā)送LeaderAndIsrRequest。
ReplicaStateMachine
ReplicaStateMachine是Controller Leader用于維護(hù)副本狀態(tài)的狀態(tài)機(jī)。副本狀態(tài)由ReplicaState接口表示,它有七個(gè)子類,分別代表了副本的七種不同的狀態(tài),如表所示。
ReplicaState之間的轉(zhuǎn)換如圖所示。下面介紹各個(gè)ReplicaState狀態(tài)之間轉(zhuǎn)換時(shí)需要完成的相關(guān)操作。
- NonExistentReplica →NewReplica Controller向此副本所在Broker發(fā)送LeaderAndIsrRequest,并向集群中所有可用的Broker發(fā)送UpdateMetadataRequest。
- NewReplica →OnlineReplicaController將NewReplica加入到AR集合中。
- OnlineReplica,OfflineReplica→OnlineReplica
Controller向此副本所在的Broker發(fā)送LeaderAndIsrRequest,并向集群中所有可用的Broker發(fā)送UpdateMetadataRequest。
- NewReplica,OnlineReplica,OflineReplica,ReplicaDeletionIneligible →OffineReplica
Controller向副本所在Broker發(fā)送StopReplicaRequest,之后會(huì)從ISR集合中清除此副本,最后向其他可用副本所在的Broker發(fā)送LeaderAndIsrRequest,并向集群中所有可用的Broker發(fā)送UpdateMetadataRequest。 - OffineReplica→ReplicaDeletionStarted
Controller向副本所在Broker發(fā)送StopReplicaRequest。 - ReplicaDeletionStarted →ReplicaDeletionSuccessful只做狀態(tài)轉(zhuǎn)換,并沒(méi)有其他操作。
- ReplicaDeletionStarted →ReplicaDeletionIneligible只做狀態(tài)轉(zhuǎn)換,并沒(méi)有其他操作。
- ReplicaDeletionSuccessful →NonExistentReplicaController從AR集合中刪除此副本。
在ReplicaStateMachine中也有controllerContext、zkUtils、brokerRequestBatch字段,它們的功能與PartitionStateMachine中的同名字段相同,ReplicaStateMachine剩余的字段如下所述。
- replicaState:Map[PartitionAndReplica,ReplicaState]類型,記錄每個(gè)副本對(duì)應(yīng)的ReplicaState狀態(tài)。
- brokerChangeListener:ZooKeeper的監(jiān)聽(tīng)器,用于監(jiān)聽(tīng)Broker的變化,例如Broker宕機(jī)或重新上線等事件。
ReplicaStateMachine啟動(dòng)時(shí)會(huì)對(duì)replicaState集合進(jìn)行初始化,并調(diào)用handleStateChanges()方法嘗試將可用副本轉(zhuǎn)換為OnlineReplica狀態(tài)。