Protobuf自動反射訊息型別的網路傳輸方案

摩西2016發表於2018-06-20

轉載自http://www.cnblogs.com/Solstice/archive/2011/04/03/2004458.html

陳碩 (giantchen_AT_gmail)

Blog.csdn.net/Solstice  t.sina.com.cn/giantchen

這篇文章要解決的問題是:在接收到 protobuf 資料之後,如何自動建立具體的 Protobuf Message 物件,再做的反序列化。“自動”的意思是:當程式中新增一個 protobuf Message 型別時,這部分程式碼不需要修改,不需要自己去註冊訊息型別。其實,Google Protobuf 本身具有很強的反射(reflection)功能,可以根據 type name 建立具體型別的 Message 物件,我們直接利用即可。

本文假定讀者瞭解 Google Protocol Buffers 是什麼,這不是一篇 protobuf 入門教程。

本文以 C++ 語言舉例,其他語言估計有類似的解法,歡迎補充。

本文的示例程式碼在: https://github.com/chenshuo/recipes/tree/master/protobuf

網路程式設計中使用 protobuf 的兩個問題

Google Protocol Buffers (Protobuf) 是一款非常優秀的庫,它定義了一種緊湊的可擴充套件二進位制訊息格式,特別適合網路資料傳輸。它為多種語言提供 binding,大大方便了分散式程式的開發,讓系統不再侷限於用某一種語言來編寫。

在網路程式設計中使用 protobuf 需要解決兩個問題:

  • 長度,protobuf 打包的資料沒有自帶長度資訊或終結符,需要由應用程式自己在發生和接收的時候做正確的切分;
  • 型別,protobuf 打包的資料沒有自帶型別資訊,需要由傳送方把型別資訊傳給給接收方,接收方建立具體的 Protobuf Message 物件,再做的反序列化。

第一個很好解決,通常的做法是在每個訊息前面加個固定長度的 length header,例如我在 《Muduo 網路程式設計示例之二: Boost.Asio 的聊天伺服器》 中實現的 LengthHeaderCodec,程式碼見 http://code.google.com/p/muduo/source/browse/trunk/examples/asio/chat/codec.h

第二個問題其實也很好解決,Protobuf 對此有內建的支援。但是奇怪的是,從網上簡單搜尋的情況看,我發現了很多山寨的做法。

山寨做法

以下均為在 protobuf data 之前加上 header,header 中包含 int length 和型別資訊。型別資訊的山寨做法主要有兩種:

  • 在 header 中放 int typeId,接收方用 switch-case 來選擇對應的訊息型別和處理函式;
  • 在 header 中放 string typeName,接收方用 look-up table 來選擇對應的訊息型別和處理函式。

這兩種做法都有問題。

第一種做法要求保持 typeId 的唯一性,它和 protobuf message type 一一對應。如果 protobuf message 的使用範圍不廣,比如接收方和傳送方都是自己維護的程式,那麼 typeId 的唯一性不難保證,用版本管理工具即可。如果 protobuf message 的使用範圍很大,比如全公司都在用,而且不同部門開發的分散式程式可能相互通訊,那麼就需要一個公司內部的全域性機構來分配 typeId,每次增加新 message type 都要去註冊一下,比較麻煩。

第二種做法稍好一點。typeName 的唯一性比較好辦,因為可以加上 package name(也就是用 message 的 fully qualified type name),各個部門事先分好 namespace,不會衝突與重複。但是每次新增訊息型別的時候都要去手工修改 look-up table 的初始化程式碼,比較麻煩。

其實,不需要自己重新發明輪子,protobuf 本身已經自帶了解決方案。

根據 type name 反射自動建立 Message 物件

Google Protobuf 本身具有很強的反射(reflection)功能,可以根據 type name 建立具體型別的 Message 物件。但是奇怪的是,其官方教程裡沒有明確提及這個用法,我估計還有很多人不知道這個用法,所以覺得值得寫這篇 blog 談一談。

以下是陳碩繪製的 Protobuf  class diagram,點選檢視原圖

protobuf_classdiagram

我估計大家通常關心和使用的是圖的左半部分:MessageLite、Message、Generated Message Types (Person, AddressBook) 等,而較少注意到圖的右半部分:Descriptor, DescriptorPool, MessageFactory。

上圖中,其關鍵作用的是 Descriptor class,每個具體 Message Type 對應一個 Descriptor 物件。儘管我們沒有直接呼叫它的函式,但是Descriptor在“根據 type name 建立具體型別的 Message 物件”中扮演了重要的角色,起了橋樑作用。上圖的紅色箭頭描述了根據 type name 建立具體 Message 物件的過程,後文會詳細介紹。

原理簡述

Protobuf Message class 採用了 prototype pattern,Message class 定義了 New() 虛擬函式,用以返回本物件的一份新例項,型別與本物件的真實型別相同。也就是說,拿到 Message* 指標,不用知道它的具體型別,就能建立和它型別一樣的具體 Message Type 的物件。

每個具體 Message Type 都有一個 default instance,可以通過 ConcreteMessage::default_instance() 獲得,也可以通過 MessageFactory::GetPrototype(const Descriptor*) 來獲得。所以,現在問題轉變為 1. 如何拿到 MessageFactory;2. 如何拿到 Descriptor*。

當然,ConcreteMessage::descriptor() 返回了我們想要的 Descriptor*,但是,在不知道 ConcreteMessage 的時候,如何呼叫它的靜態成員函式呢?這似乎是個雞與蛋的問題。

我們的英雄是 DescriptorPool,它可以根據 type name 查到 Descriptor*,只要找到合適的 DescriptorPool,再呼叫 DescriptorPool::FindMessageTypeByName(const string& type_name) 即可。眼前一亮?

在最終解決問題之前,先簡單測試一下,看看我上面說的對不對。

簡單測試

本文用於舉例的 proto 檔案:query.proto,見 https://github.com/chenshuo/recipes/blob/master/protobuf/query.proto

package muduo;

message Query {
  required int64 id = 1;
  required string questioner = 2;

  repeated string question = 3;
}

message Answer {
  required int64 id = 1;
  required string questioner = 2;
  required string answerer = 3;

  repeated string solution = 4;
}

message Empty {
  optional int32 id = 1;
}
其中的 Query.questioner 和 Answer.answerer 是我在前一篇文章這提到的《分散式系統中的程式標識》。

以下程式碼驗證 ConcreteMessage::default_instance()、ConcreteMessage::descriptor()、 MessageFactory::GetPrototype()、DescriptorPool::FindMessageTypeByName() 之間的不變式 (invariant):

https://github.com/chenshuo/recipes/blob/master/protobuf/descriptor_test.cc#L15

  typedef muduo::Query T;

  std::string type_name = T::descriptor()->full_name();
  cout << type_name << endl;

  const Descriptor* descriptor = DescriptorPool::generated_pool()->FindMessageTypeByName(type_name);
  assert(descriptor == T::descriptor());
  cout << "FindMessageTypeByName() = " << descriptor << endl;
  cout << "T::descriptor()         = " << T::descriptor() << endl;
  cout << endl;

  const Message* prototype = MessageFactory::generated_factory()->GetPrototype(descriptor);
  assert(prototype == &T::default_instance());
  cout << "GetPrototype()        = " << prototype << endl;
  cout << "T::default_instance() = " << &T::default_instance() << endl;
  cout << endl;

  T* new_obj = dynamic_cast<T*>(prototype->New());
  assert(new_obj != NULL);
  assert(new_obj != prototype);
  assert(typeid(*new_obj) == typeid(T::default_instance()));
  cout << "prototype->New() = " << new_obj << endl;
  cout << endl;
  delete new_obj;

根據 type name 自動建立 Message 的關鍵程式碼

好了,萬事具備,開始行動:

  1. 用 DescriptorPool::generated_pool() 找到一個 DescriptorPool 物件,它包含了程式編譯的時候所連結的全部 protobuf Message types
  2. 用 DescriptorPool::FindMessageTypeByName() 根據 type name 查詢 Descriptor。
  3. 再用 MessageFactory::generated_factory() 找到 MessageFactory 物件,它能建立程式編譯的時候所連結的全部 protobuf Message types。
  4. 然後,用 MessageFactory::GetPrototype() 找到具體 Message Type 的 default instance。
  5. 最後,用 prototype->New() 建立物件。

示例程式碼見 https://github.com/chenshuo/recipes/blob/master/protobuf/codec.h#L69

Message* createMessage(const std::string& typeName)
{
  Message* message = NULL;
  const Descriptor* descriptor = DescriptorPool::generated_pool()->FindMessageTypeByName(typeName);
  if (descriptor)
  {
    const Message* prototype = MessageFactory::generated_factory()->GetPrototype(descriptor);
    if (prototype)
    {
      message = prototype->New();
    }
  }
  return message;
}

呼叫方式:https://github.com/chenshuo/recipes/blob/master/protobuf/descriptor_test.cc#L49

  Message* newQuery = createMessage("muduo.Query");
  assert(newQuery != NULL);
  assert(typeid(*newQuery) == typeid(muduo::Query::default_instance()));
  cout << "createMessage(\"muduo.Query\") = " << newQuery << endl;

古之人不餘欺也 :-)

注意,createMessage() 返回的是動態建立的物件的指標,呼叫方有責任釋放它,不然就會記憶體洩露。在 muduo 裡,我用 shared_ptr<Message> 來自動管理 Message 物件的生命期。

執行緒安全性

Google 的文件說,我們用到的那幾個 MessageFactory 和 DescriptorPool 都是執行緒安全的,Message::New() 也是執行緒安全的。並且它們都是 const member function。

關鍵問題解決了,那麼剩下工作就是設計一種包含長度和訊息型別的 protobuf 傳輸格式

Protobuf 傳輸格式

陳碩設計了一個簡單的格式,包含 protobuf data 和它對應的長度與型別資訊,訊息的末尾還有一個 check sum。格式如下圖,圖中方塊的寬度是 32-bit。

protobuf_wireformat1

用 C struct 虛擬碼描述:

 struct ProtobufTransportFormat __attribute__ ((__packed__))
 {
   int32_t  len;
   int32_t  nameLen;
   char     typeName[nameLen];
   char     protobufData[len-nameLen-8];
   int32_t  checkSum; // adler32 of nameLen, typeName and protobufData
 };
注意,這個格式不要求 32-bit 對齊,我們的 decoder 會自動處理非對齊的訊息。

例子

用這個格式打包一個 muduo.Query 物件的結果是:

protobuf_wireexample

設計決策

以下是我在設計這個傳輸格式時的考慮:

  • signed int。訊息中的長度欄位只使用了 signed 32-bit int,而沒有使用 unsigned int,這是為了移植性,因為 Java 語言沒有 unsigned 型別。另外 Protobuf 一般用於打包小於 1M 的資料,unsigned int 也沒用。
  • check sum。雖然 TCP 是可靠傳輸協議,雖然 Ethernet 有 CRC-32 校驗,但是網路傳輸必須要考慮資料損壞的情況,對於關鍵的網路應用,check sum 是必不可少的。對於 protobuf 這種緊湊的二進位制格式而言,肉眼看不出資料有沒有問題,需要用 check sum。
  • adler32 演算法。我沒有選用常見的 CRC-32,而是選用 adler32,因為它計算量小、速度比較快,強度和 CRC-32差不多。另外,zlib 和 java.unit.zip 都直接支援這個演算法,不用我們自己實現。
  • type name 以 ‘\0’ 結束。這是為了方便 troubleshooting,比如通過 tcpdump 抓下來的包可以用肉眼很容易看出 type name,而不用根據 nameLen 去一個個數字節。同時,為了方便接收方處理,加入了 nameLen,節省 strlen(),空間換時間。
  • 沒有版本號。Protobuf Message 的一個突出優點是用 optional fields 來避免協議的版本號(凡是在 protobuf Message 裡放版本號的人都沒有理解 protobuf 的設計),讓通訊雙方的程式能各自升級,便於系統演化。如果我設計的這個傳輸格式又把版本號加進去,那就畫蛇添足了。具體請見本人《分散式系統的工程化開發方法》第 57 頁:訊息格式的選擇。

示例程式碼

為了簡單起見,採用 std::string 來作為打包的產物,僅為示例。

打包 encode 的程式碼:https://github.com/chenshuo/recipes/blob/master/protobuf/codec.h#L35

解包 decode 的程式碼:https://github.com/chenshuo/recipes/blob/master/protobuf/codec.h#L99

測試程式碼: https://github.com/chenshuo/recipes/blob/master/protobuf/codec_test.cc

如果以上程式碼編譯通過,但是在執行時出現“cannot open shared object file”錯誤,一般可以用 sudo ldconfig 解決,前提是 libprotobuf.so 位於 /usr/local/lib,且 /etc/ld.so.conf 列出了這個目錄。

$ make all # 如果你安裝了 boost,可以 make whole

$ ./codec_test
./codec_test: error while loading shared libraries: libprotobuf.so.6: cannot open shared object file: No such file or directory

$ sudo ldconfig

與 muduo 整合

muduo 網路庫將會整合對本文所述傳輸格式的支援(預計 0.1.9 版本),我會另外寫一篇短文介紹 Protobuf Message <=> muduo::net::Buffer 的相互轉化,使用 muduo::net::Buffer 來打包比上面 std::string 的程式碼還簡單,它是專門為 non-blocking 網路庫設計的 buffer class。

此外,我們可以寫一個 codec 來自動完成轉換,就行 asio/char/codec.h 那樣。這樣客戶程式碼直接收到的就是 Message 物件,傳送的時候也直接傳送 Message 物件,而不需要和 Buffer 物件打交道。

訊息的分發 (dispatching)

目前我們已經解決了訊息的自動建立,在網路程式設計中,還有一個常見任務是把不同型別的 Message 分發給不同的處理函式,這同樣可以藉助 Descriptor 來完成。我在 muduo 裡實現了 ProtobufDispatcherLite 和 ProtobufDispatcher 兩個分發器,使用者可以自己註冊針對不同訊息型別的處理函式。預計將會在 0.1.9 版本釋出,您可以先睹為快:

初級版,使用者需要自己做 down casting: https://github.com/chenshuo/recipes/blob/master/protobuf/dispatcher_lite.cc

高階版,使用模板技巧,節省使用者打字: https://github.com/chenshuo/recipes/blob/master/protobuf/dispatcher.cc

基於 muduo 的 Protobuf RPC?

Google Protobuf 還支援 RPC,可惜它只提供了一個框架,沒有開源網路相關的程式碼,muduo 正好可以填補這一空白。我目前還沒有決定是不是讓 muduo 也支援以 protobuf message 為訊息格式的 RPC,muduo 還有很多事情要做,我也有很多部落格文章打算寫,RPC 這件事情以後再說吧。

注:Remote Procedure Call (RPC) 有廣義和狹義兩種意思。狹義的講,一般特指 ONC RPC,就是用來實現 NFS 的那個東西;廣義的講,“以函式呼叫之名,行網路通訊之實”都可以叫 RPC,比如 Java RMI,.Net Remoting,Apache Thriftlibevent RPC,XML-RPC 等等。

(待續)

相關文章