WebAssembly 通用運行時 --Wasmer

Wasmer 支持基於 WebAssembly 的超輕量級容器,該容器可以在任何地方運行:從臺式機到雲和 IoT 設備,還可以以任何編程語言嵌入。

通過設計,WebAssembly 模塊運行所在的環境與基礎主機系統的本機功能完全隔離(或沙盒化)。這意味着默認情況下,Wasm 模塊被設計爲僅執行純計算。

因此,通常無法從 WASM 訪問 “OS” 級資源,例如文件描述符,網絡套接字,系統時鐘和隨機數。但是,在許多情況下,Wasm 模塊需要執行的工作不僅僅是執行純計算。它們必須與本機 “ OS” 功能交互。

Wasmer 旨在提供三個關鍵功能:

特點

Wasmer 目前 release 版本爲 0.17.1,不過 1.0.0-alpha02.0 版本已經發出來了,基本上準備生產就緒了。

生態

對比 wasmtime,其生態更加完善。提供了 wapmWebAssembly.sh

wapm 是 WebAssembly 包管理器。

WebAssembly shell 程序是一個在線 shell 程序,您可以在其中拖放 WebAssembly 模塊以進行嘗試,還可以執行 WAPM 中可用的 WASI 模塊的所有命令。

支持的語言

Wasmer 運行時可用作嵌入不同語言的庫,因此您可以在任何地方使用 WebAssembly。

目前支持以下語言:

安裝

官方提供了安裝腳本,整個安裝比較簡單:

curl https://get.wasmer.io -sSfL | sh
Installing Wasmer and WAPM!

               ww
               wwwww
        ww     wwwwww  w
        wwwww      wwwwwwwww
ww      wwwwww  w     wwwwwww
wwwww      wwwwwwwwww   wwwww
wwwwww  w      wwwwwww  wwwww
wwwwwwwwwwwwww   wwwww  wwwww
wwwwwwwwwwwwwww  wwwww  wwwww
wwwwwwwwwwwwwww  wwwww  wwwww
wwwwwwwwwwwwwww  wwwww  wwwww
wwwwwwwwwwwwwww  wwwww   wwww
wwwwwwwwwwwwwww  wwwww
   wwwwwwwwwwww   wwww
       wwwwwwww
           wwww

> Getting wasmer releases... ✓
> Downloading 0.17.1 release...
######################################################################## 100.0%-=#=#   #   #                                                   > Downloading 0.17.1 release... ✓####################################### 100.0%
> Unpacking contents... ✓
> Adding to bash profile... ✓
Note: We've added the following to your /Users/iyacontrol/.zshrc
If you have a different profile please add the following:

# Wasmer
export WASMER_DIR="/Users/iyacontrol/.wasmer"
[ -s "$WASMER_DIR/wasmer.sh" ] && source "$WASMER_DIR/wasmer.sh"

> Successfully installed wasmer 0.17.1!
wasmer & wapm will be available the next time you open the terminal.
If you want to have the commands available now please execute:
source /Users/iyacontrol/.wasmer/wasmer.sh

安裝完成,通過執行 wasmer 命令檢查一下:

wasmer
error: The following required arguments were not provided:
    <path>

USAGE:
    wasmer <path> --backend <backend>

For more information try --help

如果需要安裝指定版本的 wasmer,可以通過如下的方式安裝:

curl https://get.wasmer.io -sSfL | sh -s v0.17.0

Demo

rust 和 c/c++ 是目前支持 wasm 比較好的語言,所以本 demo 使用 rust 完成。

1:使用 cargo 新建 hello-world 工程:

cargo new hello-world
cd hello-world

3:編寫 main.rs 文件:

fn main() {
    println!("Hello, world!");
}

4:編譯:

cargo  build --target wasm32-wasi --release
   Compiling hello v0.1.0 (/Users/iyacontrol/rust/hello-world)
    Finished release [optimized] target(s) in 1.01s

本人 rust 版本爲最新版 1.46。已經支持wasm32-wasi類型。默認情況下,沒有安裝該 target 支持,所以需要運行以下 命令:

rustup target add wasm32-wasi

5:執行

我們側重點在 wasi 的執行,所以使用 wasmer 運行時,去執行編譯好的產物。

wasmer target/wasm32-wasi/release/hello-world.wasm
Hello, world!

總結

本文簡單從特性,生態等方面介紹了 wasmer。demo 示例屬於純計算案例,wasi 的更多意義在於和主機 os 交互,所以下一篇文章,我們會側重於這點。

本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://zhuanlan.zhihu.com/p/243210440