如何把自定义过滤函数编译为 WASM 在 Memcached 中运行?
解读
面试官并非在问“Memcached 原生是否支持 WASM”,而是考察候选人能否把实验性扩展能力与国内生产环境可落地性结合起来。
国内大厂(阿里、字节、腾讯)自研的 Memcached 分支已把 extstore + 插件机制 作为标配,WASM 被用来解决“热升级逻辑而不重启进程”的痛点。
因此,回答要围绕三条主线:
- 让面试官确信你理解 Memcached 的 协议解析与 Worker 线程模型;
- 给出 从 C/C++/Rust 源码到 .wasm 的完整编译链路,并说明如何嵌入;
- 用 灰度、回滚、热更新 的国内运维语言收尾,体现可运维性。
知识点
- Memcached 多线程模型:主线程 accept,Worker 线程通过 CQ(Connection Queue) 处理命令,插件钩子点在 process_command() 之后、item_alloc() 之前。
- WASM 运行时选择:国内生产环境普遍采用 WasmEdge 或 Wasmtime 的 C API,因为许可证友好、支持 AOT 编译,内存隔离与 CPU 配额可控。
- 编译工具链:
- C/C++:使用 wasi-sdk (clang-16),加
-O3 -flto --target=wasm32-wasi生成 .wasm; - Rust:用
cargo wasi --release,在Cargo.toml里开启 panic=abort 与 lto=true 减小体积。
- C/C++:使用 wasi-sdk (clang-16),加
- 嵌入流程:
- 在 memcached 的 extstore_module 结构体新增
wasm_filter_t成员; - 启动时
wasm_runtime_init(),把 .wasm 文件 mmap 到 不可执行匿名内存,再wasm_runtime_load(); - 每条 get/set 命令经过时,把 key、flag、expire 打包成 protobuf 小对象,通过
wasm_runtime_call("filter")调用; - 返回值 0 表示放行,非 0 表示丢弃并回送 CLIENT_ERROR filtered。
- 在 memcached 的 extstore_module 结构体新增
- 性能与稳定性:
- 使用 AOT 编译缓存(.so.mapped)把 WASM 预编译成 native code,QPS 损耗 < 3%;
- 通过 memory.grow 上限 64 KB 防止 OOM;
- 国内机房常用 ** cgroup + memfd** 做双层硬限,WasmEdge 的 fuel 机制 可精确到指令级熔断。
- 灰度与回滚:
- 把 .wasm 版本号写进 x-mc-wasm-version 响应头,接入 ARM 蓝绿发布平台;
- 若命中率下降或 p99 延迟 > 5 ms,通过 配置中心秒级切换 回滚到空函数,实现 热回滚零重启。
答案
步骤一:代码实现
以 Rust 为例,新建 filter/src/lib.rs:
#[no_mangle]
pub extern "C" fn filter(key_ptr: *const u8, key_len: usize, flags: u32) -> i32 {
let key = unsafe { std::slice::from_raw_parts(key_ptr, key_len) };
// 国内内容安全场景:过滤敏感词
if key.starts_with(b"ad_") && flags & 0x01 == 0 {
return -1; // 丢弃
}
0
}
Cargo.toml 加:
[lib]
crate-type = ["cdylib"]
[profile.release]
panic = "abort"
lto = true
执行:
cargo install cargo-wasi
cargo wasi build --release
得到 target/wasm32-wasi/release/filter.wasm,体积 < 20 KB。
步骤二:嵌入 Memcached
在 memcached-1.6.x 的 wasm_filter.c 中:
static wasm_filter_t g_filter;
void wasm_filter_init(const char *path) {
wasm_runtime_init();
int fd = open(path, O_RDONLY);
struct stat st;
fstat(fd, &st);
void *buf = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
g_filter.module = wasm_runtime_load(buf, st.st_size, NULL, 0);
g_filter.inst = wasm_runtime_instantiate(g_filter.module, 64*1024);
}
int wasm_filter_run(const char *key, size_t nkey, uint32_t flags) {
wasm_function_inst_t func = wasm_runtime_lookup_function(g_filter.inst, "filter");
wasm_val_t args[3] = {
{.kind = WASM_I32, .of.i32 = (int32_t)(uintptr_t)key},
{.kind = WASM_I32, .of.i32 = (int32_t)nkey},
{.kind = WASM_I32, .of.i32 = (int32_t)flags}
};
wasm_val_t result;
wasm_runtime_call(g_filter.inst, func, 3, args, 1, &result);
return result.of.i32;
}
在 process_get_command() 里加:
if (wasm_filter_run(c->item_key, c->item_nkey, c->item_flags) != 0) {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_EFILTER, 0);
return;
}
步骤三:上线与监控
- 把
filter.wasm打进 Docker 镜像,通过 K8s ConfigMap 挂载; - 在 Prometheus 暴露
mc_wasm_filter_reject_total指标,Grafana 大盘联动告警; - 利用 WasmEdge 的 fuel 机制 设置单请求 200 万指令上限,超限时返回 SERVER_ERROR wasm_trap,防止死循环。
拓展思考
- 若 WASM 函数需要 访问全局黑名单,可把黑名单做成 只读 Memory Segment,通过
wasm_runtime_register_shared_memory()映射到多个实例,节省 30% 内存。 - 国内 信创场景 要求 ARM 架构,WasmEdge 提供 aarch64 AOT 后端,编译命令加
--target aarch64-unknown-linux-gnu即可,性能损耗 < 2%。 - 未来可把 WASM 当作“缓存侧车”,在 DPDK 用户态驱动 里直接过滤,绕过内核协议栈,实现 单核 10 Mqps 的缓存防火墙,这也是国内云厂商的 下一代 Service Mesh 数据面 方向。