去中心化計算的未來:通過 RPC 從微服務過渡到 WASM

這篇文章將展示如何使用 Wasm 和 RPC 在 web 上執行與語言無關的通用代碼。

本文作者: Second State 的研究員、開源核心開發 Tim McCallum。


去中心化計算的未來:通過 RPC 從微服務過渡到 WASM

從瀏覽器內的角度來看,Wasm 最近的開發工作,理所當然地受到了廣泛好評。在上一篇 ,我們對 Rust 到 Wasm 的編譯以及簡單的瀏覽器內 Wasm 執行的案例做了演示。

在另外一篇文章 ,裡面有絕佳的瀏覽器內的 WASM 應用程序示例,並輔以了對WebAssembly(Wasm)的詳細解釋。

瀏覽器之外

Wasm 不僅僅是瀏覽器的字節碼。 Wasm 有著前所未有的強大的可移植性、高效率和靈活性。因此,我們現在可以做到,以多種不同語言編寫瀏覽器內 Wasm 應用程序,發展到在所有設備上分發 Wasm 獨立功能單元,在這一點上取得飛躍。

Wasm 執行環境可以包括最少的 shell、移動設備、臺式機和物聯網設備。Wasm 可能會推動從微芯片乃至整個數據中心,這所有一切的發展(Webassembly.org,2019)。

去中心化計算的未來:通過 RPC 從微服務過渡到 WASM

為什麼跨越瀏覽器很重要?


當連接到現代 Web 服務時,我們並非僅僅與一臺機器進行交互,而是持續和後臺可能數千臺機器進行交互( Arpaci-Dusseau 和Arpaci-Dusseau,2018 )。

網站越複雜,運營成本就越高。散佈在分佈式系統上的微服務需要盡最大可能做到簡單、高效和可靠。對於 Facebook、Google 這種大公司來說,這些特性意味著可以節省大量能耗,進而節省成本,促成積極成果。

除了這些能輕易做到的,我們還應該積極試驗,以找到方法來改善 Wasm 最終用戶/消費者體驗。 eBay 就是一個很好的例子。

利用 Wasm,eBay 最近很好地完善了其移動條形碼掃描儀的實現,恰到好處地為客戶提供了最優服務( Tech.ebayinc.com,2019)。

為什麼選 Wasm?

首先我們需要了解下“抽象化”。

雖然操作系統抽象化對於構建分佈式系統來說是一個糟糕的選擇,但編程語言抽象化卻更具意義。 (阿帕奇-杜索和阿帕奇-杜索,2018)。Wasm 作為從一開始就使用形式語義設計的第一種主流編程語言,進一步地提供了對現代硬件的抽象化的支持(Rossberg等,2018)。

Wasm 允許在最大量的源代碼語言中編寫和共享每個單個功能的邏輯。Wasm符合我們熟知的最佳軟件原則和慣例(DRY 和 KISS),並提供了必要時在所有設備之間轉換可執行代碼的方法。

為什麼要進行遠程過程調用(Remote Procedure Call)?

從進程間通信(IPC)角度來看,最主要的抽象化是基於遠程程序調用(Remote Procedure Call)的概念,簡稱 RPC。(Arpaci-Dusseau和Arpaci-Dusseau,2018)。

要實現這種分佈式機器之間普遍存在的互操作性,需要具備允許任何應用程序(以任何語言編寫)直接從任何其他分佈式機器調用服務的功能,就好像它只是調用自己的本地對象一樣。 這正是遠程過程調用 (RPC) 技術所實現的。

本文的目標是使用 Wasm 和 RPC 在 web 上執行與語言無關的通用代碼。

在下一節中,會講解如何:

  1. 編寫自定義的 Rust 代碼並編譯為 Wasm
  2. 設置 RPC 服務器
  3. 在 RPC 服務器上定義自定義服務
  4. 安裝 Wasm 虛擬機(WAVM)
  5. 通過 HTTP Post(即Curl,Python等)遠程執行自定義 WebAssembly(Wasm)代碼
去中心化計算的未來:通過 RPC 從微服務過渡到 WASM

1.編寫自定義的 Rust 代碼並編譯為 Wasm

安裝 Rust

<code>curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs (https://sh.rustup.rs/) | shsource $HOME/.cargo/env/<code>

創建新的 Rust 項目

<code>cd ~cargo new --lib add_numbers_via_wavmcd add_numbers_via_wavm/<code>

編輯 Cargo.toml 文件; 添加 lib 部分 ,同時也添加依賴項,如下所示

<code>[lib]name = "adding_lib"path = "src/adding.rs"crate-type =["cdylib"][dependencies]serde_json = "1.0"/<code>

在命令行中添加必要的 Wasm 軟件和配置

<code>rustup target add wasm32-wasirustup override set nightly/<code>

創建一個名為 ~/.cargo/config 的新文件。並將以下構建文本放入這個新創建的配置文件中。

<code>[build]target = "wasm32-wasi"/<code>

編寫一個我們可以調用的有不同的功能的定製的 Rust 程序。在下面的例子中,函數“ double”和“ triple” 會分別取一個整數並分別乘以 2 和 3。

<code>use serde_json::json;pub extern fn print(answer: i32){let the_answer = json!({"Result": answer});println!("{}", the_answer.to_string());}#[no_mangle]pub extern fn double(x: i32){let z = x * 2;print(z);}#[no_mangle]pub extern fn triple(x: i32){let z = x * 3;print(z);}/<code>

可以使用以下命令編譯上面的代碼

<code>cargo build --release/<code>


2. 設置 RPC 服務器

這裡給大家推薦一個簡潔的 C++ RPC 服務器,叫做 rpcsrv (鏈接:https://github.com/jgarzik/rpcsrv)。 我們要使用這個 C++ RPC 服務器來接受 HTTP POST 並通過 C++ 將它們轉換為系統調用。

<code>sudo apt-get updatesudo apt-get -y upgradesudo apt-get install autoconfsudo apt install libevent-2.1-6sudo apt-get install libevent-devsudo apt-get install libtoolcd ~git clone https://github.com/jgarzik/rpcsrv.gitcd ~/rpcsrvgit submodule update --init./autogen.sh./configuremakesudo make install/<code>

使用以下命令開啟 RPC 服務

<code>sudo ./rpcsrvd --listen-port 8080/<code>

3. 在 RPC 服務器上定義自定義服務

在我們進一步討論之前,我想簡單地討論一下 JSON 的使用。 我簡要地探索了一個關於單值的絕妙概念。 Univalue 是一個高性能的 RAII C++ JSON 庫和通用值對象類。我之後會找時間針對這個做徹底的研究。

方便起見,我結合使用了 UniValue 和 rapidjson 。 同樣,我也需要更多的時間來研究,來找到數據交換和互操作性的最佳方法,我們之後再進行討論。

下面的代碼用於安裝 rapidjson 。

<code>cd ~https://github.com/Tencent/rapidjson.gitcd ~/rapidjsongit submodule update --initmkdir buildcd ~/rapidjson/build/cmake ..sudo cp -rp ~/rapidjson/include/rapidjson /usr/include//<code>

在安裝 rapidjson 之後,我修改了原始 C++ API 文件(鏈接:https://github.com/jgarzik/rpcsrv/blob/master/src/myapi_1.cc),以便在 rpcsrvcodebase 中包含 rapidjson 功能。

<code>#include "rapidjson/document.h"#include "rapidjson/writer.h"#include "rapidjson/stringbuffer.h"#include <iostream>using namespace rapidjson;/<iostream>/<code>

在這個階段,我們可以繼續在 C++ 代碼中使用 rapidjson 功能。 下面是一個示例,演示如何修改修改原始 echo 函數(鏈接:https://github.com/jgarzik/rpcsrv/blob/master/src/myapi_1.cc#l38)

<code>//// RPC "echo"//static UniValue myapi_1_echo(const UniValue & jreq,  const UniValue & params) {  // Receive and parse incoming parameters  string s = params.write();  const char * theJson = s.c_str();  Document d;  d.Parse(theJson);  // Assign parameters to C++ variables and print to console  Value & theService = d["Service Name"];  Value & theType = d["Type"];  Value & theFunctionName = d["Execution"]["FunctionName"];  Value & theArgument = d["Execution"]["Argument"];  cout << endl;  cout << "Received a new request to execute a service on Wasm Virtual  Machine..." << endl;  cout << s.c_str() << endl;  cout << endl;  cout << "Service Name is: " << theService.GetString() << endl;  cout << "Service Type is: " << theType.GetString() << endl;  cout << "Wasm function is: " << theFunctionName.GetString() << endl;  cout << "Wasm function argument: " << theArgument.GetString() <<    endl;    // Construct and execute the call to Wasm Virtual Machine  string commandString = "wavm run --abi=wasi --function=";  commandString += theFunctionName.GetString();  commandString += " ";  commandString += "~/add_numbers_via_wavm/target/wasm32  wasi / release / adding_lib.wasm ";  commandString += " ";  commandString += theArgument.GetString();  cout << "\\n";  cout << "Executing command ... " << endl;  string theWasmResults =    execute_function_and_return_output(commandString);    // Print the result to console  cout << "Results are as follows ...: " << endl;  cout << theWasmResults << endl;  UniValue result(theWasmResults);  cout << "Finished." << endl;  // Return the results back to the caller of the RPC  return jrpcOk(jreq, result);}/<code>

4. 安裝Wasm 虛擬機(WAVM)

WAVM 使用 LLVM 將 WebAssembly 代碼編譯成機器代碼,其性能接近原生性能。

下面是安裝 WAVM的說明

<code>sudo apt-get install gccsudo apt-get install clang wget https://github.com/WAVM/WAVM/releases/download/nightly%2F2019-11-04/wavm-0.0.0-prerelease-linux.debsudo apt install ./wavm-0.0.0-prerelease-linux.deb/<code>

5. 通過 HTTP Post (即 Curl、 Python 等)遠程執行自定義 WebAssembly (Wasm) 代碼


執行可以由任何能夠生成 HTTP POST 的機制執行。 例如,從 Postman 這樣的 GUI 到 Linux curl 命令,當然還有像 Python 和 Javal 這樣的解釋和編譯代碼庫。

下面是在 linux 命令行中使用 Curl 的調用代碼示例

<strong>Curl - 傳入一段有效的JSON代碼

<code>tpmccallum$ curl --header "Content-Type: application/json" --request POST --data '{"jsonrpc":"2.0","method":"echo","params":{"Service Name": "Double the digits","Type": "Execution","Execution": {"FunctionName": "double","Argument": "10"}}, "id":1}' [http://123.456.78.9:8080/rpc/1](http://localhost:8080/rpc/1)/<code>

當查看這個調用代碼時,請記住 Rust 程序( Wasm 最早緣起於 Rust) 有兩個函數: “ double”和“ triple”。 增加的 RPC 層意味著這些原始函數現在被定義為兩個單獨的服務。

正如上面所看到的,我們不僅要指定想調用的服務,還要指定所需的單個參數。 當這個 POST 在 web 上執行時,RPC 服務器直接調用 WAVM,然後返回一個 JSON 結果對象給調用代碼。

<strong>返回有效的 JSON

<code>{ "jsonrpc": "2.0", "result": {  "Result": 20 }, "id": 1}/<code>

返回對象是完全可配置的,這只是一個返回計算結果的簡單示例。

<strong>RPC 服務器輸出

RPC 服務器輸出是可選的,這裡只是為了演示而創建的。 這裡演示了 RPC 服務器可以來回傳遞 JSON。其他格式也有機會內置到 RPC 層(位於 Rust 和 Wasm 代碼之上)。

<code>Received a new request to execute a service on Wasm Virtual Machine... {"Service Name":"Double the digits","Type":"Execution","Execution":{"FunctionName":"double","Argument":"10"}}Service Name is: Double the digitsService Type is: ExecutionWasm function is: doubleWasm function argument: 10Executing command ...Results are as follows ...:{"Result":20}Finished./<code>

<strong>Python - 傳入一段有效的JSON代碼

系統設置

<code>sudo apt-get install python-pippip install json-rpcpip install requests/<code>

我們將 Python 傳入一段有效的JSON代碼,描述我們需要哪種服務。 在這個例子中,我們希望將數字10翻一倍,即調用“ FunctionName” : “ double”和“ Argument” : “10”。

<code>>>>import requests>>>import json>>>url = "http://123.456.78.9:8080/rpc/1">>>payload = {    "jsonrpc":"2.0","method":"echo","params":{"Service Name":"Double the digits","Type": "Execution","Execution": {"FunctionName": "double","Argument": "10"}}, "id":1}>>>response = requests.post(url, json=payload).json()/<code>

現在我們可以看到,響應返回執行 Wasm 的結果,即“ Result” : 20。

<code>>>> print response{u'jsonrpc': u'2.0', u'result': u'{"Result":20}, u'id': 1}/<code>

我們調用另一個服務(即“ FunctionName” : “ triple” ,“ Argument” : “10”)再次嘗試這個方法

<code>>>>url = "http://123.456.78.9:8080/rpc/1">>>payload = {    "jsonrpc":"2.0","method":"echo","params":{"Service Name":"Triple the digits","Type": "Execution","Execution": {"FunctionName": "triple","Argument": "10"}}, "id":1}>>>response = requests.post(url, json=payload).json()/<code>

同樣,我們可以看到這個響應是所選服務的正確結果。

<code>>>> print response{u'jsonrpc': u'2.0', u'result': u'{"Result":30}', u'id': 1}/<code> 

本文通過 RPC 演示瞭如何使用 Wasm 。我是一名熱情的開源區塊鏈軟件研究人員,也是 SecondState 公司(在達拉斯、奧斯汀、北京和臺北設有辦公室)的核心開發。 如果你想了解更多關於 Wasm 和其他可以提升業務的技術,請關注我們喲。

參考文獻

  1. Arpaci-Dusseau, R.H. 和 Arpaci-Dusseau, A.C.,2018, 《操作系統:三個簡單的部分》, Arpaci-Dusseau Books LLC.
  2. Rossberg, A., Titzer, B., Haas, A., Schuff, D., Gohman, D., Wagner, L., Zakai, A., Bastien, J. 以及 Holman, M. (2018), 《使用 WebAssembly 加速網絡發展》, ACM通訊,107-115頁.
  3. Tech.ebayinc.com. (2019), eBay 上的 WebAssembly : 一個真實世界的案例, [在線資源] 可訪問: https://tech.ebayinc.com/engineering/webassembly-at-ebay-a-real-world-use-case/ [2019年11月20日訪問].


分享到:


相關文章: