Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> 關於Linux

用自定義 Python 函數搞定 Protobuf 字符串的混合編碼難題

我目前參與的是一個老項目,裡面的字符串編碼頗為混亂:數據庫裡有些是 GB2312,有些是 UTF8;代碼中 likewise 摻雜著 GBK 與 UTF8,轉來轉去,常常搞不清當前的字符串究竟是什麼編碼。由於是老項目,也就一直沒去動它。最近合服腳本改由項目組維護,我拿到腳本一看是 Python 寫的,而自己此前並未學過 Python,只能現學現用。

數據庫裡用到了 Protobuf,其中也存著字符串,編碼同樣 GBK 與 UTF8 混用、交叉出現。有過合服經驗的同學都懂,這裡往往涉及改名等操作,比如名字衝突時需要修改,而修改 Protobuf 裡的名字就得先解析出來、改好後再序列化回去。問題恰恰出在這裡:Protobuf 默認使用 UTF8 進行解析(Decode)與序列化(Encode),可參見 google.protobuf.internal 中 decoder.py 的函數:

 def StringDecoder(field_number, is_repeated, is_packed, key, new_default):
     local_DecodeVarint = _DecodeVarint
     local_unicode = unicode
     assert not is_packed
     if is_repeated:
         ...
         value.append(local_unicode(buffer[pos:new_pos], 'utf-8'))
         ...
     else:
         def DecodeField(buffer, pos, end, message, field_dict):
             (size, pos) = local_DecodeVarint(buffer, pos)
             new_pos = pos + size
             if new_pos > end:
                 raise _DecodeError('Truncated string.')
             field_dict[key] = local_unicode(buffer[pos:new_pos], 'utf-8')
             return new_pos
         return DecodeField

以及 encoder.py 中的函數:

 def StringEncoder(field_number, is_repeated, is_packed):
     tag = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED)
     ...
     else:
         def EncodeField(write, value):
             encoded = value.encode('utf-8')
             write(tag)
             local_EncodeVarint(write, local_len(encoded))
             return write(encoded)
         return EncodeField

如果 Protobuf 中的字符串編碼並非 UTF8,那麼解析過程就會拋出異常(奇怪的是,同事的電腦上卻沒出現):'utf8' codec can't decode byte……

於是我首先想到的是:有沒有可能在不改動 Protobuf 原有代碼的前提下,用自己的函數來解析?惡補了一通 Python 基礎後,我發現 Protobuf 把 Decode 的函數入口放在了一個數組裡,引入模塊時便自動初始化這些入口,再保存到各個 Protobuf 類中——每個 PB 類都有一個 decoders_by_tag 字典,存放著各種數據類型的解析函數入口。

從上面的代碼可以看出,具體的解析函數(DecodeField)被放在閉包中,無法直接修改,因此只能整個替換 StringDecoder。深入研究後,我終於找到了它設置入口的地方。在 google.protobuf.internal 的 type_checkers.py 中有這樣一段代碼:

 TYPE_TO_ENCODER = { ... _FieldDescriptor.TYPE_STRING: encoder.StringEncoder, ... }
 TYPE_TO_SIZER = { ... _FieldDescriptor.TYPE_STRING: encoder.StringSizer, ... }
 TYPE_TO_DECODER = { ... _FieldDescriptor.TYPE_STRING: decoder.StringDecoder, ... }

第一個是序列化(Encoder)的函數入口,第二個是計算大小的函數入口,第三個則是解析(Decoder)的入口。這裡映射了所有類型的處理函數,只要把這些入口替換成我們自己的函數,就能按實際需要進行處理了。

這裡要特別注意:Protobuf 的各個類都是在模塊導入時就初始化好的,因此若要修改入口函數,必須在 PB 各類被引入之前完成。為此我寫了一個模塊文件 protobuf_hack.py,它必須先於 PB 類被 import,內容如下:

 from google.protobuf.internal import decoder
 from google.protobuf.internal import encoder
 from google.protobuf.internal import wire_format
 from google.protobuf.internal import type_checkers
 from google.protobuf import reflection
 from google.protobuf import message
 def StringDecoder(field_number, is_repeated, is_packed, key, new_default):
     local_DecodeVarint = decoder._DecodeVarint
     local_unicode = unicode
     ...
     field_dict[key] = local_unicode(buffer[pos:new_pos], 'gbk')
     ...
 type_checkers.TYPE_TO_DECODER[type_checkers._FieldDescriptor.TYPE_STRING] = StringDecoder

如此一來,所有 PB 中的字符串都會按 GBK 解析了。但項目裡的字符串並非全是 GBK,也有 UTF8,為兼容兩種編碼,我做了個處理:先用一種編碼嘗試解析,若拋異常再換另一種,這樣便能保證所有字符串都被正確解析。理想很豐滿,現實卻很骨感——解析是對了,可序列化回去、在服務器程序中使用的時候卻出現亂碼,因為原來的 GBK 或 UTF8 已被統一成了 UTF8。當然,我們也可以像 Decoder 那樣為 Encoder 自定義函數,但問題是 Encoder 裡並不知道這個字符串原在數據庫中是什麼編碼,也拿不到 PB 及字段信息,無法差別處理。

至此,算是白忙一場,仍無法滿足需求。

如果我們能只修改指定 PB 類的處理函數就好了,因為我們清楚哪些 PB 的字符串是 GBK 編碼的。再次深入研究,總算做到了。這裡有一個函數幫了大忙——reflection.py 中的 ParseMessage:

 def ParseMessage(descriptor, byte_str):
     class _ResultClass(message.Message):
         __metaclass__ = GeneratedProtocolMessageType
         DESCRIPTOR = descriptor
     new_msg = _ResultClass()
     new_msg.ParseFromString(byte_str)
     return new_msg

這個函數本質上是依據描述符(descriptor)解析二進制串,生成一個新的 PB 消息實例。關鍵就在那段動態生成類實例的代碼——它會走一次 PB 類的初始化流程,也就是初始化我們所需的 Decoder 與 Encoder 映射字典。為工作需要,我把它改了一下:

 def ParseMessage(descriptor):
     class _ResultClass(message.Message):
         __metaclass__ = reflection.GeneratedProtocolMessageType
         DESCRIPTOR = descriptor
     new_msg = _ResultClass()
     return new_msg

然後加入需要用自定義函數處理的 PB 類(注意這裡一定要是最小的 PB 結構):

 def hacker(msg):
     ParseMessage(msg.DESCRIPTOR)
 def hack_pb():
     #修改默認的字符串處理函數入口為自定義函數
     type_checkers.TYPE_TO_DECODER[type_checkers._FieldDescriptor.TYPE_STRING] = StringDecoder
     type_checkers.TYPE_TO_ENCODER[type_checkers._FieldDescriptor.TYPE_STRING] = StringEncoder
     type_checkers.TYPE_TO_SIZER[type_checkers._FieldDescriptor.TYPE_STRING] = StringSizer
     try:
         # 這裡加入我們需要修改的 PB 類
         hacker(DbProto.DB_FriendAssetEntry_PB)
     except Exception as e:
         print(e)
     #還原字符串處理函數入口
     type_checkers.TYPE_TO_DECODER[type_checkers._FieldDescriptor.TYPE_STRING] = decoder.StringDecoder
     type_checkers.TYPE_TO_ENCODER[type_checkers._FieldDescriptor.TYPE_STRING] = encoder.StringEncoder
     type_checkers.TYPE_TO_SIZER[type_checkers._FieldDescriptor.TYPE_STRING] = encoder.StringSizer

由於 Encode 時 Protobuf 會先計算字段長度、再逐個處理,所以我們還得把計算大小的函數也換成自定義版本,否則再次解析會出錯。

至此基本滿足了需求,算是大功告成!不過細心的讀者想必發現了一個目前仍無解的問題:如果一個最小的 PB 裡有兩個字符串字段、且採用了不同編碼,該怎麼辦?正常設計者不會這麼做,但正如我們項目裡的編碼混亂一樣,一旦不小心搞成不同編碼就悲劇了。若哪位高手有解法,歡迎分享!

完整文件如下:

 from google.protobuf.internal import decoder
 from google.protobuf.internal import encoder
 from google.protobuf.internal import wire_format
 from google.protobuf.internal import type_checkers
 from google.protobuf import reflection
 from google.protobuf import message
 def StringDecoder(field_number, is_repeated, is_packed, key, new_default):
     local_DecodeVarint = decoder._DecodeVarint
     local_unicode = unicode
     ...
     #這裡先嘗試使用 UTF8 編碼進行解析,如果出現異常則嘗試使用 GBK 編碼解析
     try:
         str = local_unicode(buffer[pos:new_pos], 'utf-8')
     except Exception as e:
         try:
             str = local_unicode(buffer[pos:new_pos], 'gbk')
         except Exception as e1:
             str = ''
     ...
 def StringEncoder(field_number, is_repeated, is_packed):
     ...
     encoded = value.encode('gbk')  #序列化的時候就直接使用 GBK 編碼了
     ...
 def StringSizer(field_number, is_repeated, is_packed):
     ...
     l = local_len(value.encode('gbk'))  #注意序列化前計算長度時也需要使用與序列化相同的編碼,否則會出錯
     ...
 def ParseMessage(descriptor):
     class _ResultClass(message.Message):
         __metaclass__ = reflection.GeneratedProtocolMessageType
         DESCRIPTOR = descriptor
     new_msg = _ResultClass()
     return new_msg
 def hacker(msg):
     ParseMessage(msg.DESCRIPTOR)
 def hack_pb():
     type_checkers.TYPE_TO_DECODER[type_checkers._FieldDescriptor.TYPE_STRING] = StringDecoder
     type_checkers.TYPE_TO_ENCODER[type_checkers._FieldDescriptor.TYPE_STRING] = StringEncoder
     type_checkers.TYPE_TO_SIZER[type_checkers._FieldDescriptor.TYPE_STRING] = StringSizer
     try:
         hacker(DbProto.DB_FriendAssetEntry_PB)
     except Exception as e:
         print(e)
     type_checkers.TYPE_TO_DECODER[type_checkers._FieldDescriptor.TYPE_STRING] = decoder.StringDecoder
     type_checkers.TYPE_TO_ENCODER[type_checkers._FieldDescriptor.TYPE_STRING] = encoder.StringEncoder
     type_checkers.TYPE_TO_SIZER[type_checkers._FieldDescriptor.TYPE_STRING] = encoder.StringSizer
 #這裡讓其在引入模塊時自動執行
 hack_pb()
Copyright © Linux教程網 All Rights Reserved