zookeeper 儲存基本都是在SyncRequestProcessor 單個線程完成的
1) 初始化
1.1)DataTree初始化
public DataTree() { /* Rather than fight it, let root have an alias */ nodes.put("", root); nodes.put(rootZookeeper, root); /** add the proc node and quota node */ root.addChild(procChildZookeeper); nodes.put(procZookeeper, procDataNode); procDataNode.addChild(quotaChildZookeeper); nodes.put(quotaZookeeper, quotaDataNode); }
會有3個節點 /、/zookeeper、/zookeeper/quota 內容為空白
注意DataTree維護了兩個資料結構
一個是ConcurrentHashMap<String, DataNode> nodes,所有的節點都可以在這查到
一個是DataNode,DataNode包含了Set<String> children,含有父子關係
也就是說通過DataNode可以遍曆到子node的路徑(索引),然後通過索引去nodes查到node執行個體
1.2)載入snapshot 和 committedlog中的事務到記憶體樹
【詳見ZKDatabase.loadDataBase--->FileTxnSnapLog.restore】
首先會載入多個snapshot到記憶體數中
怎麼會有多個snapshot不理解。
載入committedlog
系統會產生多個committedlog,以事務的序號作為尾碼名,比如1-50個事務放在log.1, 51-100放在log.51,......
檔案名稱中尾碼序號就是檔案中第一個序號
由於snapshot和committedlog並非完全同步,通常情況下,committedlog資訊會多於snapshot,比如snapshot記錄到了第80條事務,
但committedlog 可能記錄了150條事務,因此在載入的時候,就應該聯合snapshot和committedlog
如何聯合。舉個例子,就拿上面的例子來說,假設共有150條事務,併產生了3個記錄檔,log.1,log.51,log.100
snapshot記錄到了第80條,那麼就還應該需要log.51和log.100來做合并,程式會從log.51中第81條事務開始載入
【詳見TxnIterator】
1.3)處理到期session
【詳見ZooKeeperServer.killSession-->zkDb.killSession】
zkDb.killSession為什麼沒有產生binlog?
1.4 ) 產生快照見ZooKeeperServer.takeSnapshot
2)運行過程
一個專門的線程SyncRequestProcessor不斷處理儲存請求【詳見SyncRequestProcessor.run】
以一個典型產生node的情境為例
zk.create("/root", "mydata".getBytes(), Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT);
2.1)擷取請求並決定是否應該flush到磁碟
if (toFlush.isEmpty()) { si = queuedRequests.take(); } else { si = queuedRequests.poll(); if (si == null) { flush(toFlush); continue; } }
如果toFlush列表中沒有需要flush的請求,那麼就阻塞等待請求
否則已非阻塞的方式從請求隊列去請求,一旦沒有請求就flush
可見zookeeper選擇在閒置時候flush,這是flush的時機之一
flush的具體功能【詳見SyncRequestProcessor.flush】
toFlush 見3.0)節
2.2)線程是否應該結束
if (si == requestOfDeath) { break; }
如果請求是特殊的請求Request.requestOfDeath,那麼線程結束,典型的隊列哨兵模式
2.3)寫log
【詳見FileTxnLog.append】
將修改類的請求寫入log,類似mysql的binlog
如果寫入到2.4) 否則到2.5
2.4)是否應該roll log
如果是事務型的請求,那麼zks.getZKDatabase().append(si)會返回true
是否是事務型的請求。
if (zks.getZKDatabase().append(si)) { logCount++; if (logCount > (snapCount / 2 + randRoll)) { randRoll = r.nextInt(snapCount/2); // roll the log zks.getZKDatabase().rollLog(); // take a snapshot if (snapInProcess != null && snapInProcess.isAlive()) { LOG.warn("Too busy to snap, skipping"); } else { snapInProcess = new Thread("Snapshot Thread") { public void run() { try { zks.takeSnapshot(); } catch(Exception e) { LOG.warn("Unexpected exception", e); } } }; snapInProcess.start(); } logCount = 0; } }
每寫入一條日誌,logCount++, 加到一定數量,開始roll log,
如果此時並沒有在產生快照,為了不阻塞線程,會起一個臨時線程產生快照,然後將logCount清0
每次產生快照都會以snap.${Long.toHexString(dataTree.lastProcessedZxid)}來命名
2.5) 是否應該直接響應
else if (toFlush.isEmpty()) { // optimization for read heavy workloads // iff this is a read, and there are no pending // flushes (writes), then just pass this to the next // processor nextProcessor.processRequest(si); if (nextProcessor instanceof Flushable) { ((Flushable)nextProcessor).flush(); } continue; }
查看此時toFlush(響應隊列)是否為空白,如果為空白,說明近一段時間讀多寫少,直接就響應了
2.6)最後的處理
toFlush.add(si);if (toFlush.size() > 1000) { flush(toFlush);}
如果沒有直接響應,那麼就將請求加入toFlush(響應隊列),如果此時toFlush隊列長度超過1000,就flush了
到此為止,toFlush(響應隊列)看上去邏輯混亂,下面會專門講,另外flush的用途也會接下來講
3)FAQ
3.0)toFlush到底是什麼。
toFlush隊列用於儲存請求,可能是讀也可能是寫
zookeeper專門使用了一個線程SyncRequestProcessor來處理請求,所以這個線程必須合理的工作,否則就會對整體的效能造成傷害
如果都是讀請求就沒必要toFlush了,但如果是寫請求,就必須把請求寫入log,這個寫入未必能保證真的同步到磁碟,但如果每次寫請求都同步,
效能會有問題,所以從程式的設計應該能看到作者應該是處於這個考慮選擇了兩個時機來做這件事情
如果沒有請求的時候(即較閒置時候)
toFlush隊列到了一定數量(1000),就會批量同步
可以看到的一些問題
由於要選擇合適的時機flush,用戶端的響應會受到影響,為什麼不考慮分離磁碟同步和響應用戶端。為了更嚴謹。
如果寫多讀少,寫會干擾讀,因為所有的寫都會加入到toFlush隊列,而如果toFlush隊列不為空白,讀也會放進去,正如上面提到的,toFlush並不會立即響應
3.1 )flush幹了什麼。怎麼實現的。
private void flush(LinkedList<Request> toFlush) throws IOException { if (toFlush.isEmpty()) return; zks.getZKDatabase().commit(); while (!toFlush.isEmpty()) { Request i = toFlush.remove(); nextProcessor.processRequest(i); } if (nextProcessor instanceof Flushable) { ((Flushable)nextProcessor).flush(); } }
同步磁碟zks.getZKDatabase().commit()
調用nextProcessor的方法響應網路請求,
通常情況下nextProcessor是FinalRequestProcessor且與Flushable沒有關係
所以只需關注FinalRequestProcessor.processRequest方法,下面會提到
3.2)zks.getZKDatabase().commit() 幹了什麼。
zks.getZKDatabase().commit()實際調用了FileTxnLog.commit,代碼如下
public synchronized void commit() throws IOException { if (logStream != null) { logStream.flush(); } for (FileOutputStream log : streamsToFlush) { log.flush(); if (forceSync) { long startSyncNS = System.nanoTime(); log.getChannel().force(false); long syncElapsedMS = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startSyncNS); if (syncElapsedMS > fsyncWarningThresholdMS) { LOG.warn("fsync-ing the write ahead log in " + Thread.currentThread().getName() + " took " + syncElapsedMS + "ms which will adversely effect operation latency. " + "See the ZooKeeper troubleshooting guide"); } } } while (streamsToFlush.size() > 1) { streamsToFlush.removeFirst().close(); } }
將當前流logStream flush
將之前append的流streamsToFlush逐個flush;forceSync預設為true,因此會調用log.getChannel().force同步到磁碟
完成之後,會將streamsToFlush中的流刪除
上面的flush和getChannel().force的差別。
一個是應用級一個是磁碟級,當調用flush會將應用資料緩衝區中的全部提交給磁碟驅動去調度,但此時也未必全部同步到磁碟
磁碟寫一般是非同步,所以後者會保證全部同步到磁碟,類似作業系統的API fsync
3)FinalRequestProcessor 如何?的。
3.3.1)處理outstandingChanges
synchronized (zks.outstandingChanges) { while (!zks.outstandingChanges.isEmpty() && zks.outstandingChanges.get(0).zxid <= request.zxid) { ChangeRecord cr = zks.outstandingChanges.remove(0); if (cr.zxid < request.zxid) { LOG.warn("Zxid outstanding " + cr.zxid + " is less than current " + request.zxid); } if (zks.outstandingChangesForPath.get(cr.path) == cr) { zks.outstandingChangesForPath.remove(cr.path); } } if (request.hdr != null) { TxnHeader hdr = request.hdr; Record txn = request.txn; rc = zks.processTxn(hdr, txn); } // do not add non quorum packets to the queue. if (Request.isQuorum(request.type)) { zks.getZKDatabase().addCommittedProposal(request); } }
outstandingChanges是一個事務型請求的冗餘隊列,一旦處理完相關的事物請求,需要將outstandingChanges的相關item刪除
處理事務型請求,主要是涉及datatree的寫操作
最後會將請求放入ZKDatabase的committedLog,便於叢集中的其他機器快速同步 3.3.2)構造響應
接下來開始一長段的switch/case根據請求類型進行處理,基本都會構造響應
以一個事務型請求為例
case OpCode.setData: { lastOp = "SETD"; rsp = new SetDataResponse(rc.stat); err = Code.get(rc.err); break; }
再看看一個非事務型請求的例子
case OpCode.exists: { lastOp = "EXIS"; // TODO we need to figure out the security requirement for this! ExistsRequest existsRequest = new ExistsRequest(); ByteBufferInputStream.byteBuffer2Record(request.request, existsRequest); String path = existsRequest.getPath(); if (path.indexOf('\0') != -1) { throw new KeeperException.BadArgumentsException(); } Stat stat = zks.getZKDatabase().statNode(path, existsRequest .getWatch() ? cnxn : null); rsp = new ExistsResponse(stat); break; }
由於在3.1中已完成對事務型請求的處理,所以本階段中事務型請求無需再處理
如果是非事務型需要處理,通常就是操作一下datatree擷取資料
3.3.3)網路響應
ReplyHeader hdr = new ReplyHeader(request.cxid, request.zxid, err.intValue()); zks.serverStats().updateLatency(request.createTime); cnxn.updateStatsForResponse(request.cxid, request.zxid, lastOp, request.createTime, System.currentTimeMillis()); try { cnxn.sendResponse(hdr, rsp, "response"); if (closeSession) { cnxn.sendCloseSession(); } } catch (IOException e) { LOG.error("FIXMSG",e); }
構造一個ReplyHeader,並且響應見cnxn.sendResponse
3.4)snapshot產生時機及命名規則。
3.4.1)3個時機
載入的時候,用於merge快照和交易記錄
正如上面提到的SyncRequestProcessor線程當交易記錄多於一定數量且較空閑
follower線程接受到leader線程相關指令 3.4.2)命名規則
public static String makeSnapshotName(long zxid) { return "snaps